"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.doScan = doScan;
exports.doAnalyze = doAnalyze;
exports.doBlindspots = doBlindspots;
const path = __importStar(require("path"));
const figlet_1 = __importDefault(require("figlet"));
const gradient_string_1 = __importDefault(require("gradient-string"));
const utils_1 = require("../utils");
const project = (0, utils_1.getProjectName)();
function doScan(args) {
    const banner = figlet_1.default.textSync('FivoCell', { font: 'ANSI Shadow', horizontalLayout: 'fitted' });
    console.log((0, gradient_string_1.default)(['#FF6B35', '#FFAB91'])(banner));
    (0, utils_1.printDim)('Scanning codebase + building all layers...\n');
    const noRules = args.includes('--no-rules');
    const forceRules = args.includes('--force-rules');
    const scanPathArg = args.find((a, i) => i >= 1 && !a.startsWith('--'));
    const scanCwd = scanPathArg ? path.resolve(scanPathArg) : process.cwd();
    let scanProject = require('path').basename(scanCwd);
    try {
        const { detectProject } = require('../../../setup/setup');
        scanProject = detectProject(scanCwd).name;
    }
    catch { }
    try {
        const { scanCodebase } = require('../../../02-scanner/blindspots/code-scanner');
        const { populateAllLayers } = require('../../../05-community/stats/layers');
        const result = scanCodebase(scanCwd, scanProject);
        (0, utils_1.printSuccess)(`[1/2] Scanned ${result.filesScanned} files, ${result.totalLines.toLocaleString()} lines`);
        populateAllLayers({
            profile: result.profile,
            patterns: result.patterns,
            project: scanProject,
        });
        (0, utils_1.printSuccess)('[2/2] Populated all layers:');
        console.log(utils_1.C.dim('    .cell/personal/  — profile, style, errors, decisions'));
        console.log(utils_1.C.dim('    .cell/team/      — shared patterns, blind spots'));
        console.log(utils_1.C.dim('    .cell/community/ — community patterns, trends'));
        if (!noRules) {
            const { writeCellRules } = require('../../../01-context/context/agents-md');
            const rulesResult = writeCellRules(scanCwd, { overwrite: forceRules });
            const lines = [];
            if (rulesResult.agentsMd === 'written')
                lines.push('AGENTS.md');
            if (rulesResult.cursorRules === 'written')
                lines.push('.cursorrules');
            if (lines.length > 0) {
                (0, utils_1.printSuccess)(`[3/3] Wrote AI rules: ${lines.join(', ')} (idempotent — kept existing files)`);
            }
            else {
                (0, utils_1.printDim)('[3/3] AI rules: AGENTS.md + .cursorrules already present (kept as-is)');
            }
        }
        else {
            (0, utils_1.printDim)('[3/3] AI rules: skipped (--no-rules)');
        }
        try {
            const { scanDirectoryForBlindSpots, getTopFixes, getCategorySummary } = require('../../../../core/enhanced-blind-spots');
            const spots = scanDirectoryForBlindSpots(scanCwd, 200);
            const topFixes = getTopFixes(spots, 5);
            if (topFixes.length > 0) {
                console.log();
                console.log(utils_1.C.bold('  Top 5 fixes first:'));
                for (let i = 0; i < topFixes.length; i++) {
                    const s = topFixes[i];
                    console.log(`  ${utils_1.C.num(String(i + 1))}. ${s.message}`);
                    console.log(`     ${utils_1.C.dim(s.filePath + ':' + s.lineNumber)}`);
                }
            }
            const catSummary = getCategorySummary(spots);
            if (catSummary.length > 0) {
                console.log();
                (0, utils_1.printDim)('Category breakdown:');
                for (const c of catSummary.slice(0, 6)) {
                    (0, utils_1.printDim)(`    ${c.category}: ${c.count} (${c.topSeverity})`);
                }
            }
        }
        catch { }
        console.log();
        (0, utils_1.printDim)('Run: cell status');
        console.log();
        try {
            const { markFirstScan } = require('../../../setup/cell-state');
            markFirstScan();
        }
        catch { }
        try {
            const { captureCurrentBranchSnapshot } = require('../../../03-knowledge/decisions/branch-snapshot');
            captureCurrentBranchSnapshot(scanProject, scanCwd);
        }
        catch { }
    }
    catch (e) {
        (0, utils_1.printWarning)('Scan failed: ' + String(e));
        console.log();
    }
}
function doAnalyze(args) {
    console.log();
    console.log(utils_1.C.bold('  Cell AI Analysis'));
    console.log(utils_1.C.dim('  ────────────────'));
    console.log();
    const sub = args[1] || '';
    if (sub === '--save' && args[2]) {
        const category = args[2];
        console.log(utils_1.C.primary(`  Save AI insights for: ${category}`));
        console.log(utils_1.C.dim('  Paste the AI-generated response below (Ctrl+Z or Ctrl+D to finish):'));
        console.log();
        const chunks = [];
        process.stdin.on('data', (chunk) => chunks.push(chunk));
        process.stdin.on('end', () => {
            const content = Buffer.concat(chunks).toString().trim();
            if (content) {
                const { saveAIInsight } = require('../../../03-knowledge/decisions/ai-bridge');
                saveAIInsight(project, category, content);
                (0, utils_1.printSuccess)(`Insights saved: ${category}`);
                (0, utils_1.printDim)(`.cell/personal/insights/${category}.md`);
                console.log();
                process.exit(0);
            }
            else {
                (0, utils_1.printWarning)('No content provided.');
                console.log();
                process.exit(1);
            }
        });
        process.stdin.resume();
        return;
    }
    if (sub === '--show') {
        const { getAIInsights } = require('../../../03-knowledge/decisions/ai-bridge');
        const insights = getAIInsights(project);
        if (insights.length === 0) {
            (0, utils_1.printDim)('No AI insights yet. Run: cell analyze');
            console.log();
            return;
        }
        for (const i of insights) {
            console.log(utils_1.C.bold(`  ${i.category}`));
            (0, utils_1.printDim)(`${i.timestamp} | Source: ${i.source}`);
            console.log(i.content.substring(0, 300));
            (0, utils_1.printDim)('...');
            console.log();
        }
        return;
    }
    const { getAnalysisCommand } = require('../../../03-knowledge/decisions/ai-bridge');
    const { intro, prompts } = getAnalysisCommand(process.cwd());
    (0, utils_1.printDim)(intro);
    console.log();
    for (const p of prompts) {
        console.log(utils_1.C.bold(`  ━━━ ${p.title} ━━━`));
        (0, utils_1.printDim)(`Tokens: ~${p.tokensEstimate} | Category: ${p.category}`);
        console.log();
        const promptLines = p.prompt.split('\n');
        for (const line of promptLines.slice(0, 10)) {
            console.log(`  ${utils_1.C.dim('│')} ${line}`);
        }
        if (promptLines.length > 10) {
            console.log(`  ${utils_1.C.dim('│')} ... (${promptLines.length - 10} more lines)`);
        }
        console.log();
        console.log(utils_1.C.primary(`  → Copy to AI tool, get answer, then: cell analyze --save ${p.category}`));
        console.log();
    }
    (0, utils_1.printDim)('cell analyze --show    View saved insights');
    console.log();
}
function doBlindspots(args) {
    console.log();
    console.log(utils_1.C.bold('  Cell Blind Spots'));
    console.log(utils_1.C.dim('  ────────────────'));
    console.log();
    const scanPathArg = args.find((a, i) => i >= 1 && !a.startsWith('--'));
    const scanCwd = scanPathArg ? path.resolve(scanPathArg) : process.cwd();
    const topOnly = args.includes('--top');
    const topN = topOnly ? 10 : 10;
    const jsonOutput = args.includes('--json');
    try {
        const { scanDirectoryForBlindSpots, getTopFixes, getCategorySummary } = require('../../../../core/enhanced-blind-spots');
        const spots = scanDirectoryForBlindSpots(scanCwd, 200);
        const topFixes = getTopFixes(spots, topN);
        if (jsonOutput) {
            console.log(JSON.stringify({ total: spots.length, top: topFixes.slice(0, topN) }, null, 2));
            console.log();
            return;
        }
        if (topFixes.length === 0) {
            (0, utils_1.printDim)('No blind spots found. Your code looks clean!');
            console.log();
            return;
        }
        if (topOnly) {
            console.log(utils_1.C.bold(`  Top ${Math.min(topN, topFixes.length)} blind spots (of ${spots.length} total):`));
        }
        else {
            console.log(utils_1.C.bold(`  Found ${spots.length} blind spots:`));
        }
        console.log();
        for (let i = 0; i < topFixes.length; i++) {
            const s = topFixes[i];
            const severity = s.severity === 'critical' ? utils_1.C.warn('CRITICAL') : s.severity === 'high' ? utils_1.C.primary('HIGH') : utils_1.C.dim('MEDIUM');
            console.log(`  ${utils_1.C.num(String(i + 1))}. [${severity}] ${s.message}`);
            console.log(`     ${utils_1.C.dim(s.filePath + ':' + s.lineNumber)}`);
        }
        if (!topOnly) {
            const catSummary = getCategorySummary(spots);
            if (catSummary.length > 0) {
                console.log();
                (0, utils_1.printDim)('Category breakdown:');
                for (const c of catSummary.slice(0, 10)) {
                    (0, utils_1.printDim)(`    ${c.category}: ${c.count} (${c.topSeverity})`);
                }
            }
        }
        console.log();
        if (!topOnly) {
            (0, utils_1.printDim)('Tip: cell blindspots --top  for just the top 10 fixes');
            console.log();
        }
    }
    catch (e) {
        console.log(utils_1.C.warn('  Blind spot scan failed: ' + String(e)));
    }
}
//# sourceMappingURL=scan.js.map