"use strict";
/**
 * 🧡 Trust Dashboard Command - The Emotional Core
 * Transforms developer psychology from hope-driven to trust-driven AI development
 *
 * Mission: "I don't worry about AI context complexity anymore"
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.calculateTrustScore = calculateTrustScore;
exports.displayTrustDashboard = displayTrustDashboard;
exports.trustCommand = trustCommand;
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 faf_compiler_1 = require("../compiler/faf-compiler");
const trust_cache_1 = require("../utils/trust-cache");
const yaml_1 = require("../fix-once/yaml");
/**
 * Calculate comprehensive trust score based on .faf quality
 */
async function calculateTrustScore(fafPath) {
    try {
        const fafContent = await fs_1.promises.readFile(fafPath, 'utf-8');
        const fafData = (0, yaml_1.parse)(fafContent);
        // Basic validation - check if essential sections exist
        const isValid = fafData &&
            typeof fafData === 'object' &&
            fafData.project &&
            fafData.metadata;
        // Calculate context completeness using existing scoring
        const compiler = new faf_compiler_1.FafCompiler();
        const scoreResult = await compiler.compile(fafPath);
        const contextCompleteness = scoreResult.score || 0;
        // Calculate freshness (based on timestamp if available)
        const freshnessScore = calculateFreshness(fafData);
        // AI compatibility enhanced with verification
        const aiCompatibility = await calculateAICompatibility(fafPath, fafData, isValid);
        // Overall trust calculation (weighted average)
        const overall = Math.round((contextCompleteness * 0.4) +
            (aiCompatibility * 0.3) +
            (freshnessScore * 0.2) +
            (isValid ? 10 : 0));
        return {
            overall: Math.min(overall, 100),
            contextCompleteness,
            aiCompatibility,
            freshnessScore,
            verificationStatus: isValid ? 'unverified' : 'failed'
        };
    }
    catch {
        return {
            overall: 0,
            contextCompleteness: 0,
            aiCompatibility: 0,
            freshnessScore: 0,
            verificationStatus: 'failed'
        };
    }
}
/**
 * Calculate AI compatibility based on content quality and cached verification results
 */
async function calculateAICompatibility(fafPath, fafData, isValid) {
    // Check for cached verification results first
    const cachedResults = await (0, trust_cache_1.getTrustCache)(fafPath);
    if (cachedResults) {
        // Use verified AI compatibility score
        return cachedResults.aiCompatibilityScore;
    }
    // Fallback to content-based scoring
    if (!isValid) {
        return 30;
    }
    let score = 50; // Base score for valid files
    // Check for championship content (no placeholders)
    const hasGoodGoal = fafData?.project?.goal &&
        !fafData.project.goal.includes('!CI') &&
        fafData.project.goal !== 'Project development and deployment';
    const hasGoodDescription = fafData?.instant_context?.what_building &&
        !fafData.instant_context.what_building.includes('!CI') &&
        fafData.instant_context.what_building !== 'Software application';
    const hasRevolutionaryContent = fafData?.project?.mission?.includes('Make Your AI Happy');
    const hasTechStack = fafData?.instant_context?.tech_stack &&
        fafData.instant_context.tech_stack !== 'Unknown';
    // Championship scoring
    if (hasGoodGoal) {
        score += 15;
    }
    if (hasGoodDescription) {
        score += 15;
    }
    if (hasRevolutionaryContent) {
        score += 10;
    } // Brand ambassador bonus
    if (hasTechStack) {
        score += 10;
    }
    return Math.min(score, 100);
}
/**
 * Calculate freshness score based on timestamp
 */
function calculateFreshness(fafData) {
    try {
        const timestamp = fafData?.metadata?.updated_date || fafData?.metadata?.created_date;
        if (!timestamp) {
            return 50;
        } // No timestamp = middle score
        const lastUpdate = new Date(timestamp);
        const now = new Date();
        const daysDiff = (now.getTime() - lastUpdate.getTime()) / (1000 * 60 * 60 * 24);
        // Freshness scoring: 100% for <7 days, declining to 0% at 90+ days
        if (daysDiff < 7) {
            return 100;
        }
        if (daysDiff < 30) {
            return Math.max(80 - ((daysDiff - 7) * 2), 50);
        }
        if (daysDiff < 90) {
            return Math.max(50 - ((daysDiff - 30) * 0.8), 10);
        }
        return 10; // Very stale
    }
    catch {
        return 50; // Default middle score
    }
}
/**
 * Display the Trust Dashboard - the emotional core UI
 */
