import { existsSync, readFileSync, statSync } from 'fs';
import { homedir } from 'os';
import path from 'path';
/** `vscode-file://` / `file://` → absolute path on disk (or http URL). */
export function normalizeMediaRef(src) {
    const raw = src.trim();
    if (!raw)
        return null;
    if (/^https?:\/\//i.test(raw))
        return raw;
    let fsPath = raw;
    if (fsPath.startsWith('vscode-file://vscode-app')) {
        const rest = fsPath.slice('vscode-file://vscode-app'.length);
        const q = rest.indexOf('?');
        fsPath = decodeURIComponent(q >= 0 ? rest.slice(0, q) : rest);
    }
    else if (fsPath.startsWith('file://')) {
        fsPath = decodeURIComponent(fsPath.replace(/^file:\/\//, ''));
    }
    if (path.isAbsolute(fsPath))
        return path.normalize(fsPath);
    return null;
}
/** One path per file for merge/dedupe (JSONL absolute vs DOM vscode-file://). */
export function canonicalizeImagePaths(paths) {
    const out = [];
    const seen = new Set();
    for (const raw of paths) {
        const trimmed = raw.trim();
        if (!trimmed)
            continue;
        const canon = normalizeMediaRef(trimmed) ??
            (path.isAbsolute(trimmed) ? path.normalize(trimmed) : trimmed);
        if (seen.has(canon))
            continue;
        seen.add(canon);
        out.push(canon);
    }
    return out;
}
/** Resolve query `path` from client (absolute path or vscode-file URL). */
export function resolveMediaPathParam(rawPath) {
    const trimmed = rawPath.trim();
    if (!trimmed)
        return null;
    return normalizeMediaRef(trimmed) ?? (path.isAbsolute(trimmed) ? path.normalize(trimmed) : null);
}
const ALLOWED_ROOTS = () => [
    path.join(homedir(), 'Library', 'Application Support', 'Cursor'),
    path.join(homedir(), '.cursor'),
];
export function isAllowedMediaPath(filePath) {
    const resolved = path.resolve(filePath);
    return ALLOWED_ROOTS().some((root) => {
        const r = path.resolve(root);
        return resolved === r || resolved.startsWith(r + path.sep);
    });
}
export function readAllowedMediaFile(filePath) {
    const resolved = path.resolve(filePath);
    if (!isAllowedMediaPath(resolved))
        return null;
    if (!existsSync(resolved) || !statSync(resolved).isFile())
        return null;
    const ext = path.extname(resolved).toLowerCase();
    const contentType = ext === '.png'
        ? 'image/png'
        : ext === '.jpg' || ext === '.jpeg'
            ? 'image/jpeg'
            : ext === '.gif'
                ? 'image/gif'
                : ext === '.webp'
                    ? 'image/webp'
                    : 'application/octet-stream';
    return { data: readFileSync(resolved), contentType };
}
