import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { PNG } from 'pngjs';
import { SandboxViolationError } from '../sandbox.js';

describe('baselines', () => {
  let tmpDir: string;
  let originalRoot: string;

  beforeEach(async () => {
    tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'web-dev-mcp-baselines-'));
    const config = await import('../../config.js');
    originalRoot = config.config.workspaceRoot;
    (config.config as { workspaceRoot: string }).workspaceRoot = tmpDir;
  });

  afterEach(async () => {
    const config = await import('../../config.js');
    (config.config as { workspaceRoot: string }).workspaceRoot = originalRoot;
    fs.rmSync(tmpDir, { recursive: true, force: true });
  });

  it('writes and reads a baseline round-trip', async () => {
    const { writeBaseline, readBaseline, listBaselines } = await import('../baselines.js');
    const png = PNG.sync.write(new PNG({ width: 2, height: 2 }));
    const saved = writeBaseline('home', png);
    expect(saved.relativePath.replace(/\\/g, '/')).toBe('.web-dev-mcp/baselines/home.png');
    expect(Buffer.compare(readBaseline('home'), png)).toBe(0);
    expect(listBaselines()).toContain('home.png');
  });

  it('rejects path-like baseline names', async () => {
    const { writeBaseline } = await import('../baselines.js');
    const png = PNG.sync.write(new PNG({ width: 1, height: 1 }));
    expect(() => writeBaseline('../escape', png)).toThrow(SandboxViolationError);
    expect(() => writeBaseline('a/b', png)).toThrow(SandboxViolationError);
  });
});
