import fs from 'node:fs';
import path from 'node:path';
import { config } from '../config.js';
import { resolveWorkspacePath, SandboxViolationError } from './sandbox.js';
const BASELINES_DIR = path.join('.web-dev-mcp', 'baselines');
function sanitizeBaselineName(name) {
    const trimmed = name.trim();
    if (!trimmed) {
        throw new SandboxViolationError('Baseline name must be a non-empty string.');
    }
    if (trimmed.includes('..') || trimmed.includes('/') || trimmed.includes('\\') || trimmed.includes(':')) {
        throw new SandboxViolationError(`Invalid baseline name "${name}": use a simple name without path separators or "..".`);
    }
    return trimmed.endsWith('.png') ? trimmed : `${trimmed}.png`;
}
export function resolveBaselinePath(name) {
    const fileName = sanitizeBaselineName(name);
    const relative = path.join(BASELINES_DIR, fileName);
    return resolveWorkspacePath(config.workspaceRoot, relative);
}
export function ensureBaselinesDir() {
    const dir = resolveWorkspacePath(config.workspaceRoot, BASELINES_DIR);
    fs.mkdirSync(dir, { recursive: true });
    return dir;
}
export function writeBaseline(name, png) {
    ensureBaselinesDir();
    const absolutePath = resolveBaselinePath(name);
    fs.writeFileSync(absolutePath, png);
    return {
        absolutePath,
        relativePath: path.relative(config.workspaceRoot, absolutePath),
    };
}
export function readBaseline(name) {
    const absolutePath = resolveBaselinePath(name);
    if (!fs.existsSync(absolutePath)) {
        throw new Error(`Baseline not found at "${path.relative(config.workspaceRoot, absolutePath)}". ` +
            'Capture one first with browser_screenshot_baseline.');
    }
    return fs.readFileSync(absolutePath);
}
export function listBaselines() {
    const dir = resolveWorkspacePath(config.workspaceRoot, BASELINES_DIR);
    if (!fs.existsSync(dir))
        return [];
    return fs
        .readdirSync(dir)
        .filter((entry) => entry.toLowerCase().endsWith('.png'))
        .sort();
}
//# sourceMappingURL=baselines.js.map