"use strict";
/**
 * 🤖 AI Verification System - The Trust Builder
 * Tests .faf context with Claude, ChatGPT, and Gemini to prove AI understanding
 *
 * Mission: Transform "🔴 Needs improvement" → "☑️ Perfect context"
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifyWithAI = verifyWithAI;
exports.displayVerificationResults = displayVerificationResults;
exports.updateTrustWithVerification = updateTrustWithVerification;
exports.verifyCommand = verifyCommand;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const colors_1 = require("../fix-once/colors");
const file_utils_1 = require("../utils/file-utils");
const trust_cache_1 = require("../utils/trust-cache");
const yaml_1 = require("../fix-once/yaml");
/**
 * Mock AI verification for development (will be replaced with real API calls)
 */
async function mockAIVerification(model, fafContent) {
    const startTime = Date.now();
    // Simulate API delay
    await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 500));
    const fafData = (0, yaml_1.parse)(fafContent);
    // Analyze content quality
    const hasProjectGoal = fafData?.project?.goal && !fafData.project.goal.includes('!CI');
    const hasStack = fafData?.instant_context?.tech_stack;
    const hasClearDescription = fafData?.instant_context?.what_building;
    let confidence = 0;
    const suggestions = [];
    // Calculate confidence based on content quality
    if (hasProjectGoal) {
        confidence += 40;
    }
    if (hasStack) {
        confidence += 30;
    }
    if (hasClearDescription) {
        confidence += 30;
    }
    // Add some model-specific variation
    const modelVariation = {
        'claude': Math.random() * 10 - 5, // -5 to +5
        'chatgpt': Math.random() * 8 - 4, // -4 to +4  
        'gemini': Math.random() * 12 - 6 // -6 to +6
    };
    confidence += modelVariation[model] || 0;
    confidence = Math.max(0, Math.min(100, Math.round(confidence)));
    // Generate understanding based on actual content
    let understanding = '';
    if (fafData?.instant_context?.what_building) {
        understanding = `This is ${fafData.instant_context.what_building}. `;
    }
    if (fafData?.instant_context?.tech_stack) {
        understanding += `Built with ${fafData.instant_context.tech_stack}. `;
    }
    if (fafData?.project?.goal) {
        understanding += `The goal is ${fafData.project.goal}.`;
    }
    if (!understanding) {
        understanding = "Limited context available - need more project details.";
        suggestions.push("Add clear project description");
        suggestions.push("Specify main technology stack");
        suggestions.push("Define project goals and objectives");
    }
    return {
        model,
        understood: confidence > 70,
        confidence,
        understanding: understanding.trim(),
        suggestions: suggestions.length > 0 ? suggestions : undefined,
        responseTime: Date.now() - startTime
    };
}
/**
 * Test .faf context with multiple AI models
 */
async function verifyWithAI(fafPath, options = {}) {
    const models = options.models || ['claude', 'chatgpt', 'gemini'];
    const fafContent = await fs_1.promises.readFile(fafPath, 'utf-8');
    console.log(colors_1.chalk.cyan('🤖 Testing AI understanding across all models...'));
    console.log();
    const results = [];
    // Test with each AI model
    for (const model of models) {
        try {
            console.log(colors_1.chalk.dim(`   Testing with ${model}...`));
            const result = await mockAIVerification(model, fafContent);
            results.push(result);
        }
        catch (error) {
            results.push({
                model,
                understood: false,
                confidence: 0,
                understanding: `Error testing with ${model}: ${error}`,
                responseTime: 0
            });
        }
    }
    return results;
}
/**
 * Display verification results with beautiful formatting
 */
function displayVerificationResults(results, detailed = false) {
    console.log();
    for (const result of results) {
        const statusEmoji = result.understood ? '☑️' : result.confidence > 50 ? '🟡' : '🔴';
        const statusText = result.understood ? 'Perfect context' : result.confidence > 50 ? 'Good context' : 'Needs improvement';
        const modelName = result.model.charAt(0).toUpperCase() + result.model.slice(1);
        console.log(`${statusEmoji} ${modelName}: ${statusText} (${result.confidence}% confidence)`);
        if (detailed) {
            console.log(colors_1.chalk.dim(`   Understanding: "${result.understanding}"`));
            if (result.responseTime) {
                console.log(colors_1.chalk.dim(`   Response time: ${result.responseTime}ms`));
            }
            if (result.suggestions) {
                console.log(colors_1.chalk.dim('   Suggestions:'));
                result.suggestions.forEach(suggestion => {
                    console.log(colors_1.chalk.dim(`     • ${suggestion}`));
                });
            }
            console.log();
        }
    }
    // Calculate overall trust level
    const avgConfidence = Math.round(results.reduce((sum, r) => sum + r.confidence, 0) / results.length);
    const allUnderstood = results.every(r => r.understood);
    console.log();
    if (allUnderstood) {
        console.log(colors_1.chalk.green.bold('🎉 All AIs understand your project correctly!'));
        console.log(colors_1.chalk.green(`Trust Level: ${avgConfidence}% - LOCKED & LOADED`));
    }
    else {
        const understoodCount = results.filter(r => r.understood).length;
        console.log(colors_1.chalk.yellow(`📊 ${understoodCount}/${results.length} AIs have good understanding`));
        console.log(colors_1.chalk.yellow(`Trust Level: ${avgConfidence}% - Needs work`));
        console.log();
        console.log(colors_1.chalk.cyan('💡 Trust Boosters:'));
        console.log(colors_1.chalk.dim('   • Run `faf init --force` to regenerate with better context'));
        console.log(colors_1.chalk.dim('   • Add more specific project details to your .faf file'));
        console.log(colors_1.chalk.dim('   • Use `faf sync` to update with latest changes'));
    }
}
/**
 * Update Trust Dashboard with verification results
 */
async function updateTrustWithVerification(fafPath, results) {
    const avgConfidence = Math.round(results.reduce((sum, r) => sum + r.confidence, 0) / results.length);
    // Save verification results to cache for Trust Dashboard integration
    await (0, trust_cache_1.saveTrustCache)(fafPath, results);
    console.log(colors_1.chalk.dim(`🔄 Updated AI compatibility score: ${avgConfidence}%`));
    return avgConfidence;
}
/**
 * Main verify command handler
 */
async function verifyCommand(options = {}) {
    try {
        const fafPath = await (0, file_utils_1.findFafFile)();
        if (!fafPath) {
            console.log(colors_1.chalk.red('❌ No .faf file found in current directory or parent directories'));
            console.log(colors_1.chalk.dim('💡 Run `faf init` to generate your first .faf file'));
            process.exit(1);
        }
        console.log(colors_1.chalk.dim(`🔍 Verifying context: ${path_1.default.relative(process.cwd(), fafPath)}`));
        const startTime = Date.now();
        const results = await verifyWithAI(fafPath, options);
        const duration = Date.now() - startTime;
        displayVerificationResults(results, options.detailed);
        // Update trust score
        await updateTrustWithVerification(fafPath, results);
        if (options.detailed) {
            console.log();
            console.log(colors_1.chalk.dim(`⚡ Verification completed in ${duration}ms`));
        }
        // Exit with appropriate code
        const allGood = results.every(r => r.understood);
        if (!allGood) {
            process.exit(1);
        }
    }
    catch (error) {
        console.error(colors_1.chalk.red('❌ Error during AI verification:'), error);
        process.exit(1);
    }
}
//# sourceMappingURL=verify.js.map