"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.generateAnalysisPrompts = generateAnalysisPrompts;
exports.saveAIInsight = saveAIInsight;
exports.getAIInsights = getAIInsights;
exports.getAnalysisCommand = getAnalysisCommand;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const database_1 = require("../../06-memory/database/database");
const CELL_DIR = path.join(os.homedir(), '.fivo', 'cell');
// ─── Prompt Generator ──────────────────────────────────────────────────────
function generateAnalysisPrompts(projectDir) {
    const db = (0, database_1.getDb)();
    const prompts = [];
    const dir = projectDir || process.cwd();
    const projectName = path.basename(dir);
    // ── Project Identity Prompt ─────────────────────────────────────────
    const stackData = readStackFromDB(db, projectName);
    const filesList = readTopFiles(dir, 20);
    if (stackData || filesList.length > 0) {
        const stackInfo = stackData
            ? `Stack: ${stackData.frontend || 'none'} + ${stackData.backend || 'none'}\nDatabase: ${(stackData.database || ['unknown']).join(', ')}\nORM: ${stackData.orm || 'none'}\nTesting: ${(stackData.testing || ['none']).join(', ')}`
            : 'Stack: auto-detected from codebase';
        prompts.push({
            title: 'Project Identity & Purpose',
            category: 'project_identity',
            prompt: `Analyze this codebase and tell me exactly what's being built.

CONTEXT:
Project: ${projectName}
${stackInfo}
Key files:
${filesList.map(f => `  - ${f}`).join('\n')}

TASK:
1. What is this project? What problem does it solve?
2. What's the main business logic? Where is it?
3. What are the most important files/modules?
4. Is this production code, a side project, or an experiment?
5. What seems incomplete or in progress?

Answer in short, clear bullet points. No fluff. NO code snippets.`,
            tokensEstimate: 300,
        });
    }
    // ── Architecture Analysis Prompt ────────────────────────────────────
    const archData = readArchitectureFromDB(db, projectName);
    if (archData) {
        prompts.push({
            title: 'Architecture Deep Analysis',
            category: 'architecture',
            prompt: `Analyze the architecture of this project.

CONTEXT:
Project: ${projectName}
Architecture type: ${archData.type || 'unknown'}
Entry points: ${(archData.entryPoints || []).join(', ')}
Top-level structure: ${(archData.topLevelDirs || []).join(', ')}

TASK:
1. What architecture pattern is being used? (feature-based, layer-based, etc.)
2. Is this architecture appropriate for the project's size and purpose?
3. What are the architectural strengths?
4. What are the architectural weaknesses or risks?
5. If you could change ONE thing about the architecture, what would it be?

Answer in short bullet points. No fluff.`,
            tokensEstimate: 250,
        });
    }
    // ── Blind Spots Analysis Prompt ─────────────────────────────────────
    const blindSpots = readBlindSpotsFromDB(db, projectName);
    if (blindSpots.length > 0) {
        const spotSummary = blindSpots.slice(0, 10).map(b => `- ${b.value || b.description} (severity: ${b.severity || 'medium'})`).join('\n');
        prompts.push({
            title: 'Blind Spots & Issues Analysis',
            category: 'blind_spots',
            prompt: `Analyze these detected blind spots and code issues.

PROJECT: ${projectName}

DETECTED ISSUES:
${spotSummary}

TASK:
1. Which 3 issues are MOST critical and should be fixed FIRST?
2. For each of those 3: what's the root cause?
3. What's the SIMPLEST fix for each?
4. Are any of these interconnected (fixing one helps another)?
5. What's the estimated effort to fix the top 3?

Answer in short bullet points. Be specific about fixes.`,
            tokensEstimate: 300,
        });
    }
    // ── Recommendations Prompt ──────────────────────────────────────────
    const patterns = readPatternsFromDB(db, projectName);
    if (patterns.length > 0) {
        const patternSummary = patterns.slice(0, 10).map(p => `${p.category}: ${p.value} (${p.count}x)`).join('\n');
        prompts.push({
            title: 'Improvement Recommendations',
            category: 'recommendations',
            prompt: `Based on this codebase analysis, suggest improvements.

PROJECT: ${projectName}
Top patterns:
${patternSummary}
${blindSpots.length > 0 ? `\nKnown issues: ${blindSpots.length} detected` : ''}

TASK:
1. What 5 specific improvements would most benefit this project?
2. Which improvements are "quick wins" (under 1 hour)?
3. Which improvements are "strategic" (need planning)?
4. Is there any technology or library you'd recommend adding?
5. Is there anything you'd recommend REMOVING or REPLACING?

Answer in bullet points. Be actionable and specific.`,
            tokensEstimate: 250,
        });
    }
    return prompts;
}
// ─── Insight Saver ─────────────────────────────────────────────────────────
function saveAIInsight(project, category, content) {
    const db = (0, database_1.getDb)();
    db.exec(`
    CREATE TABLE IF NOT EXISTS ai_insights (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      project TEXT NOT NULL,
      category TEXT NOT NULL,
      content TEXT NOT NULL,
      source TEXT DEFAULT 'ai',
      created_at TEXT DEFAULT (datetime('now'))
    );
  `);
    db.prepare('INSERT INTO ai_insights (project, category, content) VALUES (?, ?, ?)').run(project, category, content);
    // Also save to JSON for human reading
    const insightDir = path.join(CELL_DIR, 'personal', 'insights');
    if (!fs.existsSync(insightDir))
        fs.mkdirSync(insightDir, { recursive: true });
    const insightFile = path.join(insightDir, `${category}.md`);
    fs.writeFileSync(insightFile, `# ${category}\nGenerated: ${new Date().toISOString()}\n\n${content}`, 'utf-8');
}
function getAIInsights(project) {
    const db = (0, database_1.getDb)();
    const query = project
        ? 'SELECT category, content, created_at, source FROM ai_insights WHERE project = ? ORDER BY created_at DESC'
        : 'SELECT category, content, created_at, source FROM ai_insights ORDER BY created_at DESC';
    const params = project ? [project] : [];
    try {
        const rows = db.prepare(query).all(...(params));
        return rows.map(r => ({
            category: r.category,
            content: r.content,
            timestamp: r.created_at,
            source: r.source,
        }));
    }
    catch {
        return [];
    }
}
// ─── Display ───────────────────────────────────────────────────────────────
function getAnalysisCommand(projectDir) {
    const prompts = generateAnalysisPrompts(projectDir);
    const intro = '═══ CELL AI ANALYSIS PROMPTS ═══\n\nCopy any prompt below to your AI tool (Cursor, Claude Code, etc.).\nAfter getting results, run: cell analyze --save <category>\n';
    return { intro, prompts };
}
// ─── DB Helpers ────────────────────────────────────────────────────────────
function readStackFromDB(db, project) {
    try {
        const row = db.prepare("SELECT pattern_value FROM code_patterns WHERE pattern_type = 'project_dna' AND project = ? LIMIT 1").get(project);
        if (row?.pattern_value)
            return JSON.parse(row.pattern_value);
    }
    catch { }
    return null;
}
function readArchitectureFromDB(db, project) {
    try {
        const row = db.prepare("SELECT pattern_value FROM code_patterns WHERE pattern_type = 'architecture' AND project = ? LIMIT 1").get(project);
        if (row?.pattern_value)
            return JSON.parse(row.pattern_value);
    }
    catch { }
    return null;
}
function readBlindSpotsFromDB(db, project) {
    try {
        return db.prepare("SELECT pattern_value as value, count FROM code_patterns WHERE category = 'blind_spots' AND project = ? ORDER BY count DESC LIMIT 20").all(project);
    }
    catch {
        return [];
    }
}
function readPatternsFromDB(db, project) {
    try {
        return db.prepare("SELECT category, pattern_value as value, count FROM code_patterns WHERE project = ? AND category IN ('style','naming','functions','architecture','testing') ORDER BY count DESC LIMIT 20").all(project);
    }
    catch {
        return [];
    }
}
function readTopFiles(dir, limit) {
    try {
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        return entries
            .filter(e => e.isFile() && !e.name.startsWith('.'))
            .slice(0, limit)
            .map(e => e.name);
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=ai-bridge.js.map