"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.doStatus = doStatus;
exports.doDoctor = doDoctor;
exports.doVerify = doVerify;
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const os = __importStar(require("os"));
const utils_1 = require("../utils");
const project = (0, utils_1.getProjectName)();
function doStatus() {
    (0, utils_1.printHeader)('Cell Status');
    const cwd = process.cwd();
    const cellRoot = path.join(cwd, '.cell');
    // Project info
    console.log(utils_1.C.bold('  Project:'), utils_1.C.num(project));
    console.log();
    // Daemon status
    (0, utils_1.isDaemonRunning)().then(running => {
        if (running) {
            (0, utils_1.printSuccess)('Daemon: running on http://localhost:9876');
        }
        else {
            (0, utils_1.printWarning)('Daemon: not running (run: cell start)');
        }
    }).catch(() => {
        (0, utils_1.printWarning)('Daemon: not running');
    });
    // .cell folder
    if (fs.existsSync(cellRoot)) {
        const files = countFiles(cellRoot);
        (0, utils_1.printSuccess)(`.cell/: exists (${files} files)`);
    }
    else {
        (0, utils_1.printWarning)('.cell/: not found (run: cell scan)');
    }
    // DB
    const dbPath = path.join(os.homedir(), '.fivo', 'cell', 'cell.db');
    if (fs.existsSync(dbPath)) {
        const stat = fs.statSync(dbPath);
        const sizeMB = (stat.size / 1024 / 1024).toFixed(1);
        (0, utils_1.printSuccess)(`Database: ${sizeMB} MB`);
    }
    else {
        (0, utils_1.printWarning)('Database: not found');
    }
    console.log();
}
async function doDoctor() {
    (0, utils_1.printHeader)('Cell Doctor — Health Check');
    const cwd = process.cwd();
    const critical = [];
    const warnings = [];
    const passes = [];
    // 1. Git repo
    const gitDir = path.join(cwd, '.git');
    if (fs.existsSync(gitDir)) {
        passes.push('git');
    }
    else {
        warnings.push('Git repo not found (optional, but recommended)');
    }
    // 2. Node/TypeScript project
    const pkgJson = path.join(cwd, 'package.json');
    if (fs.existsSync(pkgJson)) {
        passes.push('node');
    }
    else {
        warnings.push('No package.json found (non-Node project?)');
    }
    // 3. .cell folder
    const cellDir = path.join(cwd, '.cell');
    if (fs.existsSync(cellDir)) {
        const personalDir = path.join(cellDir, 'personal');
        const fileCount = fs.existsSync(personalDir) ? fs.readdirSync(personalDir).length : 0;
        passes.push('cell-dir');
    }
    else {
        warnings.push('No .cell/ folder found (run: cell scan)');
    }
    // 4. SQLite DB
    const dbPath = path.join(os.homedir(), '.fivo', 'cell', 'cell.db');
    if (fs.existsSync(dbPath)) {
        try {
            const stat = fs.statSync(dbPath);
            const sizeMB = (stat.size / 1024 / 1024).toFixed(1);
            passes.push('db');
        }
        catch {
            critical.push('SQLite DB exists but not readable');
        }
    }
    else {
        critical.push('No SQLite DB found');
    }
    // 5. Last scan
    const { detectProject, checkScanState, checkWatchState, checkMcpState } = require('../../setup/setup');
    const proj = detectProject(cwd);
    const scan = checkScanState(cwd);
    if (scan.done) {
        passes.push('scan');
    }
    else {
        warnings.push(`No scan found (${scan.reason})`);
    }
    // 6. Daemon
    const daemonUp = await (0, utils_1.isDaemonRunning)();
    if (daemonUp) {
        passes.push('daemon');
    }
    else {
        warnings.push('Daemon not running (run: cell start)');
    }
    // 7. Watcher
    const watch = checkWatchState(proj.name);
    if (watch.done) {
        passes.push('watcher');
    }
    else {
        warnings.push(`Watcher not active (${watch.reason})`);
    }
    // 8. MCP config
    const mcp = checkMcpState(os.homedir());
    if (mcp.done > 0) {
        passes.push('mcp');
    }
    else {
        warnings.push('No MCP configs found (run: cell mcp-config)');
    }
    // 9. Key provider
    try {
        const { getKeyProviderConfidence } = require('../../../06-memory/privacy/key-provider');
        const conf = getKeyProviderConfidence();
        if (conf.level === 'high') {
            passes.push('key-provider');
        }
        else if (conf.level === 'medium') {
            warnings.push(`Key provider: medium confidence (${conf.reason})`);
        }
        else {
            critical.push(`Key provider: low confidence (${conf.reason})`);
        }
    }
    catch {
        // skip
    }
    // 10. FTS health
    try {
        const { getFtsHealth } = require('../../../06-memory/stores/memory-search');
        const fts = getFtsHealth();
        if (fts.status === 'healthy' || fts.status === 'empty') {
            passes.push('fts');
        }
        else if (fts.status === 'degraded') {
            critical.push(`FTS degraded: ${fts.ratio}% indexed`);
        }
        else {
            warnings.push(`FTS: ${fts.status}`);
        }
    }
    catch {
        // skip
    }
    // 11. Mirror health
    try {
        const { verifyCellHealth } = require('../../../06-memory/mirror/cell-mirror');
        const health = verifyCellHealth(cwd);
        if (health.status === 'healthy' || health.status === 'fresh') {
            passes.push('mirror');
        }
        else if (health.status === 'broken') {
            critical.push(`Mirror broken: ${health.issues.length} issues`);
        }
        else {
            warnings.push(`Mirror: ${health.status}`);
        }
    }
    catch {
        // skip
    }
    // 12. DB tables (informational)
    try {
        const { getDb } = require('../../../06-memory/database/database');
        const db = getDb();
        const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();
        let withData = 0;
        let empty = 0;
        for (const { name } of tables) {
            try {
                const row = db.prepare(`SELECT COUNT(*) as c FROM "${name}"`).get();
                if (row.c > 0)
                    withData++;
                else
                    empty++;
            }
            catch {
                empty++;
            }
        }
        if (empty > 20) {
            warnings.push(`Database: ${tables.length} tables (${withData} with data, ${empty} empty — normal for fresh installs)`);
        }
        else {
            passes.push('db-tables');
        }
    }
    catch {
        // skip
    }
    // ─── Output ──────────────────────────────────────────────────────────
    console.log();
    const total = critical.length + warnings.length + passes.length;
    if (critical.length > 0) {
        console.log(utils_1.C.bold('  🔴 CRITICAL:'));
        for (const c of critical) {
            console.log(utils_1.C.warn(`    - ${c}`));
        }
    }
    if (warnings.length > 0) {
        console.log(utils_1.C.bold('  🟡 WARNING:'));
        for (const w of warnings) {
            console.log(utils_1.C.dim(`    - ${w}`));
        }
    }
    if (passes.length > 0) {
        console.log(utils_1.C.bold('  ✅ OK:'));
        for (const p of passes) {
            console.log(utils_1.C.success(`    - ${p}`));
        }
    }
    console.log();
    if (critical.length === 0 && warnings.length === 0) {
        console.log(utils_1.C.success(`  All ${total} checks passed. Cell is fully healthy.`));
    }
    else if (critical.length > 0) {
        console.log(utils_1.C.warn(`  ${critical.length} critical, ${warnings.length} warnings, ${passes.length} OK`));
    }
    else {
        console.log(utils_1.C.dim(`  ${warnings.length} warnings, ${passes.length} OK — no critical issues`));
    }
    console.log();
}
function doVerify() {
    (0, utils_1.printHeader)('Cell Verify — Data Health');
    const cwd = process.cwd();
    let allHealthy = true;
    // Mirror health
    try {
        const { verifyCellHealth } = require('../../../06-memory/mirror/cell-mirror');
        const health = verifyCellHealth(cwd);
        if (health.status === 'healthy' || health.status === 'fresh') {
            (0, utils_1.printSuccess)(`Mirror: ${health.status}`);
        }
        else {
            (0, utils_1.printWarning)(`Mirror: ${health.status} (${health.issues.length} issues)`);
            allHealthy = false;
        }
    }
    catch {
        (0, utils_1.printDim)('Mirror check skipped');
    }
    // FTS health
    try {
        const { getFtsHealth } = require('../../../06-memory/stores/memory-search');
        const fts = getFtsHealth();
        if (fts.status === 'healthy' || fts.status === 'empty') {
            (0, utils_1.printSuccess)(`FTS: ${fts.status} (${fts.ratio}%)`);
        }
        else {
            (0, utils_1.printWarning)(`FTS: ${fts.status} (${fts.ratio}%)`);
            allHealthy = false;
        }
    }
    catch {
        (0, utils_1.printDim)('FTS check skipped');
    }
    // Key provider
    try {
        const { getKeyProviderConfidence } = require('../../../06-memory/privacy/key-provider');
        const conf = getKeyProviderConfidence();
        if (conf.level === 'high') {
            (0, utils_1.printSuccess)(`Key provider: ${conf.level}`);
        }
        else {
            (0, utils_1.printWarning)(`Key provider: ${conf.level} — ${conf.reason}`);
            if (conf.level === 'low')
                allHealthy = false;
        }
    }
    catch {
        (0, utils_1.printDim)('Key provider check skipped');
    }
    // Summary
    console.log();
    if (allHealthy) {
        console.log(utils_1.C.success('  ✅ All subsystems healthy'));
    }
    else {
        console.log(utils_1.C.warn('  ❌ Issues found — run cell doctor for details'));
    }
    console.log();
    process.exit(allHealthy ? 0 : 1);
}
function countFiles(dir) {
    let count = 0;
    try {
        for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
            if (entry.isDirectory()) {
                count += countFiles(path.join(dir, entry.name));
            }
            else {
                count++;
            }
        }
    }
    catch { }
    return count;
}
//# sourceMappingURL=status.js.map