"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.saveBranchSnapshot = saveBranchSnapshot;
exports.loadBranchSnapshot = loadBranchSnapshot;
exports.listBranchSnapshots = listBranchSnapshots;
exports.deleteBranchSnapshot = deleteBranchSnapshot;
exports.captureCurrentBranchSnapshot = captureCurrentBranchSnapshot;
exports.getBranchContextSummary = getBranchContextSummary;
exports.formatBranchContextSummary = formatBranchContextSummary;
exports.getAllBranchContexts = getAllBranchContexts;
const database_1 = require("../../06-memory/database/database");
const logger_1 = require("../../06-memory/database/logger");
function ensureTable() {
    const db = (0, database_1.getDb)();
    db.exec(`
    CREATE TABLE IF NOT EXISTS branch_snapshots (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      branch TEXT NOT NULL,
      goal TEXT,
      files_touched TEXT,
      pending_tasks TEXT,
      recent_errors TEXT,
      recent_decisions TEXT,
      last_session_id INTEGER,
      last_active_at TEXT DEFAULT (datetime('now')),
      created_at TEXT DEFAULT (datetime('now')),
      updated_at TEXT DEFAULT (datetime('now')),
      UNIQUE(project, branch)
    )
  `);
}
function saveBranchSnapshot(snapshot) {
    try {
        ensureTable();
        const db = (0, database_1.getDb)();
        const existing = db
            .prepare('SELECT id FROM branch_snapshots WHERE project = ? AND branch = ?')
            .get(snapshot.project, snapshot.branch);
        const filesJson = JSON.stringify(snapshot.filesTouched || []);
        const tasksJson = JSON.stringify(snapshot.pendingTasks || []);
        const errorsJson = JSON.stringify(snapshot.recentErrors || []);
        const decisionsJson = JSON.stringify(snapshot.recentDecisions || []);
        if (existing) {
            db.prepare(`UPDATE branch_snapshots
         SET goal = ?, files_touched = ?, pending_tasks = ?, recent_errors = ?,
             recent_decisions = ?, last_session_id = ?, last_active_at = datetime('now'),
             updated_at = datetime('now')
         WHERE id = ?`).run(snapshot.goal || null, filesJson, tasksJson, errorsJson, decisionsJson, snapshot.lastSessionId || null, existing.id);
        }
        else {
            db.prepare(`INSERT INTO branch_snapshots (project, branch, goal, files_touched, pending_tasks, recent_errors, recent_decisions, last_session_id)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(snapshot.project, snapshot.branch, snapshot.goal || null, filesJson, tasksJson, errorsJson, decisionsJson, snapshot.lastSessionId || null);
        }
    }
    catch (e) {
        logger_1.logger.warn('branch-snapshot save failed: ' + (e instanceof Error ? e.message : String(e)));
    }
}
function loadBranchSnapshot(project, branch) {
    try {
        ensureTable();
        const db = (0, database_1.getDb)();
        const row = db
            .prepare('SELECT * FROM branch_snapshots WHERE project = ? AND branch = ?')
            .get(project, branch);
        if (!row)
            return null;
        return {
            id: row.id,
            project: row.project,
            branch: row.branch,
            goal: row.goal || undefined,
            filesTouched: safeParse(row.files_touched),
            pendingTasks: safeParse(row.pending_tasks),
            recentErrors: safeParse(row.recent_errors),
            recentDecisions: safeParse(row.recent_decisions),
            lastSessionId: row.last_session_id || undefined,
            lastActiveAt: row.last_active_at || undefined,
            createdAt: row.created_at || undefined,
            updatedAt: row.updated_at || undefined,
        };
    }
    catch {
        return null;
    }
}
function listBranchSnapshots(project) {
    try {
        ensureTable();
        const db = (0, database_1.getDb)();
        const rows = db
            .prepare('SELECT * FROM branch_snapshots WHERE project = ? ORDER BY last_active_at DESC')
            .all(project);
        return rows.map((row) => ({
            id: row.id,
            project: row.project,
            branch: row.branch,
            goal: row.goal || undefined,
            filesTouched: safeParse(row.files_touched),
            pendingTasks: safeParse(row.pending_tasks),
            recentErrors: safeParse(row.recent_errors),
            recentDecisions: safeParse(row.recent_decisions),
            lastSessionId: row.last_session_id || undefined,
            lastActiveAt: row.last_active_at || undefined,
            createdAt: row.created_at || undefined,
            updatedAt: row.updated_at || undefined,
        }));
    }
    catch {
        return [];
    }
}
function deleteBranchSnapshot(project, branch) {
    try {
        ensureTable();
        const db = (0, database_1.getDb)();
        const result = db
            .prepare('DELETE FROM branch_snapshots WHERE project = ? AND branch = ?')
            .run(project, branch);
        return result.changes > 0;
    }
    catch {
        return false;
    }
}
function captureCurrentBranchSnapshot(project, cwd) {
    try {
        const { execSync } = require('child_process');
        let branch = '';
        try {
            branch = execSync('git branch --show-current', { cwd, encoding: 'utf8' }).trim();
        }
        catch {
            return;
        }
        if (!branch)
            return;
        const db = (0, database_1.getDb)();
        const existing = loadBranchSnapshot(project, branch);
        let recentFiles = [];
        try {
            const changed = execSync('git diff --name-only HEAD~5', { cwd, encoding: 'utf8' }).trim();
            if (changed)
                recentFiles = changed.split('\n').filter(Boolean).slice(0, 20);
        }
        catch { }
        let recentCommitMessages = [];
        try {
            const log = execSync('git log --oneline -5', { cwd, encoding: 'utf8' }).trim();
            if (log)
                recentCommitMessages = log.split('\n').filter(Boolean);
        }
        catch { }
        saveBranchSnapshot({
            project,
            branch,
            goal: existing?.goal || undefined,
            filesTouched: recentFiles.length > 0 ? recentFiles : existing?.filesTouched,
            recentErrors: existing?.recentErrors || [],
            recentDecisions: recentCommitMessages.length > 0 ? recentCommitMessages : existing?.recentDecisions,
            lastSessionId: existing?.lastSessionId,
        });
    }
    catch { }
}
function safeParse(json) {
    if (!json)
        return [];
    try {
        const parsed = JSON.parse(json);
        return Array.isArray(parsed) ? parsed : [];
    }
    catch {
        return [];
    }
}
function getBranchContextSummary(project, branch) {
    const snapshot = loadBranchSnapshot(project, branch);
    if (!snapshot)
        return null;
    const lastActive = snapshot.lastActiveAt ? new Date(snapshot.lastActiveAt) : new Date();
    const daysSince = Math.floor((Date.now() - lastActive.getTime()) / 86400000);
    let status;
    if (daysSince <= 1)
        status = 'active';
    else if (daysSince <= 7)
        status = 'stale';
    else
        status = 'abandoned';
    // Get CI failure count for this branch
    let ciFailures = 0;
    try {
        const { getDb } = require('../../06-memory/database/database');
        const db = getDb();
        const row = db.prepare(`SELECT COUNT(*) as c FROM memory_events WHERE project = ? AND branch = ? AND type = 'error' AND topic LIKE 'ci-%'`).get(project, branch);
        ciFailures = row?.c || 0;
    }
    catch { /* ignore */ }
    return {
        branch: snapshot.branch,
        goal: snapshot.goal,
        filesTouched: snapshot.filesTouched || [],
        pendingTasks: snapshot.pendingTasks || [],
        recentErrors: snapshot.recentErrors || [],
        recentDecisions: snapshot.recentDecisions || [],
        daysSinceLastActive: daysSince,
        status,
        ciFailures,
    };
}
function formatBranchContextSummary(summary) {
    const lines = [];
    const statusIcon = summary.status === 'active' ? '🟢' : summary.status === 'stale' ? '🟡' : '🔴';
    lines.push(`${statusIcon} Branch: ${summary.branch} (${summary.daysSinceLastActive}d ago)`);
    if (summary.goal)
        lines.push(`   Goal: ${summary.goal}`);
    if (summary.filesTouched.length > 0) {
        lines.push(`   Files: ${summary.filesTouched.slice(0, 5).join(', ')}${summary.filesTouched.length > 5 ? '...' : ''}`);
    }
    if (summary.recentDecisions.length > 0) {
        lines.push(`   Recent: ${summary.recentDecisions.slice(0, 3).join('; ')}`);
    }
    if (summary.recentErrors.length > 0) {
        lines.push(`   Errors: ${summary.recentErrors.length} recent`);
    }
    if (summary.pendingTasks.length > 0) {
        lines.push(`   Pending: ${summary.pendingTasks.slice(0, 3).join(', ')}`);
    }
    if (summary.ciFailures && summary.ciFailures > 0) {
        lines.push(`   ⚠️ CI Failures: ${summary.ciFailures} (may indicate risk)`);
    }
    return lines.join('\n');
}
function getAllBranchContexts(project) {
    const snapshots = listBranchSnapshots(project);
    return snapshots
        .map(s => getBranchContextSummary(project, s.branch))
        .filter((s) => s !== null)
        .sort((a, b) => a.daysSinceLastActive - b.daysSinceLastActive);
}
//# sourceMappingURL=branch-snapshot.js.map