"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.recordOutcome = recordOutcome;
exports.recordStepSequence = recordStepSequence;
exports.getNodes = getNodes;
exports.getEdges = getEdges;
exports.getPathProbabilities = getPathProbabilities;
exports.getGraphStats = getGraphStats;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const OUTCOME_DIR = path.join(os.homedir(), '.fivo', 'cell', 'outcome-graph');
function ensureDir() { if (!fs.existsSync(OUTCOME_DIR))
    fs.mkdirSync(OUTCOME_DIR, { recursive: true }); }
function seqPath() { return path.join(OUTCOME_DIR, 'sequences.json'); }
function loadSequences() {
    ensureDir();
    try {
        if (fs.existsSync(seqPath()))
            return JSON.parse(fs.readFileSync(seqPath(), 'utf-8'));
    }
    catch { }
    return [];
}
function saveSequences(seqs) {
    fs.writeFileSync(seqPath(), JSON.stringify(seqs, null, 2), 'utf-8');
}
function recordOutcome(outcome) {
    const seqs = loadSequences();
    seqs.push({
        sessionId: `session_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
        steps: [outcome.action],
        success: outcome.success,
        totalDurationMs: outcome.durationMs,
        timestamp: outcome.timestamp,
    });
    saveSequences(seqs);
}
function recordStepSequence(sequence) {
    const seqs = loadSequences();
    seqs.push(sequence);
    saveSequences(seqs);
}
function getNodes() {
    const seqs = loadSequences();
    const nodeMap = new Map();
    for (const seq of seqs) {
        for (const step of seq.steps) {
            const n = nodeMap.get(step) || { count: 0, successes: 0, totalDuration: 0 };
            n.count++;
            if (seq.success)
                n.successes++;
            n.totalDuration += seq.totalDurationMs;
            nodeMap.set(step, n);
        }
    }
    return Array.from(nodeMap.entries()).map(([step, data]) => ({
        step,
        count: data.count,
        successRate: data.count > 0 ? data.successes / data.count : 0,
        avgDurationMs: data.count > 0 ? data.totalDuration / data.count : 0,
    }));
}
function getEdges() {
    const seqs = loadSequences();
    const edgeMap = new Map();
    for (const seq of seqs) {
        for (let i = 0; i < seq.steps.length - 1; i++) {
            const key = `${seq.steps[i]}||${seq.steps[i + 1]}`;
            const e = edgeMap.get(key) || { count: 0, successes: 0, totalDuration: 0 };
            e.count++;
            if (seq.success)
                e.successes++;
            e.totalDuration += seq.totalDurationMs;
            edgeMap.set(key, e);
        }
    }
    return Array.from(edgeMap.entries()).map(([key, data]) => {
        const [from, to] = key.split('||');
        return {
            from,
            to,
            count: data.count,
            successRate: data.count > 0 ? data.successes / data.count : 0,
            avgDurationMs: data.count > 0 ? data.totalDuration / data.count : 0,
        };
    });
}
function getPathProbabilities(from, to) {
    const edges = getEdges();
    const paths = [];
    const outgoing = edges.filter((e) => e.from === from);
    const totalOutgoing = outgoing.reduce((s, e) => s + e.count, 0);
    for (const edge of outgoing) {
        if (edge.to === to) {
            paths.push({ from, to, probability: totalOutgoing > 0 ? edge.count / totalOutgoing : 0, sampleSize: edge.count });
        }
    }
    // BFS for indirect paths (max depth 3)
    function bfs(start, target, depth, visited) {
        if (depth > 3 || start === target)
            return [];
        const results = [];
        for (const e of edges.filter((e) => e.from === start && !visited.has(e.to))) {
            if (e.to === target) {
                results.push(e.count);
            }
            else {
                visited.add(e.to);
                const sub = bfs(e.to, target, depth + 1, visited);
                results.push(...sub.map((c) => Math.min(e.count, c)));
                visited.delete(e.to);
            }
        }
        return results;
    }
    const indirect = bfs(from, to, 1, new Set([from]));
    const totalIndirect = indirect.reduce((s, c) => s + c, 0);
    if (totalIndirect > 0) {
        paths.push({ from, to, probability: totalIndirect / (totalOutgoing + totalIndirect || 1), sampleSize: totalIndirect });
    }
    return paths.sort((a, b) => b.probability - a.probability);
}
function getGraphStats() {
    const seqs = loadSequences();
    const allSteps = seqs.flatMap((s) => s.steps);
    const edges = getEdges();
    return {
        totalSessions: seqs.length,
        totalSteps: allSteps.length,
        uniqueSteps: new Set(allSteps).size,
        uniqueEdges: edges.length,
    };
}
//# sourceMappingURL=workflow-outcome-graph.js.map