"use strict";
/**
 * 🏎️ faf score v3 - Compiler-based scoring
 * Deterministic, traceable, reproducible scores
 */
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.scoreCommandV3 = scoreCommandV3;
const colors_1 = require("../fix-once/colors");
const faf_compiler_1 = require("../compiler/faf-compiler");
const file_utils_1 = require("../utils/file-utils");
const faf_dna_1 = require("../engines/faf-dna");
const championship_style_1 = require("../utils/championship-style");
const path = __importStar(require("path"));
async function scoreCommandV3(file, options = {}) {
    // Quiet mode check
    const isQuiet = process.argv.includes('--quiet');
    try {
        // Find .faf file
        let fafPath;
        if (file) {
            // Check if file is a direct path to a .faf file
            if (file.endsWith('.faf') || file.endsWith('.faf.fixed')) {
                fafPath = file;
            }
            else {
                fafPath = await (0, file_utils_1.findFafFile)(file);
            }
        }
        else {
            fafPath = await (0, file_utils_1.findFafFile)();
        }
        if (!fafPath) {
            if (file) {
                console.error(colors_1.chalk.red(`❌ No .faf file found at: ${file}`));
                console.log(colors_1.chalk.yellow(`💡 Check the path or run "faf init" in that directory`));
            }
            else {
                console.error(colors_1.chalk.red("❌ No .faf file found in current directory"));
                console.log(colors_1.chalk.yellow('💡 Run "faf init" to create one'));
            }
            process.exit(1);
        }
        // Verify mode
        if (options.verify) {
            const compiler = new faf_compiler_1.FafCompiler();
            const isValid = await compiler.verify(fafPath, options.verify);
            if (isValid) {
                console.log(colors_1.chalk.green(`✅ Checksum ${options.verify} verified`));
            }
            else {
                console.log(colors_1.chalk.red(`❌ Checksum mismatch`));
                process.exit(1);
            }
            return;
        }
        // Create compiler
        const compiler = new faf_compiler_1.FafCompiler();
        // Compile with or without trace
        const result = options.trace
            ? await compiler.compileWithTrace(fafPath)
            : await compiler.compile(fafPath);
        // Show IR if requested
        if (options.ir) {
            console.log(colors_1.chalk.cyan("\n📋 Intermediate Representation:"));
            console.log(JSON.stringify(result.ir, null, 2));
            return;
        }
        // Show breakdown if requested
        if (options.breakdown) {
            console.log(colors_1.chalk.cyan("\n📊 Score Breakdown:"));
            console.log(colors_1.chalk.gray("─".repeat(40)));
            const sections = result.breakdown;
            console.log(`Project:   ${sections.project.filled}/${sections.project.total} slots (${sections.project.percentage}%)`);
            console.log(`Stack:     ${sections.stack.filled}/${sections.stack.total} slots (${sections.stack.percentage}%)`);
            console.log(`Human:     ${sections.human.filled}/${sections.human.total} slots (${sections.human.percentage}%)`);
            if (sections.discovery.total > 0) {
                console.log(`Discovery: ${sections.discovery.filled}/${sections.discovery.total} slots (${sections.discovery.percentage}%)`);
            }
            console.log(colors_1.chalk.gray("─".repeat(40)));
        }
        // Show verbose details
        if (options.verbose) {
            console.log(colors_1.chalk.cyan("\n🔍 Compilation Details:"));
            console.log(`Version:    ${result.trace.version}`);
            console.log(`Input Hash: ${result.trace.inputHash}`);
            console.log(`Passes:     ${result.trace.passes.length}`);
            console.log(`Duration:   ${result.trace.passes.reduce((sum, p) => sum + p.duration, 0)}ms`);
            if (result.diagnostics.length > 0) {
                console.log(colors_1.chalk.yellow(`\n⚠️ ${result.diagnostics.length} Diagnostics:`));
                result.diagnostics.forEach(d => {
                    const icon = d.severity === 'error' ? '❌' : d.severity === 'warning' ? '⚠️' : 'ℹ️';
                    console.log(`  ${icon} ${d.message}`);
                    if (d.suggestion) {
                        console.log(colors_1.chalk.gray(`     → ${d.suggestion}`));
                    }
                });
            }
        }
        // Try to show with DNA (birth weight)
        const projectPath = path.dirname(fafPath);
        const dnaManager = new faf_dna_1.FafDNAManager(projectPath);
        const dna = await dnaManager.load();
        // Show ASCII header with scoreboard title
        if (!isQuiet) {
            const { getScoreMedal } = require('../utils/championship-core');
            const { medal } = getScoreMedal(result.score);
            const birthDNA = dna ? dna.birthCertificate.birthDNA : 0;
            const scoreboardTitle = colors_1.chalk.bold(`Birth: ${birthDNA}% | ${medal} ${result.score}/100`);
            console.log((0, championship_style_1.generateFAFHeader)(scoreboardTitle));
        }
        // Main score display
        console.log(colors_1.chalk.cyan(`Scoring: ${fafPath}`));
        if (dna) {
            (0, faf_dna_1.displayScoreWithBirthDNA)(result.score, dna.birthCertificate.birthDNA, dna.birthCertificate.born, { showGrowth: true, showJourney: true });
        }
        else {
            // Simple display
            const scoreColor = getScoreColor(result.score);
            const scoreEmoji = getScoreEmoji(result.score);
            console.log();
            console.log(scoreColor(colors_1.chalk.bold(`${scoreEmoji} Score: ${result.score}%`)));
            console.log(colors_1.chalk.gray(`Filled: ${result.filled}/${result.total} slots`));
        }
        // Show checksum if requested
        if (options.checksum) {
            console.log();
            console.log(colors_1.chalk.gray(`Checksum: ${result.checksum}`));
            console.log(colors_1.chalk.gray(`Verify with: faf score --verify=${result.checksum}`));
        }
        // Show errors
        const errors = result.diagnostics.filter(d => d.severity === 'error');
        if (errors.length > 0) {
            console.log();
            console.log(colors_1.chalk.red(`❌ ${errors.length} errors found:`));
            errors.forEach(err => {
                console.log(colors_1.chalk.red(`  • ${err.message}`));
                if (err.suggestion) {
                    console.log(colors_1.chalk.yellow(`    → ${err.suggestion}`));
                }
            });
            process.exit(1);
        }
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        console.error(colors_1.chalk.red(`\n❌ Compilation failed: ${message}`));
        if (options.verbose && error instanceof Error) {
            console.error(error.stack);
        }
        process.exit(1);
    }
}
// Utility functions
function getScoreColor(percentage) {
    if (percentage >= 85)
        return colors_1.chalk.green;
    if (percentage >= 70)
        return colors_1.chalk.yellow;
    if (percentage >= 50)
        return colors_1.chalk.blue;
    return colors_1.chalk.red;
}
function getScoreEmoji(percentage) {
    if (percentage >= 90)
        return "🏆";
    if (percentage >= 80)
        return "🎯";
    if (percentage >= 70)
        return "✨";
    if (percentage >= 60)
        return "📈";
    if (percentage >= 50)
        return "🎯";
    if (percentage >= 40)
        return "🌱";
    if (percentage >= 30)
        return "🔧";
    if (percentage >= 20)
        return "⚠️";
    return "🚨";
}
//# sourceMappingURL=score-v3.js.map