async function displayTrustDashboard(fafPath, trustScore, detailed = false) {
    const { overall, contextCompleteness, aiCompatibility, freshnessScore } = trustScore;
    // Choose emoji and color based on trust level
    let trustEmoji = '🧡';
    let trustColor = colors_1.chalk.green;
    let trustMessage = 'LOCKED & LOADED';
    if (overall >= 90) {
        trustEmoji = '🧡';
        trustColor = colors_1.chalk.green.bold;
        trustMessage = 'LOCKED & LOADED';
    }
    else if (overall >= 75) {
        trustEmoji = '🟡';
        trustColor = colors_1.chalk.yellow;
        trustMessage = 'GOOD TO GO';
    }
    else if (overall >= 50) {
        trustEmoji = '🟠';
        trustColor = colors_1.chalk.yellow;
        trustMessage = 'NEEDS WORK';
    }
    else {
        trustEmoji = '🔴';
        trustColor = colors_1.chalk.red;
        trustMessage = 'NEEDS ATTENTION';
    }
    // Main Trust Dashboard
    console.log();
    console.log(colors_1.chalk.cyan('┌─ AI TRUST DASHBOARD ───────────────────┐'));
    console.log(colors_1.chalk.cyan('│') + trustColor(` ${trustEmoji} TRUST LEVEL: ${overall}% (${trustMessage})`) + ' '.repeat(Math.max(0, 40 - ` ${trustEmoji} TRUST LEVEL: ${overall}% (${trustMessage})`.length)) + colors_1.chalk.cyan('│'));
    console.log(colors_1.chalk.cyan('│                                        │'));
    console.log(`${colors_1.chalk.cyan('│')} AI UNDERSTANDING STATUS:              ${colors_1.chalk.cyan('│')}`);
    // Get verification status from cache
    const cachedResults = await (0, trust_cache_1.getTrustCache)(fafPath);
    let claudeStatus, chatgptStatus, geminiStatus;
    if (cachedResults && cachedResults.allPassed) {
        // Show verified results
        claudeStatus = `☑️ Claude     - Perfect context (${cachedResults.verificationResults.claude}%)`;
        chatgptStatus = `☑️ ChatGPT    - Perfect context (${cachedResults.verificationResults.chatgpt}%)`;
        geminiStatus = `☑️ Gemini     - Perfect context (${cachedResults.verificationResults.gemini}%)`;
    }
    else {
        // Show content-based assessment
        claudeStatus = aiCompatibility >= 80 ? '☑️ Claude     - Perfect context       ' : aiCompatibility >= 60 ? '🟡 Claude     - Good context          ' : '🔴 Claude     - Needs improvement     ';
        chatgptStatus = aiCompatibility >= 80 ? '☑️ ChatGPT    - Perfect context       ' : aiCompatibility >= 60 ? '🟡 ChatGPT    - Good context          ' : '🔴 ChatGPT    - Needs improvement     ';
        geminiStatus = aiCompatibility >= 80 ? '☑️ Gemini     - Perfect context       ' : aiCompatibility >= 60 ? '🟡 Gemini     - Good context          ' : '🔴 Gemini     - Needs improvement     ';
    }
    console.log(`${colors_1.chalk.cyan('│')} ${claudeStatus} ${colors_1.chalk.cyan('│')}`);
    console.log(`${colors_1.chalk.cyan('│')} ${chatgptStatus} ${colors_1.chalk.cyan('│')}`);
    console.log(`${colors_1.chalk.cyan('│')} ${geminiStatus} ${colors_1.chalk.cyan('│')}`);
    console.log(colors_1.chalk.cyan('│                                        │'));
    // Action message
    const actionMessage = overall >= 85 ? '💚 GO BUILD: Context locked & loaded  ' : '🔧 ACTION: Improve context quality    ';
    console.log(`${colors_1.chalk.cyan('│')} ${actionMessage} ${colors_1.chalk.cyan('│')}`);
    console.log(colors_1.chalk.cyan('└────────────────────────────────────────┘'));
    if (detailed) {
        console.log();
        console.log(colors_1.chalk.cyan('📊 Detailed Trust Metrics:'));
        console.log(`  Context Completeness: ${contextCompleteness}%`);
        console.log(`  AI Compatibility: ${aiCompatibility}%`);
        console.log(`  Freshness Score: ${freshnessScore}%`);
        console.log(`  Overall Trust: ${overall}%`);
    }
    // Actionable suggestions
    if (overall < 85) {
        console.log();
        console.log(colors_1.chalk.yellow('💡 Trust Boosters:'));
        if (contextCompleteness < 75) {
            console.log(colors_1.chalk.dim('   • Run `faf init` to improve context completeness'));
        }
        if (freshnessScore < 50) {
            console.log(colors_1.chalk.dim('   • Run `faf sync` to refresh stale information'));
        }
        if (!cachedResults) {
            console.log(colors_1.chalk.dim('   • Run `faf verify` to test AI understanding and update scores'));
        }
    }
    else if (cachedResults) {
        console.log();
        console.log(colors_1.chalk.green('☑️ Verified by AI models - context is championship grade!'));
    }
    console.log();
}
// =====================================
// TRUST MODE FUNCTIONS
// =====================================
async function showConfidenceMode(fafPath) {
    const trustScore = await calculateTrustScore(fafPath);
    console.log(colors_1.chalk.cyan('🤖 AI Confidence Analysis'));
    console.log(`├─ Claude Confidence: ${trustScore.aiCompatibility}%`);
    console.log(`├─ Context Completeness: ${trustScore.contextCompleteness}%`);
    console.log(`└─ Overall AI Trust: ${trustScore.overall}%`);
    if (trustScore.overall < 70) {
        console.log('\n💡 Boost confidence with:');
        console.log('   • faf todo - Complete improvement tasks');
        console.log('   • faf verify - Test with AI models');
    }
}
async function showGarageMode(fafPath) {
    console.log(colors_1.chalk.green('🔧 Safe Experimentation Garage'));
    console.log('├─ Backup created: .faf.garage-backup');
    console.log('├─ Safe to experiment with context changes');
    console.log('└─ Restore anytime with: faf trust --panic');
    // Create backup for safe experimentation
    const backupPath = `${fafPath}.garage-backup`;
    const fafContent = await fs_1.promises.readFile(fafPath, 'utf-8');
    await fs_1.promises.writeFile(backupPath, fafContent);
}
async function showPanicMode(fafPath) {
    console.log(colors_1.chalk.red('🚨 Emergency Context Repair'));
    // Look for backup files
    const backupPath = `${fafPath}.garage-backup`;
    const backupExists = await fs_1.promises.access(backupPath).then(() => true).catch(() => false);
    if (backupExists) {
        console.log('├─ Garage backup found - restoring...');
        const backupContent = await fs_1.promises.readFile(backupPath, 'utf-8');
        await fs_1.promises.writeFile(fafPath, backupContent);
        console.log('└─ ☑️ Context restored from garage backup!');
    }
    else {
        console.log('├─ No garage backup found');
        console.log('├─ Running emergency diagnostics...');
        console.log('└─ Run: faf check --fix for auto-repair');
    }
}
async function showQualityMode(fafPath) {
    console.log(colors_1.chalk.blue('🛡️ Quality Check Mode'));
    console.log('├─ Running comprehensive quality checks...');
    const trustScore = await calculateTrustScore(fafPath);
    // Just show the score
    console.log(`└─ Trust Score: ${trustScore.overall}%`);
}
/**
 * Main trust command handler
 */
async function trustCommand(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'));
            return; // Let analytics wrapper handle footer display
        }
        // Handle specific trust modes
        if (options.confidence) {
            await showConfidenceMode(fafPath);
            return;
        }
        if (options.garage) {
            await showGarageMode(fafPath);
            return;
        }
        if (options.panic) {
            await showPanicMode(fafPath);
            return;
        }
        if (options.quality) {
            await showQualityMode(fafPath);
            return;
        }
        console.log(colors_1.chalk.dim(`🧡 Calculating trust for: ${path_1.default.relative(process.cwd(), fafPath)}`));
        const startTime = Date.now();
        const trustScore = await calculateTrustScore(fafPath);
        const duration = Date.now() - startTime;
        await displayTrustDashboard(fafPath, trustScore, options.detailed);
        // Performance indicator (should be <300ms)
        if (options.detailed) {
            console.log(colors_1.chalk.dim(`⚡ Performance: ${duration}ms`));
        }
    }
    catch (error) {
        console.error(colors_1.chalk.red('❌ Error calculating trust score:'), error);
        process.exit(1);
    }
}
//# sourceMappingURL=trust.js.map