"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.generateAutoHandoff = generateAutoHandoff;
exports.saveAutoHandoff = saveAutoHandoff;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
function generateAutoHandoff(project, projectDir, days = 3) {
    const db = (0, database_1.getDb)();
    const since = new Date(Date.now() - days * 86400000).toISOString();
    const events = db.prepare(`
    SELECT type, topic, summary, files_json, importance, created_at
    FROM memory_events
    WHERE project = ? AND created_at >= ?
    ORDER BY importance DESC, created_at DESC
    LIMIT 100
  `).all(project, since);
    const files = collectFiles(events).slice(0, 12);
    const decisions = events.filter((e) => e.type === 'decision').slice(0, 5).map((e) => e.summary);
    const errors = events.filter((e) => e.type === 'error').slice(0, 5).map((e) => e.summary);
    const fixes = events.filter((e) => e.type === 'fix').slice(0, 5).map((e) => e.summary);
    const verifications = events.filter((e) => e.type === 'verification').slice(0, 5).map((e) => e.summary);
    const topTopic = mostCommon(events.map((e) => e.topic).filter(Boolean)) || 'recent work';
    const title = `Auto handoff — ${topTopic}`;
    const summary = buildSummary(decisions, fixes, errors, events.length);
    const impact = files.length > 0 ? `Primary impact across ${files.length} file(s), especially ${files.slice(0, 3).join(', ')}` : 'Impact not enough data';
    const nextSteps = buildNextSteps(decisions, errors, verifications);
    const status = errors.length > fixes.length ? 'blocked' : (events.length > 0 ? 'active' : 'done');
    const markdown = buildMarkdown({ title, summary, files, impact, verification: verifications, nextSteps, status });
    return { title, summary, files, impact, verification: verifications, nextSteps, status, markdown };
}
function saveAutoHandoff(projectDir, handoff) {
    const dir = path.join(projectDir, '.cell', 'handoff');
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    const file = path.join(dir, 'current.md');
    fs.writeFileSync(file, handoff.markdown, 'utf-8');
    return file;
}
function collectFiles(events) {
    const out = [];
    for (const e of events) {
        if (!e.files_json)
            continue;
        try {
            const files = JSON.parse(e.files_json);
            for (const f of files)
                out.push(f);
        }
        catch { }
    }
    return [...new Set(out)];
}
function mostCommon(values) {
    if (values.length === 0)
        return null;
    const map = new Map();
    for (const v of values)
        map.set(v, (map.get(v) || 0) + 1);
    return [...map.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] || null;
}
function buildSummary(decisions, fixes, errors, totalEvents) {
    if (totalEvents === 0)
        return 'No recent activity detected.';
    const parts = [`${totalEvents} memory events captured recently.`];
    if (decisions.length > 0)
        parts.push(`Key decisions: ${decisions.slice(0, 2).join('; ')}.`);
    if (fixes.length > 0)
        parts.push(`Fixes applied: ${fixes.slice(0, 2).join('; ')}.`);
    if (errors.length > 0)
        parts.push(`Open issues/errors: ${errors.slice(0, 2).join('; ')}.`);
    return parts.join(' ');
}
function buildNextSteps(decisions, errors, verifications) {
    const steps = [];
    if (errors.length > 0)
        steps.push('Resolve remaining errors and record fixes');
    if (verifications.length === 0)
        steps.push('Run verification commands and log results');
    if (decisions.length === 0)
        steps.push('Log architectural or product decisions for context continuity');
    if (steps.length === 0)
        steps.push('Continue current implementation and update handoff when scope changes');
    return steps;
}
function buildMarkdown(data) {
    const lines = [];
    lines.push(`## ${new Date().toISOString().slice(0, 16).replace('T', ' ')} - ${data.title}`);
    lines.push('');
    lines.push('### Summary');
    lines.push(data.summary);
    lines.push('');
    lines.push('### Files');
    for (const f of data.files)
        lines.push(`- ${f}`);
    lines.push('');
    lines.push('### Impact');
    lines.push(data.impact);
    lines.push('');
    lines.push('### Verification');
    if (data.verification.length === 0)
        lines.push('- none logged');
    else
        for (const v of data.verification)
            lines.push(`- ${v}`);
    lines.push('');
    lines.push('### Status');
    lines.push(`- ${data.status}`);
    lines.push('');
    lines.push('### Next');
    for (const n of data.nextSteps)
        lines.push(`- ${n}`);
    lines.push('');
    return lines.join('\n');
}
//# sourceMappingURL=auto-handoff.js.map