// engine/context-manager.ts — SPEC-370: Context Window Management
import { readdir, readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
const TOKENS_PER_SPEC = 1500;
const TOKENS_PER_DECISION = 200;
const TOKENS_PER_LESSON = 150;
export function estimateTokenBreakdown(specCount, decisionCount, lessonCount) {
    return {
        specs: specCount * TOKENS_PER_SPEC,
        decisions: decisionCount * TOKENS_PER_DECISION,
        lessons: lessonCount * TOKENS_PER_LESSON,
        total: specCount * TOKENS_PER_SPEC +
            decisionCount * TOKENS_PER_DECISION +
            lessonCount * TOKENS_PER_LESSON,
        specCount,
        decisionCount,
        lessonCount,
    };
}
export function suggestArchivableSpecs(specs, archiveAfterDays) {
    const now = Date.now();
    const archivable = [];
    for (const spec of specs) {
        if (spec.status !== 'done') {
            continue;
        }
        const doneAt = spec.updatedAt;
        const doneMs = doneAt ? new Date(doneAt).getTime() : 0;
        const daysSince = Math.floor((now - doneMs) / (24 * 60 * 60 * 1000));
        if (doneAt && daysSince < archiveAfterDays) {
            continue;
        }
        const relevanceScore = Math.max(0, 100 - daysSince);
        archivable.push({
            specId: spec.id,
            title: spec.title,
            status: spec.status,
            estimatedTokens: TOKENS_PER_SPEC,
            daysSinceDone: daysSince,
            relevanceScore,
        });
    }
    archivable.sort((a, b) => a.relevanceScore - b.relevanceScore);
    const potentialSavings = archivable.length * TOKENS_PER_SPEC;
    return {
        specs: archivable,
        potentialSavings,
        recommendation: archivable.length > 0
            ? `Archive ${archivable.length} done spec(s) to save ~${potentialSavings.toLocaleString()} tokens`
            : 'No archivable specs found. All done specs are recent or already archived.',
    };
}
export async function archiveSpecToPath(archivePath, spec) {
    await mkdir(dirname(archivePath), { recursive: true });
    await writeFile(archivePath, JSON.stringify({ spec, archivedAt: new Date().toISOString() }), 'utf8');
}
export async function restoreArchivedSpecFromPath(archivePath) {
    try {
        const raw = await readFile(archivePath, 'utf8');
        const data = JSON.parse(raw);
        return data !== null && typeof data === 'object';
    }
    catch {
        return false;
    }
}
export async function listArchivedSpecIds(archiveDir) {
    try {
        const files = await readdir(archiveDir);
        return files.filter((f) => f.endsWith('.json')).map((f) => f.replace('.json', ''));
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=context-manager.js.map