import { appendFileSync, mkdirSync, readFileSync, existsSync, readdirSync, statSync } from 'fs';
import { join, dirname } from 'path';
import { logger } from '../utils/logger.js';
import { summarizeError } from '../utils/error-display.js';
export class WrfcWorkmap {
    filePath;
    constructor(projectRoot, sessionId) {
        this.filePath = join(projectRoot, '.goodvibes', 'goodvibes', 'sessions', `${sessionId}_workmap.jsonl`);
    }
    dirCreated = false;
    append(entry) {
        try {
            if (!this.dirCreated) {
                mkdirSync(dirname(this.filePath), { recursive: true });
                this.dirCreated = true;
            }
            appendFileSync(this.filePath, JSON.stringify(entry) + '\n', 'utf-8');
        }
        catch (err) {
            logger.debug('WrfcWorkmap: append failed', { error: summarizeError(err) });
        }
    }
    /** Read all entries, optionally filtered by wrfcId */
    read(wrfcId) {
        if (!existsSync(this.filePath))
            return [];
        try {
            const lines = readFileSync(this.filePath, 'utf-8').trim().split('\n').filter(Boolean);
            const entries = lines.map(line => {
                try {
                    return JSON.parse(line);
                }
                catch {
                    logger.debug('WrfcWorkmap: malformed JSONL line skipped');
                    return null;
                }
            }).filter((e) => e !== null);
            if (wrfcId)
                return entries.filter(e => e.wrfcId === wrfcId);
            return entries;
        }
        catch {
            return [];
        }
    }
    /** Get all unique WRFC chain IDs with their latest status */
    listChains() {
        const entries = this.read();
        const chains = new Map();
        for (const e of entries) {
            const existing = chains.get(e.wrfcId) ?? { status: 'active', events: 0 };
            existing.events++;
            if (e.task)
                existing.task = e.task;
            if (e.score !== undefined)
                existing.lastScore = e.score;
            if (e.event === 'chain_passed')
                existing.status = 'passed';
            if (e.event === 'chain_failed')
                existing.status = 'failed';
            chains.set(e.wrfcId, existing);
        }
        return Array.from(chains.entries()).map(([wrfcId, data]) => ({ wrfcId, ...data }));
    }
    /** Static: find the most recent workmap file in sessions dir */
    static findLatest(sessionsDir) {
        const dir = sessionsDir;
        if (!existsSync(dir))
            return null;
        try {
            const files = readdirSync(dir)
                .filter((f) => f.endsWith('_workmap.jsonl'))
                .map((f) => ({ name: f, mtime: statSync(join(dir, f)).mtimeMs }))
                .sort((a, b) => b.mtime - a.mtime);
            return files.length > 0 ? join(dir, files[0].name) : null;
        }
        catch {
            return null;
        }
    }
}
