import { existsSync, readFileSync, statSync } from 'node:fs';
import { dirname, isAbsolute, resolve } from 'node:path';
import { readSandboxReport } from './sandbox-report.js';
import { readLastEval } from './last-eval.js';
const DEFAULT_CONFIG_PATH = resolve(process.cwd(), 'config/catchup.json');
const DEFAULT_SANDBOX_REPORT_PATH = resolve(process.cwd(), 'eval/sandbox/report.md');
export function getCatchupMetadata(options = {}) {
    const configPath = options.configPath ?? DEFAULT_CONFIG_PATH;
    const sandboxPath = options.sandboxReportPath ?? DEFAULT_SANDBOX_REPORT_PATH;
    const maxDocChars = options.maxDocChars ?? 12_000;
    const config = readConfig(configPath);
    const configDir = dirname(configPath);
    const projectGoal = readDocSnippet(resolveDocPath(config.projectGoalDocPath, configDir), maxDocChars);
    const roadmap = readDocSnippet(resolveDocPath(config.roadmapDocPath, configDir), maxDocChars);
    return {
        configPath,
        configExists: existsSync(configPath),
        currentPhase: config.currentPhase,
        projectGoal,
        roadmap,
        knownIssues: config.knownIssues ?? [],
        keyMcpTools: config.keyMcpTools ?? [],
        sandbox: readSandboxReport(sandboxPath),
        retrievalEval: readLastEval({ path: options.lastEvalPath }),
    };
}
function readConfig(path) {
    if (!existsSync(path)) {
        return {};
    }
    try {
        const raw = readFileSync(path, 'utf8');
        const parsed = JSON.parse(raw);
        return parsed ?? {};
    }
    catch {
        return {};
    }
}
function resolveDocPath(docPath, configDir) {
    if (!docPath)
        return undefined;
    return isAbsolute(docPath) ? docPath : resolve(configDir, '..', docPath);
}
function readDocSnippet(path, maxChars) {
    if (!path) {
        return { path: '', exists: false };
    }
    try {
        statSync(path);
    }
    catch {
        return { path, exists: false };
    }
    try {
        const raw = readFileSync(path, 'utf8');
        return {
            path,
            exists: true,
            content: raw.length > maxChars ? `${raw.slice(0, maxChars)}\n\n…[truncated ${raw.length - maxChars} chars]` : raw,
        };
    }
    catch {
        return { path, exists: false };
    }
}
