"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.doMemory = doMemory;
exports.doHandoff = doHandoff;
exports.doReplay = doReplay;
exports.doContinue = doContinue;
const utils_1 = require("../utils");
const project = (0, utils_1.getProjectName)();
function doMemory(args) {
    (0, utils_1.printHeader)('Cell Memory');
    const sub = args[1] || '';
    if (sub === 'doctor') {
        doMemoryDoctor();
        return;
    }
    if (sub === 'search') {
        const query = args[2] || '';
        if (!query) {
            (0, utils_1.printWarning)('Usage: cell memory search <query>');
            return;
        }
        (0, utils_1.httpGet)(`/memory/search?q=${encodeURIComponent(query)}&project=${project}`).then((result) => {
            if (result.results && result.results.length > 0) {
                for (const r of result.results.slice(0, 10)) {
                    console.log(`  [${r.type}] ${r.summary}`);
                    (0, utils_1.printDim)(`  ${r.created_at} | Importance: ${r.importance}`);
                }
            }
            else {
                (0, utils_1.printDim)('No results found');
            }
        }).catch(() => (0, utils_1.printWarning)('Search failed'));
        return;
    }
    if (sub === 'timeline') {
        const days = parseInt(args[2] || '7');
        (0, utils_1.httpGet)(`/memory/timeline?project=${project}&days=${days}`).then((result) => {
            if (result.timeline && result.timeline.length > 0) {
                for (const day of result.timeline) {
                    console.log(`  ${day.date}: ${day.count} events`);
                }
            }
            else {
                (0, utils_1.printDim)('No timeline data');
            }
        }).catch(() => (0, utils_1.printWarning)('Timeline failed'));
        return;
    }
    // Default: show memory stats
    (0, utils_1.httpGet)('/memory/stats').then((result) => {
        console.log(utils_1.C.bold('  Memory Statistics:'));
        console.log();
        if (result.tables) {
            for (const [table, info] of Object.entries(result.tables)) {
                const count = info.rows || 0;
                if (count > 0) {
                    (0, utils_1.printSuccess)(`  ${table}: ${count} rows`);
                }
            }
        }
        console.log();
        (0, utils_1.printDim)('Commands: cell memory search <query>, cell memory timeline, cell memory doctor');
    }).catch(() => (0, utils_1.printWarning)('Failed to get memory stats'));
}
function doMemoryDoctor() {
    (0, utils_1.printHeader)('Cell Memory Doctor');
    // Check mirror health
    try {
        const { verifyCellHealth } = require('../../../06-memory/mirror/cell-mirror');
        const health = verifyCellHealth(process.cwd());
        console.log(utils_1.C.bold('  Mirror Health:'));
        console.log(`    Status: ${health.status}`);
        console.log(`    Files: ${health.totalFiles}`);
        if (health.issues.length > 0) {
            console.log(`    Issues: ${health.issues.length}`);
            for (const issue of health.issues.slice(0, 5)) {
                (0, utils_1.printWarning)(`      - ${issue}`);
            }
        }
        if (health.warnings && health.warnings.length > 0) {
            console.log(`    Warnings: ${health.warnings.length}`);
            for (const warn of health.warnings.slice(0, 5)) {
                (0, utils_1.printDim)(`      - ${warn}`);
            }
        }
        console.log();
    }
    catch {
        (0, utils_1.printDim)('Mirror check skipped');
    }
    // Check archive integrity
    try {
        const { verifyArchiveIntegrity } = require('../../../06-memory/archive/archive-versioning');
        const integrity = verifyArchiveIntegrity(process.cwd());
        console.log(utils_1.C.bold('  Archive Integrity:'));
        console.log(`    Total chunks: ${integrity.totalChunks}`);
        console.log(`    Versioned: ${integrity.versionedChunks}`);
        console.log(`    Unversioned: ${integrity.unversionedChunks}`);
        if (integrity.issues.length > 0) {
            for (const issue of integrity.issues.slice(0, 5)) {
                (0, utils_1.printWarning)(`      - ${issue}`);
            }
        }
        console.log();
    }
    catch {
        (0, utils_1.printDim)('Archive check skipped');
    }
    // Check FTS health
    try {
        const { getFtsHealth } = require('../../../06-memory/stores/memory-search');
        const fts = getFtsHealth();
        console.log(utils_1.C.bold('  FTS Health:'));
        console.log(`    Status: ${fts.status}`);
        console.log(`    Events: ${fts.eventCount}`);
        console.log(`    Indexed: ${fts.ftsCount}`);
        console.log(`    Ratio: ${fts.ratio}%`);
        (0, utils_1.printDim)(`    ${fts.message}`);
        console.log();
    }
    catch {
        (0, utils_1.printDim)('FTS check skipped');
    }
    // Memory stats
    try {
        const { getMemoryStats } = require('../../../03-knowledge/decisions/ai-memory');
        const stats = getMemoryStats();
        console.log(utils_1.C.bold('  Memory Stats:'));
        console.log(`    Events: ${stats.totalEvents || 0}`);
        console.log(`    Archives: ${stats.totalArchives || 0}`);
        console.log(`    Summaries: ${stats.totalSummaries || 0}`);
        console.log();
    }
    catch {
        (0, utils_1.printDim)('Memory stats skipped');
    }
}
function doHandoff(args) {
    (0, utils_1.printHeader)('Cell Handoff');
    const sub = args[1] || '';
    if (sub === 'log') {
        const title = args[2] || '';
        const summary = args[3] || '';
        const status = args[4] || 'done';
        if (!title || !summary) {
            (0, utils_1.printWarning)('Usage: cell handoff log <title> <summary> [status]');
            return;
        }
        (0, utils_1.httpPost)('/handoff/log', {
            project,
            title,
            summary,
            status,
            filesChanged: [],
            why: '',
            nextSteps: '',
        }).then(() => {
            (0, utils_1.printSuccess)('Handoff logged');
        }).catch(() => (0, utils_1.printWarning)('Failed to log handoff'));
        return;
    }
    if (sub === 'history') {
        const month = args[2] || new Date().toISOString().slice(0, 7);
        (0, utils_1.httpGet)(`/handoff/history?project=${project}&month=${month}`).then((result) => {
            if (result.history && result.history.length > 0) {
                for (const h of result.history) {
                    console.log(`  [${h.status}] ${h.title}`);
                    (0, utils_1.printDim)(`  ${h.created_at}`);
                }
            }
            else {
                (0, utils_1.printDim)('No handoff history');
            }
        }).catch(() => (0, utils_1.printWarning)('Failed to get handoff history'));
        return;
    }
    // Default: show current handoff
    try {
        const { getCurrentHandoff } = require('../../../06-memory/handoff/handoff-store');
        const handoff = getCurrentHandoff(process.cwd());
        if (handoff && !handoff.includes('No handoff entries yet')) {
            console.log(handoff);
        }
        else {
            (0, utils_1.printDim)('No current handoff. Log one with: cell handoff log <title> <summary>');
        }
    }
    catch {
        (0, utils_1.printDim)('Could not load handoff');
    }
}
function doReplay(args) {
    (0, utils_1.printHeader)('Cell Memory Replay');
    const sub = args[1] || '';
    const query = args[2] || '';
    if (sub === '--last') {
        (0, utils_1.httpGet)(`/session/history?project=${project}&limit=1`).then((result) => {
            if (result.sessions && result.sessions.length > 0) {
                const s = result.sessions[0];
                console.log(`  Session: ${s.tool} (${s.startTime})`);
                console.log(`  Files: ${s.filesCount}`);
                console.log(`  Decisions: ${s.decisionsCount}`);
            }
            else {
                (0, utils_1.printDim)('No recent sessions');
            }
        }).catch(() => (0, utils_1.printWarning)('Failed to get session'));
        return;
    }
    if (query) {
        (0, utils_1.httpGet)(`/memory/search?q=${encodeURIComponent(query)}&project=${project}&limit=20`).then((result) => {
            if (result.results && result.results.length > 0) {
                for (const r of result.results) {
                    console.log(`  [${r.type}] ${r.summary}`);
                    (0, utils_1.printDim)(`  ${r.created_at}`);
                }
            }
            else {
                (0, utils_1.printDim)('No matching events');
            }
        }).catch(() => (0, utils_1.printWarning)('Replay failed'));
        return;
    }
    // Default: show recent events
    (0, utils_1.httpGet)(`/memory/timeline?project=${project}&days=7`).then((result) => {
        if (result.timeline && result.timeline.length > 0) {
            for (const day of result.timeline) {
                console.log(`  ${day.date}: ${day.count} events`);
            }
        }
        else {
            (0, utils_1.printDim)('No recent events. Start using Cell to build memory.');
        }
    }).catch(() => (0, utils_1.printWarning)('Replay failed'));
}
function doContinue() {
    (0, utils_1.printHeader)('Cell Continue');
    (0, utils_1.httpGet)(`/session/history?project=${project}&limit=1`).then((result) => {
        if (result.sessions && result.sessions.length > 0) {
            const s = result.sessions[0];
            console.log(`  Last session: ${s.tool} (${s.startTime})`);
            console.log(`  Files touched: ${s.filesCount}`);
            console.log(`  Key decisions: ${s.decisionsCount}`);
            console.log();
            (0, utils_1.printDim)('Use @cell in your AI tool to get full context.');
        }
        else {
            (0, utils_1.printDim)('No previous session found. Start with: cell scan');
        }
    }).catch(() => (0, utils_1.printWarning)('Failed to get session'));
}
//# sourceMappingURL=memory.js.map