"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.saveHandoffEntry = saveHandoffEntry;
exports.getCurrentHandoff = getCurrentHandoff;
exports.getHistoryHandoff = getHistoryHandoff;
exports.getHandoffEntries = getHandoffEntries;
exports.rotateHandoffIfNeeded = rotateHandoffIfNeeded;
exports.getHandoffStats = getHandoffStats;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const database_1 = require("../database/database");
const MAX_CURRENT_LINES = 200;
function getCellDir(projectDir) {
    return path.join(projectDir, '.cell');
}
function getHandoffDir(projectDir) {
    return path.join(getCellDir(projectDir), 'handoff');
}
function getCurrentPath(projectDir) {
    return path.join(getHandoffDir(projectDir), 'current.md');
}
function getHistoryDir(projectDir) {
    return path.join(getHandoffDir(projectDir), 'history');
}
function formatEntryMd(entry) {
    const now = new Date().toISOString().replace('T', ' ').slice(0, 16);
    const lines = [];
    lines.push(`## ${now} - ${entry.title}`);
    lines.push('');
    lines.push(`Summary: ${entry.summary}`);
    if (entry.why)
        lines.push(`\nWhy: ${entry.why}`);
    if (entry.filesChanged && entry.filesChanged.length > 0) {
        lines.push(`\nFiles Changed:`);
        for (const f of entry.filesChanged)
            lines.push(`- ${f}`);
    }
    if (entry.relatedFiles && entry.relatedFiles.length > 0) {
        lines.push(`\nRelated Files:`);
        for (const f of entry.relatedFiles)
            lines.push(`- ${f}`);
    }
    if (entry.impact)
        lines.push(`\nImpact: ${entry.impact}`);
    if (entry.verification)
        lines.push(`\nVerification: ${entry.verification}`);
    if (entry.tool || entry.model)
        lines.push(`\nTool/Model: ${entry.tool || '?'} / ${entry.model || '?'}`);
    lines.push(`\nStatus: ${entry.status}`);
    if (entry.nextSteps)
        lines.push(`\nNext: ${entry.nextSteps}`);
    lines.push('');
    return lines.join('\n');
}
function ensureDirs(projectDir) {
    const dirs = [
        getHandoffDir(projectDir),
        getHistoryDir(projectDir),
    ];
    for (const d of dirs) {
        if (!fs.existsSync(d))
            fs.mkdirSync(d, { recursive: true });
    }
}
function saveHandoffEntry(projectDir, entry) {
    ensureDirs(projectDir);
    // 1. Save to SQLite
    const db = (0, database_1.getDb)();
    db.prepare(`
    INSERT INTO handoff_entries (project, branch, title, summary, why, files_changed_json, related_files_json, impact, verification, tool, model, status, next_steps)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `).run(entry.project, entry.branch || null, entry.title, entry.summary, entry.why || null, entry.filesChanged ? JSON.stringify(entry.filesChanged) : null, entry.relatedFiles ? JSON.stringify(entry.relatedFiles) : null, entry.impact || null, entry.verification || null, entry.tool || null, entry.model || null, entry.status, entry.nextSteps || null);
    // 2. Append to current.md
    const currentPath = getCurrentPath(projectDir);
    let currentContent = '';
    if (fs.existsSync(currentPath)) {
        currentContent = fs.readFileSync(currentPath, 'utf-8');
    }
    const newEntryMd = formatEntryMd(entry);
    const lines = (currentContent + '\n' + newEntryMd).split('\n');
    if (lines.length > MAX_CURRENT_LINES) {
        // Rotate: move old content to monthly history
        const historyDir = getHistoryDir(projectDir);
        const now = new Date();
        const monthFile = path.join(historyDir, `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}.md`);
        const header = lines[0] || '# Handoff History';
        const excessLines = lines.slice(0, lines.length - MAX_CURRENT_LINES);
        const keepLines = lines.slice(lines.length - MAX_CURRENT_LINES);
        let existingHistory = '';
        if (fs.existsSync(monthFile)) {
            existingHistory = fs.readFileSync(monthFile, 'utf-8');
        }
        const historyContent = (existingHistory ? existingHistory + '\n\n' : header + '\n\n') + excessLines.join('\n');
        fs.writeFileSync(monthFile, historyContent);
        fs.writeFileSync(currentPath, keepLines.join('\n'));
    }
    else {
        const content = currentContent.trim() ? currentContent.trim() + '\n\n' + newEntryMd : '# Current Handoff\n\n' + newEntryMd;
        fs.writeFileSync(currentPath, content);
    }
}
function getCurrentHandoff(projectDir) {
    const currentPath = getCurrentPath(projectDir);
    if (!fs.existsSync(currentPath))
        return '# Current Handoff\n\nNo handoff entries yet.';
    return fs.readFileSync(currentPath, 'utf-8');
}
function getHistoryHandoff(projectDir, yearMonth) {
    const historyDir = getHistoryDir(projectDir);
    if (!yearMonth) {
        const now = new Date();
        yearMonth = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
    }
    const historyPath = path.join(historyDir, `${yearMonth}.md`);
    if (!fs.existsSync(historyPath))
        return `# Handoff History — ${yearMonth}\n\nNo history entries for this month.`;
    return fs.readFileSync(historyPath, 'utf-8');
}
function getHandoffEntries(projectDir, limit = 20) {
    const db = (0, database_1.getDb)();
    const project = path.basename(projectDir);
    return db.prepare('SELECT * FROM handoff_entries WHERE project = ? ORDER BY created_at DESC LIMIT ?').all(project, limit);
}
function rotateHandoffIfNeeded(projectDir) {
    const currentPath = getCurrentPath(projectDir);
    if (!fs.existsSync(currentPath))
        return false;
    const content = fs.readFileSync(currentPath, 'utf-8');
    const lines = content.split('\n');
    if (lines.length <= MAX_CURRENT_LINES)
        return false;
    const historyDir = getHistoryDir(projectDir);
    if (!fs.existsSync(historyDir))
        fs.mkdirSync(historyDir, { recursive: true });
    const now = new Date();
    const monthFile = path.join(historyDir, `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}.md`);
    const header = '# Handoff History\n\n';
    const excessLines = lines.slice(0, lines.length - MAX_CURRENT_LINES);
    const keepLines = lines.slice(lines.length - MAX_CURRENT_LINES);
    let existingHistory = '';
    if (fs.existsSync(monthFile)) {
        existingHistory = fs.readFileSync(monthFile, 'utf-8');
    }
    const historyContent = (existingHistory ? existingHistory + '\n\n' : header) + excessLines.join('\n');
    fs.writeFileSync(monthFile, historyContent);
    fs.writeFileSync(currentPath, keepLines.join('\n'));
    return true;
}
function getHandoffStats(projectDir) {
    const currentPath = getCurrentPath(projectDir);
    let currentLines = 0;
    if (fs.existsSync(currentPath)) {
        currentLines = fs.readFileSync(currentPath, 'utf-8').split('\n').length;
    }
    const historyDir = getHistoryDir(projectDir);
    let historyMonths = 0;
    if (fs.existsSync(historyDir)) {
        historyMonths = fs.readdirSync(historyDir).filter(f => f.endsWith('.md')).length;
    }
    const project = path.basename(projectDir);
    const db = (0, database_1.getDb)();
    const row = db.prepare('SELECT COUNT(*) as c FROM handoff_entries WHERE project = ?').get(project);
    return {
        currentLines,
        historyMonths,
        dbEntries: row.c,
        needsRotation: currentLines > MAX_CURRENT_LINES,
    };
}
//# sourceMappingURL=handoff-store.js.map