import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, } from 'fs';
import { homedir } from 'os';
import { join } from 'path';
import { messagesFingerprint } from './lenta-seq-journal.js';
import { resolveJsonlFilePath } from './agent-title-match.js';
const CAPTURE_ROOT = join(homedir(), '.cursorconnect', 'capture');
export function captureConfigPath() {
    return join(CAPTURE_ROOT, 'config.json');
}
export function readCaptureConfig() {
    const path = captureConfigPath();
    if (!existsSync(path))
        return null;
    try {
        const raw = JSON.parse(readFileSync(path, 'utf8'));
        if (!raw.enabled || !raw.agentId?.trim())
            return null;
        return { ...raw, agentId: raw.agentId.trim() };
    }
    catch {
        return null;
    }
}
export function writeCaptureConfig(cfg) {
    mkdirSync(CAPTURE_ROOT, { recursive: true });
    writeFileSync(captureConfigPath(), `${JSON.stringify(cfg, null, 2)}\n`);
}
export function clearCaptureConfig() {
    writeCaptureConfig({ enabled: false, agentId: '' });
}
export function captureSessionDir(agentId) {
    return join(CAPTURE_ROOT, 'sessions', agentId);
}
export class LentaCaptureSession {
    agentId;
    step = 0;
    lastSig = '';
    constructor(agentId) {
        this.agentId = agentId;
        const dir = captureSessionDir(agentId);
        mkdirSync(dir, { recursive: true });
        const manifestPath = join(dir, 'manifest.jsonl');
        if (!existsSync(manifestPath)) {
            writeFileSync(manifestPath, `${JSON.stringify({
                startedAt: new Date().toISOString(),
                agentId,
                note: 'Full JSONL+DOM snapshots per bridge event',
            })}\n`);
        }
    }
    shouldCapture(targetAgentId) {
        return targetAgentId === this.agentId;
    }
    record(payload) {
        const sig = messagesFingerprint(payload.messages);
        if (sig === this.lastSig && payload.reason !== 'jsonl_file') {
            return null;
        }
        this.lastSig = sig;
        this.step += 1;
        const stepId = `${String(this.step).padStart(5, '0')}-${payload.reason}`;
        const dir = join(captureSessionDir(this.agentId), stepId);
        mkdirSync(dir, { recursive: true });
        const meta = {
            at: new Date().toISOString(),
            step: this.step,
            stepId,
            agentId: this.agentId,
            reason: payload.reason,
            source: payload.source,
            emitSeq: payload.emitSeq,
            seqHeld: payload.seqHeld,
            transition: payload.transition,
            jsonlRowCount: payload.jsonlRowCount,
            counts: {
                messages: payload.messages.length,
                history: payload.historyMessages.length,
                live: payload.liveMessages.length,
                domRaw: payload.domRaw?.length ?? 0,
                domViewport: payload.domViewport?.length ?? 0,
                jsonlRaw: payload.jsonlRawRows?.length ?? 0,
            },
            messagesSig: sig.slice(0, 500),
            activeComposerId: payload.activeComposerId,
            agentWorking: payload.agentWorking,
            jsonlFile: payload.jsonlFilePath,
        };
        writeFileSync(join(dir, 'meta.json'), `${JSON.stringify(meta, null, 2)}\n`);
        writeFileSync(join(dir, 'messages.json'), `${JSON.stringify(payload.messages, null, 2)}\n`);
        writeFileSync(join(dir, 'historyMessages.json'), `${JSON.stringify(payload.historyMessages, null, 2)}\n`);
        writeFileSync(join(dir, 'liveMessages.json'), `${JSON.stringify(payload.liveMessages, null, 2)}\n`);
        if (payload.domRaw?.length) {
            writeFileSync(join(dir, 'domRaw.json'), `${JSON.stringify(payload.domRaw, null, 2)}\n`);
        }
        if (payload.domViewport?.length) {
            writeFileSync(join(dir, 'domViewport.json'), `${JSON.stringify(payload.domViewport, null, 2)}\n`);
        }
        if (payload.jsonlRawRows?.length) {
            writeFileSync(join(dir, 'jsonl.rows.json'), `${JSON.stringify(payload.jsonlRawRows, null, 2)}\n`);
        }
        if (payload.jsonlFilePath && existsSync(payload.jsonlFilePath)) {
            try {
                copyFileSync(payload.jsonlFilePath, join(dir, 'transcript.jsonl'));
            }
            catch {
                /* non-fatal */
            }
        }
        const manifestLine = JSON.stringify(meta);
        writeFileSync(join(captureSessionDir(this.agentId), 'manifest.jsonl'), manifestLine + '\n', { flag: 'a' });
        bridgeCaptureLog(stepId, meta.counts, payload.reason);
        return dir;
    }
}
function bridgeCaptureLog(stepId, counts, reason) {
    console.log(`[lenta-capture] ${stepId} reason=${reason} msgs=${counts.messages} hist=${counts.history} live=${counts.live} domRaw=${counts.domRaw}`);
}
let session = null;
let sessionAgentId = '';
export function getLentaCaptureSession(agentId) {
    const cfg = readCaptureConfig();
    if (!cfg || cfg.agentId !== agentId)
        return null;
    if (!session || sessionAgentId !== agentId) {
        session = new LentaCaptureSession(agentId);
        sessionAgentId = agentId;
    }
    return session;
}
export function captureLentaIfEnabled(agentId, payload) {
    const cap = getLentaCaptureSession(agentId);
    if (!cap)
        return;
    cap.record(payload);
}
export function resolveAgentJsonlPath(projectsDir, agentId, opts) {
    return resolveJsonlFilePath(projectsDir, agentId, opts) ?? undefined;
}
export function listCaptureSteps(agentId) {
    const dir = captureSessionDir(agentId);
    if (!existsSync(dir))
        return [];
    return readdirSync(dir)
        .filter((n) => /^\d{5}-/.test(n))
        .sort();
}
