"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReversaAgent = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ReversaExecutors_1 = require("./ReversaExecutors");
const ReversaContracts_1 = require("./ReversaContracts");
class ReversaAgent {
    statePath;
    executors;
    constructor() {
        this.statePath = path.join(process.cwd(), '.reversa', 'state.json');
        this.executors = new ReversaExecutors_1.ReversaExecutors(process.cwd());
        fs.mkdirSync(path.dirname(this.statePath), { recursive: true });
    }
    resume() {
        if (!fs.existsSync(this.statePath)) {
            const initial = { phase: 'reconnaissance', updatedAt: new Date().toISOString(), notes: ['Reversa initialized'] };
            this.save(initial);
            return initial;
        }
        return JSON.parse(fs.readFileSync(this.statePath, 'utf-8'));
    }
    advance(note) {
        const cur = this.resume();
        const phases = ['reconnaissance', 'excavation', 'interpretation', 'generation', 'review'];
        const idx = phases.indexOf(cur.phase);
        const nextPhase = phases[Math.min(idx + 1, phases.length - 1)];
        const checkpoint = { ...(cur.checkpoint || {}) };
        if (nextPhase === 'excavation')
            checkpoint.scout = 'surface map ready';
        if (nextPhase === 'interpretation')
            checkpoint.archaeologist = 'module deep analysis ready';
        if (nextPhase === 'generation')
            checkpoint.detective = 'implicit business rules extracted';
        if (nextPhase === 'review') {
            checkpoint.architect = 'c4/erd/contracts synthesized';
            checkpoint.writer = 'operational contracts generated';
            checkpoint.reviewer = 'gaps reviewed';
        }
        const next = { phase: nextPhase, mode: cur.mode || 'default', designProfileId: cur.designProfileId, checkpoint, updatedAt: new Date().toISOString(), notes: [...cur.notes, note] };
        this.save(next);
        return next;
    }
    setMode(mode, designProfileId) {
        const cur = this.resume();
        const next = { ...cur, mode, designProfileId, updatedAt: new Date().toISOString(), notes: [...cur.notes, `Mode set to ${mode}${designProfileId ? ` (${designProfileId})` : ''}`] };
        this.save(next);
        return next;
    }
    runPhase(phase, note = 'phase run') {
        const cur = this.resume();
        const mapping = {
            reconnaissance: 'scout', excavation: 'archaeologist', interpretation: 'detective', generation: 'writer', review: 'reviewer'
        };
        const result = this.executors.run(mapping[phase], { mode: cur.mode, profile: cur.designProfileId, note });
        const next = { ...cur, phase, updatedAt: new Date().toISOString(), notes: [...cur.notes, `${phase}: ${result.summary}`] };
        this.save(next);
        return next;
    }
    runAll(note = 'run all') {
        const phases = ['reconnaissance', 'excavation', 'interpretation', 'generation', 'review'];
        let state = this.resume();
        for (const p of phases)
            state = this.runPhase(p, `${note} :: ${p}`);
        this.writeFinalContracts();
        return state;
    }
    writeFinalContracts() {
        const cur = this.resume();
        const artifactsRoot = path.join(process.cwd(), '.reversa', 'artifacts');
        const validation = (0, ReversaContracts_1.validatePhaseChain)(artifactsRoot);
        const contracts = (0, ReversaContracts_1.getContracts)();
        const out = path.join(process.cwd(), '.reversa', 'final-contracts.md');
        const body = [
            '# Reversa Final Contracts',
            `mode: ${cur.mode || 'default'}`,
            `designProfileId: ${cur.designProfileId || 'none'}`,
            `validation_ok: ${validation.ok}`,
            `missing: ${validation.missing.join(', ') || 'none'}`,
            '',
            '## Contracts',
            ...contracts.map((c) => `- ${c.phase}/${c.role}: in=[${c.requiredInputs.join(', ')}] out=[${c.producedOutputs.join(', ')}]`)
        ].join('\n');
        fs.writeFileSync(out, body, 'utf-8');
        return out;
    }
    exportContractsJson() {
        const cur = this.resume();
        const artifactsRoot = path.join(process.cwd(), '.reversa', 'artifacts');
        const validation = (0, ReversaContracts_1.validatePhaseChain)(artifactsRoot);
        const contracts = (0, ReversaContracts_1.getContracts)();
        const out = path.join(process.cwd(), '.reversa', 'final-contracts.json');
        fs.writeFileSync(out, JSON.stringify({ mode: cur.mode || 'default', designProfileId: cur.designProfileId || 'none', validation, contracts }, null, 2), 'utf-8');
        return out;
    }
    save(state) {
        fs.writeFileSync(this.statePath, JSON.stringify(state, null, 2), 'utf-8');
    }
}
exports.ReversaAgent = ReversaAgent;
