"use strict";
/**
 * 🏎️ faf auto - The One Command Championship
 * Zero to Championship in one command - no faffing about!
 */
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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.autoCommand = autoCommand;
const colors_1 = require("../fix-once/colors");
const fs = __importStar(require("fs/promises"));
const file_utils_1 = require("../utils/file-utils");
const init_1 = require("./init");
const sync_1 = require("./sync");
const ai_enhance_1 = require("./ai-enhance");
const bi_sync_1 = require("./bi-sync");
const show_1 = require("./show");
const yaml_1 = __importDefault(require("../fix-once/yaml"));
const faf_compiler_1 = require("../compiler/faf-compiler");
async function autoCommand(directory, options = {}) {
    const targetDir = directory || process.cwd();
    const homeDir = require('os').homedir();
    // CRITICAL: Prevent running in home or root directory
    if (!directory && (targetDir === homeDir || targetDir === '/')) {
        console.log(colors_1.chalk.red('\n⚠️  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;
    }
    try {
        // Step 0: Check for platform workflows (funnel to TURBO)
        const { findN8nWorkflows, findMakeScenarios, findOpalMiniApps, findOpenAIAssistants } = await Promise.resolve().then(() => __importStar(require('../utils/file-utils')));
        // Check n8n workflows
        const n8nWorkflows = await findN8nWorkflows(targetDir);
        if (n8nWorkflows.length > 0) {
            console.log(colors_1.chalk.yellow(`\n⚠️  n8n workflow detected: ${colors_1.chalk.white(n8nWorkflows[0])}`));
            console.log(colors_1.chalk.cyan(`\n💡 Fancy an 85% or even a 99%? 🏎️💨`));
            console.log(colors_1.chalk.white(`   faf turbo analyze "${n8nWorkflows[0]}"`));
            console.log(colors_1.chalk.gray(`\n🏆 TURBO: 48% → 85%+ (with bi-sync) <3 seconds!`));
            console.log(colors_1.chalk.gray(`   vs. standard auto: 25% (generic detection)\n`));
            const readline = await Promise.resolve().then(() => __importStar(require('readline')));
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            const answer = await new Promise((resolve) => {
                rl.question(colors_1.chalk.cyan('Continue with standard auto (not recommended)? [y/N]: '), resolve);
            });
            rl.close();
            if (answer.toLowerCase() !== 'y') {
                console.log(colors_1.chalk.green(`\n✨ Run this instead:`));
                console.log(colors_1.chalk.white(`   faf turbo analyze "${n8nWorkflows[0]}"`));
                console.log();
                process.exit(0);
            }
            console.log(colors_1.chalk.gray('\n⚠️  Proceeding with standard auto (n8n intelligence will be missed)...\n'));
        }
        // Check Make.com scenarios
        const makeScenarios = await findMakeScenarios(targetDir);
        if (makeScenarios.length > 0) {
            console.log(colors_1.chalk.yellow(`\n⚠️  Make.com scenario detected: ${colors_1.chalk.white(makeScenarios[0])}`));
            console.log(colors_1.chalk.cyan(`\n💡 Fancy an 85% or even a 99%? 🏎️💨`));
            console.log(colors_1.chalk.white(`   faf turbo analyze "${makeScenarios[0]}"`));
            console.log(colors_1.chalk.gray(`\n🏆 TURBO: 50% → 85%+ (with bi-sync) <3 seconds!`));
            console.log(colors_1.chalk.gray(`   vs. standard auto: 25% (generic detection)\n`));
            const readline = await Promise.resolve().then(() => __importStar(require('readline')));
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            const answer = await new Promise((resolve) => {
                rl.question(colors_1.chalk.cyan('Continue with standard auto (not recommended)? [y/N]: '), resolve);
            });
            rl.close();
            if (answer.toLowerCase() !== 'y') {
                console.log(colors_1.chalk.green(`\n✨ Run this instead:`));
                console.log(colors_1.chalk.white(`   faf turbo analyze "${makeScenarios[0]}"`));
                console.log();
                process.exit(0);
            }
            console.log(colors_1.chalk.gray('\n⚠️  Proceeding with standard auto (Make.com intelligence will be missed)...\n'));
        }
        // Check Google Opal mini-apps
        const opalMiniApps = await findOpalMiniApps(targetDir);
        if (opalMiniApps.length > 0) {
            console.log(colors_1.chalk.yellow(`\n⚠️  Google Opal mini-app detected: ${colors_1.chalk.white(opalMiniApps[0])}`));
            console.log(colors_1.chalk.cyan(`\n💡 Fancy an 85% or even a 99%? 🏎️💨`));
            console.log(colors_1.chalk.white(`   faf turbo analyze "${opalMiniApps[0]}"`));
            console.log(colors_1.chalk.gray(`\n🏆 TURBO: 45% → 85%+ (with bi-sync) <3 seconds!`));
            console.log(colors_1.chalk.gray(`   vs. standard auto: 25% (generic detection)\n`));
            const readline = await Promise.resolve().then(() => __importStar(require('readline')));
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            const answer = await new Promise((resolve) => {
                rl.question(colors_1.chalk.cyan('Continue with standard auto (not recommended)? [y/N]: '), resolve);
            });
            rl.close();
            if (answer.toLowerCase() !== 'y') {
                console.log(colors_1.chalk.green(`\n✨ Run this instead:`));
                console.log(colors_1.chalk.white(`   faf turbo analyze "${opalMiniApps[0]}"`));
                console.log();
                process.exit(0);
            }
            console.log(colors_1.chalk.gray('\n⚠️  Proceeding with standard auto (Google Opal intelligence will be missed)...\n'));
        }
        // Check OpenAI Assistants
        const openaiAssistants = await findOpenAIAssistants(targetDir);
        if (openaiAssistants.length > 0) {
            console.log(colors_1.chalk.yellow(`\n⚠️  OpenAI Assistant detected: ${colors_1.chalk.white(openaiAssistants[0])}`));
            console.log(colors_1.chalk.cyan(`\n💡 Fancy an 85% or even a 99%? 🏎️💨`));
            console.log(colors_1.chalk.white(`   faf turbo analyze "${openaiAssistants[0]}"`));
            console.log(colors_1.chalk.gray(`\n🏆 TURBO: 55% → 85%+ (with bi-sync) <3 seconds!`));
            console.log(colors_1.chalk.gray(`   vs. standard auto: 25% (generic detection)\n`));
            const readline = await Promise.resolve().then(() => __importStar(require('readline')));
            const rl = readline.createInterface({
                input: process.stdin,
                output: process.stdout
            });
            const answer = await new Promise((resolve) => {
                rl.question(colors_1.chalk.cyan('Continue with standard auto (not recommended)? [y/N]: '), resolve);
            });
            rl.close();
            if (answer.toLowerCase() !== 'y') {
                console.log(colors_1.chalk.green(`\n✨ Run this instead:`));
                console.log(colors_1.chalk.white(`   faf turbo analyze "${openaiAssistants[0]}"`));
                console.log();
                process.exit(0);
            }
            console.log(colors_1.chalk.gray('\n⚠️  Proceeding with standard auto (OpenAI intelligence will be missed)...\n'));
        }
        // Step 1: Check if .faf exists
        let fafPath = await (0, file_utils_1.findFafFile)(targetDir);
        // Get scores for header display
        let birthScore = 0;
        let currentScore = 0;
        let addedScore = 0;
        if (fafPath) {
            try {
                const fafData = await fs.readFile(fafPath, 'utf-8');
                const parsed = yaml_1.default.parse(fafData);
                if (parsed.faf_dna?.birth_dna !== undefined) {
                    birthScore = Math.round(parsed.faf_dna.birth_dna);
                }
                const compiler = new faf_compiler_1.FafCompiler();
                const scoreResult = await compiler.compile(fafPath);
                currentScore = Math.round(scoreResult.score || 0);
                addedScore = currentScore - birthScore;
            }
            catch (e) {
                // Ignore score errors, will show 0%
            }
        }
        console.log(colors_1.chalk.bold.blue("\n🏎️⚡️ FAF AUTO - CHAMPIONSHIP MODE ENGAGED!"));
        if (fafPath) {
            console.log(colors_1.chalk.white(`Birth: ${birthScore}% | ADDED: ${addedScore}% | .FAF score: ${currentScore}%`));
        }
        console.log(colors_1.chalk.gray("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"));
        if (!fafPath) {
            console.log(colors_1.chalk.yellow("📋 No .faf found - Creating championship context..."));
            // Initialize with auto-detection
            await (0, init_1.initFafFile)(targetDir, {
                force: options.force,
                template: 'auto'
            });
            fafPath = await (0, file_utils_1.findFafFile)(targetDir);
            console.log(colors_1.chalk.green("✅ .faf created!"));
        }
        else {
            console.log(colors_1.chalk.green("✅ .faf found!"));
        }
        // Step 2: Sync dependencies and context
        console.log(colors_1.chalk.yellow("\n🔄 Syncing context with latest changes..."));
        await (0, sync_1.syncFafFile)(fafPath || undefined, { auto: true });
        console.log(colors_1.chalk.green("✅ Context synchronized!"));
        // Step 3: Create/Update CLAUDE.md via bi-sync
        console.log(colors_1.chalk.yellow("\n🔗 Creating CLAUDE.md bi-directional sync..."));
        await (0, bi_sync_1.biSyncCommand)({
            auto: true,
            force: options.force
        });
        console.log(colors_1.chalk.green("✅ CLAUDE.md synced!"));
        // Step 4: AI Enhancement (if requested and API key available)
        if (options.ai) {
            const hasApiKey = process.env.OPENAI_API_KEY || process.env.ANTHROPIC_API_KEY;
            if (hasApiKey) {
                console.log(colors_1.chalk.yellow("\n🤖 Enhancing with AI intelligence..."));
                try {
                    await (0, ai_enhance_1.enhanceFafWithAI)(fafPath || undefined);
                    console.log(colors_1.chalk.green("✅ AI enhancement complete!"));
                }
                catch (error) {
                    console.log(colors_1.chalk.yellow("⚠️  AI enhancement skipped (API issue)"));
                }
            }
            else {
                console.log(colors_1.chalk.gray("\n💡 Tip: Set OPENAI_API_KEY for AI enhancements"));
            }
        }
        // Step 5: Show the scorecard
        console.log(colors_1.chalk.yellow("\n📊 Generating Championship Scorecard...\n"));
        console.log(colors_1.chalk.gray("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
        if (options.show !== false) {
            await (0, show_1.showFafScoreCard)(targetDir, { raw: false });
        }
        // Success message
        console.log(colors_1.chalk.gray("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"));
        console.log(colors_1.chalk.bold.green("\n🏁 FAF AUTO COMPLETE - CHAMPIONSHIP READY!"));
        console.log(colors_1.chalk.gray("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n"));
        // Quick tips
        console.log(colors_1.chalk.blue("Next steps:"));
        console.log(colors_1.chalk.gray("  • Check your score: ") + colors_1.chalk.white("faf show"));
        console.log(colors_1.chalk.gray("  • See details: ") + colors_1.chalk.white("faf score --details"));
        console.log(colors_1.chalk.gray("  • Keep synced: ") + colors_1.chalk.white("faf bi-sync --watch"));
        console.log(colors_1.chalk.gray("  • Get AI help: ") + colors_1.chalk.white("faf ai-enhance"));
        console.log(colors_1.chalk.gray("\n🏎️ Stop faffing about - start building!\n"));
    }
    catch (error) {
        console.log(colors_1.chalk.red("\n💥 FAF AUTO hit the wall:"));
        console.log(colors_1.chalk.red(error instanceof Error ? error.message : String(error)));
        console.log(colors_1.chalk.yellow("\n💡 Try: faf auto --force to override"));
        process.exit(1);
    }
}
/**
 * The Championship Promise:
 * One command to rule them all
 * Zero configuration required
 * Maximum context generated
 *
 * faf auto =
 *   faf init +
 *   faf sync +
 *   faf bi-sync +
 *   faf enhance +
 *   faf show
 *
 * From 0% to Championship in 30 seconds!
 */ 
//# sourceMappingURL=auto.js.map