import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, mkdirSync, readFileSync, existsSync, readdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { saveRawData, RAW_SAVE_TOOLS, generateRawFilename } from './raw-save.js';

describe('raw-save', () => {
  let tempDir: string;

  beforeEach(() => {
    tempDir = mkdtempSync(join(tmpdir(), 'raw-save-test-'));
    mkdirSync(join(tempDir, 'logs'), { recursive: true });
  });

  afterEach(() => {
    rmSync(tempDir, { recursive: true, force: true });
  });

  it('saves text data to logs/raw/', () => {
    saveRawData(tempDir, 'WebFetch', 'Hello World');
    const rawDir = join(tempDir, 'logs', 'raw');
    expect(existsSync(rawDir)).toBe(true);
    const files = readdirSync(rawDir) as string[];
    expect(files.length).toBe(1);
    expect(files[0]).toMatch(/^webfetch-\d{8}-\d{6}-\d{3}\.txt$/);
    expect(readFileSync(join(rawDir, files[0]), 'utf-8')).toBe('Hello World');
  });

  it('appends to rawdata-history.jsonl', () => {
    saveRawData(tempDir, 'XSearch', 'search results');
    const historyPath = join(tempDir, 'logs', 'rawdata-history.jsonl');
    expect(existsSync(historyPath)).toBe(true);
    const entry = JSON.parse(readFileSync(historyPath, 'utf-8').trim());
    expect(entry.tool).toBe('XSearch');
    expect(entry.filename).toMatch(/^xsearch-/);
    expect(entry.bytes).toBeGreaterThan(0);
  });

  it('does not save for non-target tools', () => {
    saveRawData(tempDir, 'Read', 'file contents');
    const rawDir = join(tempDir, 'logs', 'raw');
    expect(existsSync(rawDir)).toBe(false);
  });

  it('generates correct filename format', () => {
    const name = generateRawFilename('WebFetch', '.txt');
    expect(name).toMatch(/^webfetch-\d{8}-\d{6}-\d{3}\.txt$/);
  });

  it('RAW_SAVE_TOOLS contains expected tools', () => {
    expect(RAW_SAVE_TOOLS.has('WebFetch')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('WebSearch')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('XSearch')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('XUserPosts')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('XPostDetail')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('BrowseWeb')).toBe(true);
    expect(RAW_SAVE_TOOLS.has('Read')).toBe(false);
  });
});
