"use strict";
/**
 * 🚀 faf init - Initialization Command
 * Generate .faf file from project structure with auto-detection
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initFafFile = initFafFile;
const colors_1 = require("../fix-once/colors");
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const yaml_1 = require("../fix-once/yaml");
const championship_style_1 = require("../utils/championship-style");
const technical_credit_1 = require("../utils/technical-credit");
const file_utils_1 = require("../utils/file-utils");
const faf_generator_championship_1 = require("../generators/faf-generator-championship");
const faf_compiler_1 = require("../compiler/faf-compiler");
const fafignore_parser_1 = require("../utils/fafignore-parser");
const balance_visualizer_1 = require("../utils/balance-visualizer");
const faf_dna_1 = require("../engines/faf-dna");
const fab_formats_processor_1 = require("../engines/fab-formats-processor");
const platform_detector_1 = require("../utils/platform-detector");
const email_opt_in_1 = require("../utils/email-opt-in");
async function initFafFile(projectPath, options = {}) {
    const startTime = Date.now();
    // FAF banner is now shown by cli.ts - removed duplicate
    // (The main cli.ts handles showing the banner for 'init' command)
    try {
        const projectRoot = projectPath || process.cwd();
        const homeDir = require('os').homedir();
        // CRITICAL: Prevent running in home or root directory
        if (!projectPath && (projectRoot === homeDir || projectRoot === '/')) {
            console.log();
            console.log(championship_style_1.FAF_COLORS.fafOrange('⚠️  For speed and safety, we do not work on ROOT directories.'));
            console.log(colors_1.chalk.yellow('Please provide or cd my-project\n'));
            return;
        }
        const outputPath = options.output ? options.output : `${projectRoot}/.faf`;
        // Check if .faf file already exists
        if ((await (0, file_utils_1.fileExists)(outputPath)) && !options.force && !options.new && !options.choose) {
            const username = require('os').userInfo().username;
            console.log();
            console.log(colors_1.chalk.cyan.bold(`👋 Hi ${username}!`));
            console.log();
            console.log(colors_1.chalk.green(`🤖 We found a .faf file at: `) + colors_1.chalk.cyan(outputPath));
            console.log(championship_style_1.FAF_COLORS.fafOrange(`💡 Do you want to use this one? Or run `) + colors_1.chalk.cyan('faf init --new') + championship_style_1.FAF_COLORS.fafOrange(' to create a fresh one?'));
            console.log();
            return; // Don't exit, just return gracefully
        }
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.rocket} Initializing .faf file...`));
        // Check for .fafignore
        const fafIgnorePath = path_1.default.join(projectRoot, ".fafignore");
        if (!(await (0, file_utils_1.fileExists)(fafIgnorePath))) {
            console.log(colors_1.chalk.gray("   Creating .fafignore with default patterns..."));
            await (0, fafignore_parser_1.createDefaultFafIgnore)(projectRoot);
            console.log(colors_1.chalk.green("   ☑️ Created .fafignore (customize to exclude files)"));
        }
        else {
            console.log(colors_1.chalk.gray("   Using existing .fafignore file"));
        }
        // Detect project structure
        const projectType = options.template === "auto"
            ? await (0, file_utils_1.detectProjectType)(projectRoot)
            : options.template || (await (0, file_utils_1.detectProjectType)(projectRoot));
        console.log(colors_1.chalk.gray(`   Detected project type: ${projectType}`));
        // Generate .faf content
        const fafContent = await (0, faf_generator_championship_1.generateFafFromProject)({
            projectType,
            outputPath,
            projectRoot: projectRoot,
        });
        // Write .faf file
        await fs_1.promises.writeFile(outputPath, fafContent, "utf-8");
        const elapsedTime = Date.now() - startTime;
        console.log(colors_1.chalk.green(`☑️ Created ${outputPath}`));
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange('🤖 .faf = Foundational AI-context Format = Project DNA for AI✨ 🧡⚡️'));
        console.log(championship_style_1.FAF_COLORS.fafOrange('🧡 Trust: Context verified'));
        console.log(championship_style_1.FAF_COLORS.fafCyan(`⚡️ Speed: Generated in ${elapsedTime}ms`));
        console.log(championship_style_1.FAF_COLORS.fafGreen('SPEEDY AI you can TRUST!'));
        console.log();
        // Award technical credit for successful initialization
        await (0, technical_credit_1.autoAwardCredit)('init_success', outputPath);
        // REVOLUTIONARY: Score CLAUDE.md ONLY for Birth DNA!
        // This is the TRUE starting point - what AI sees initially
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.magic_wand} Analyzing CLAUDE.md for Birth DNA...`));
        const claudeMdPath = path_1.default.join(projectRoot, 'CLAUDE.md');
        let birthDNA = 0;
        let fromClaudeMD = false;
        if (await (0, file_utils_1.fileExists)(claudeMdPath)) {
            // Score ONLY CLAUDE.md for Birth DNA
            const claudeMdContent = await fs_1.promises.readFile(claudeMdPath, 'utf-8');
            const claudeMdAnalysis = await fab_formats_processor_1.fabFormatsProcessor.processFiles(projectRoot);
            // Calculate Birth DNA from CLAUDE.md context quality
            // Low scores are GOOD - they show the journey!
            if (claudeMdContent.length < 100) {
                birthDNA = 5; // Almost empty CLAUDE.md
            }
            else if (claudeMdContent.includes('FAF')) {
                birthDNA = 22; // Has some FAF context
            }
            else {
                birthDNA = 12; // Generic CLAUDE.md
            }
            fromClaudeMD = true;
            console.log(championship_style_1.FAF_COLORS.fafOrange(`   Birth DNA from CLAUDE.md: ${birthDNA}%`));
            console.log(championship_style_1.FAF_COLORS.fafWhite(`   (Low scores are normal - they show your growth journey!)`));
        }
        else {
            // No CLAUDE.md - use minimal Birth DNA
            birthDNA = 0;
            console.log(championship_style_1.FAF_COLORS.fafOrange(`   No CLAUDE.md found - Birth DNA: ${birthDNA}%`));
        }
        // Initialize FAF DNA with birth certificate
        const dnaManager = new faf_dna_1.FafDNAManager(projectRoot);
        const dna = await dnaManager.birth(birthDNA, fromClaudeMD);
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.dna} FAF DNA created with birth certificate!`));
        console.log(championship_style_1.FAF_COLORS.fafWhite(`   Certificate: ${dna.birthCertificate.certificate}`));
        // Now calculate ACTUAL score from full .faf
        const fafData = (0, yaml_1.parse)(fafContent);
        const compiler = new faf_compiler_1.FafCompiler();
        const scoreResult = await compiler.compile(outputPath);
        const currentScore = fafData.faf_score ? parseInt(fafData.faf_score.replace('%', '')) : Math.round(scoreResult.score || 0);
        // Record first growth if different from Birth DNA
        if (currentScore !== birthDNA) {
            await dnaManager.recordGrowth(currentScore, ['Initial .faf generation from project']);
        }
        // Add faf_dna section to .faf file for faf auto to read
        const updatedFafData = {
            ...fafData,
            faf_dna: {
                birth_dna: birthDNA,
                birth_certificate: dna.birthCertificate.certificate,
                birth_date: dna.birthCertificate.born.toISOString(),
                current_score: currentScore
            }
        };
        await fs_1.promises.writeFile(outputPath, (0, yaml_1.stringify)(updatedFafData), 'utf-8');
        // Show ASCII header with scoreboard
        if (!options.quiet) {
            const { getScoreMedal } = require('../utils/championship-core');
            const { medal } = getScoreMedal(currentScore);
            const scoreboardTitle = colors_1.chalk.bold(`Birth: ${birthDNA}% | ${medal} ${currentScore}/100`);
            console.log();
            console.log((0, championship_style_1.generateFAFHeader)(scoreboardTitle));
        }
        // Display with Birth DNA
        console.log();
        (0, faf_dna_1.displayScoreWithBirthDNA)(currentScore, birthDNA, dna.birthCertificate.born, { showGrowth: true });
        // Show AI|HUMAN Balance
        const balance = balance_visualizer_1.BalanceVisualizer.calculateBalance(fafData);
        console.log(championship_style_1.FAF_COLORS.fafWhite(`${championship_style_1.FAF_ICONS.balance} Balance: `) + balance_visualizer_1.BalanceVisualizer.generateCompactBalance(balance));
        // Detect platform and show VIBE message if applicable
        const platformDetector = new platform_detector_1.PlatformDetector();
        const platformInfo = await platformDetector.detectPlatform(projectRoot);
        if (platformInfo.detected && platformInfo.tier === 'vibe') {
            console.log();
            console.log(championship_style_1.FAF_COLORS.fafOrange('⚡️ FAF VIBE DETECTED! 😽'));
            console.log(championship_style_1.FAF_COLORS.fafCyan(`   Platform: ${platformInfo.platform}`));
            console.log(championship_style_1.FAF_COLORS.fafGreen(`   FREE CLI for all platforms!`));
            console.log(championship_style_1.FAF_COLORS.fafWhite(`   ${championship_style_1.FAF_ICONS.turbo_cat} TURBO-CAT is ready to make your AI happy!`));
        }
        // Championship Next Steps with DNA lifecycle
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange(`${championship_style_1.FAF_ICONS.magic_wand} Championship Recommendations:`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   1. ')}faf auth${championship_style_1.FAF_COLORS.fafCyan(' - Authenticate your FAF DNA')}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   2. ')}faf auto${championship_style_1.FAF_COLORS.fafCyan(' - Grow your context automatically')}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   3. ')}faf score --details${championship_style_1.FAF_COLORS.fafCyan(' - Track improvement opportunities')}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   4. ')}faf trust --detailed${championship_style_1.FAF_COLORS.fafCyan(' - Boost AI happiness')}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('   5. ')}faf log${championship_style_1.FAF_COLORS.fafCyan(' - View your context evolution')}`);
        // Growth-focused messaging
        const growth = currentScore - birthDNA;
        if (growth > 0) {
            console.log();
            console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.rocket} Already improved +${growth}% from Birth DNA!`));
        }
        if (currentScore < 70) {
            console.log(championship_style_1.FAF_COLORS.fafOrange(`   ${championship_style_1.FAF_ICONS.precision} Target 70%+ for championship AI context`));
        }
        else if (currentScore >= 85) {
            console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.party} Championship performance achieved! ${championship_style_1.FAF_ICONS.trophy}`));
        }
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafWhite(`Your FAF journey has begun: ${birthDNA}% → ${currentScore}%`));
        // Prompt for email opt-in (first time users only, respects quiet mode)
        await (0, email_opt_in_1.promptEmailOptIn)({ quiet: options.quiet });
    }
    catch (error) {
        console.log(colors_1.chalk.red("💥 Initialization failed:"));
        console.log(colors_1.chalk.red(error instanceof Error ? error.message : String(error)));
        process.exit(1);
    }
}
//# sourceMappingURL=init.js.map