#!/usr/bin/env node
"use strict";
/**
 * 🚀 .faf CLI - Command Line Interface
 * Universal AI Context Format Tooling
 */
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.program = void 0;
const commander_1 = require("./fix-once/commander");
Object.defineProperty(exports, "program", { enumerable: true, get: function () { return commander_1.program; } });
const colors_1 = require("./fix-once/colors");
const inquirer_1 = __importDefault(require("inquirer"));
const validate_1 = require("./commands/validate");
const init_1 = require("./commands/init");
const score_1 = require("./commands/score");
const show_1 = require("./commands/show");
const edit_helper_1 = require("./commands/edit-helper");
const auto_1 = require("./commands/auto");
const formats_1 = require("./commands/formats");
const version_1 = require("./commands/version");
const sync_1 = require("./commands/sync");
const audit_1 = require("./commands/audit");
const lint_1 = require("./commands/lint");
const enhance_real_1 = require("./commands/enhance-real");
const ai_analyze_1 = require("./commands/ai-analyze");
const trust_1 = require("./commands/trust");
const status_1 = require("./commands/status");
const verify_1 = require("./commands/verify");
const stacks_1 = require("./commands/stacks");
const bi_sync_1 = require("./commands/bi-sync");
const credit_1 = require("./commands/credit");
const todo_1 = require("./commands/todo");
const check_1 = require("./commands/check");
const clear_1 = require("./commands/clear");
const fam_1 = require("./commands/fam");
const edit_1 = require("./commands/edit");
const search_1 = require("./commands/search");
const index_1 = require("./commands/index");
const share_1 = require("./commands/share");
const chat_1 = require("./commands/chat");
const convert_1 = require("./commands/convert");
const notifications_1 = require("./commands/notifications");
const skills_1 = require("./commands/skills");
const color_utils_1 = require("./utils/color-utils");
const championship_style_1 = require("./utils/championship-style");
const analytics_1 = require("./telemetry/analytics");
const update_checker_1 = require("./utils/update-checker");
const announcements_1 = require("./utils/announcements");
const version = require('../package.json').version;
/**
 * Analytics tracking wrapper for commands
 */
function withAnalyticsTracking(commandName, fn) {
    return (async (...args) => {
        const start = Date.now();
        const commandArgs = process.argv.slice(2);
        try {
            const result = await fn(...args);
            const duration = Date.now() - start;
            await (0, analytics_1.trackCommand)(commandName, commandArgs, duration, true);
            return result;
        }
        catch (error) {
            const duration = Date.now() - start;
            await (0, analytics_1.trackCommand)(commandName, commandArgs, duration, false);
            await (0, analytics_1.trackError)(error, commandName, commandArgs);
            throw error;
        }
    });
}
function showHeaderIfAppropriate(commandName) {
    // Check for quiet mode
    const opts = commander_1.program.opts();
    if (opts.quiet) {
        return; // Skip header in quiet mode
    }
    const showHeaderCommands = ['help', 'clear', 'enhance', 'analyze', 'chat', 'formats', 'version'];
    if (!commandName || showHeaderCommands.includes(commandName)) {
        console.log((0, championship_style_1.generateFAFHeader)());
    }
}
commander_1.program
    .name('faf')
    .description('.faf = Project DNA ✨ for ANY AI | Foundational AI-context Format | SPEEDY AI you can TRUST! 🧡⚡️')
    .version(version)
    .option('--no-color', 'Disable colored output for accessibility')
    .option('--color-scheme <scheme>', 'Color scheme for colorblind accessibility: normal|deuteranopia|protanopia|tritanopia', 'normal')
    .option('-q, --quiet', 'Quiet mode - minimal output, no ASCII banners (AI/Codex mode)')
    .option('--auto', 'Auto mode - menu-driven interface for learning and exploration')
    .option('--manual', 'Manual mode - direct command-line interface for power users')
    .addHelpText('after', `
${championship_style_1.FAF_COLORS.fafOrange('💡 In Terminal:')} Use ${colors_1.chalk.cyan('faf')} prefix - like ${colors_1.chalk.cyan('faf init')}, ${colors_1.chalk.cyan('faf faq')}

${championship_style_1.FAF_COLORS.fafCyan('🚀 Quick Start - Get Perfect AI Context:')}

  ${colors_1.chalk.green(colors_1.chalk.bold('FASTEST:'))} ${colors_1.chalk.cyan('faf auto')}     ${colors_1.chalk.gray('# ONE COMMAND - Zero to Championship!')}

  ${colors_1.chalk.gray('Or step by step:')}
  ${championship_style_1.FAF_COLORS.fafOrange('1.')} ${colors_1.chalk.cyan('faf init')}     ${colors_1.chalk.gray('# Get your .faf file')}
  ${championship_style_1.FAF_COLORS.fafOrange('2.')} ${colors_1.chalk.cyan('faf score')}    ${colors_1.chalk.gray('# Get a high score (70%+)')}
  ${championship_style_1.FAF_COLORS.fafOrange('3.')} ${colors_1.chalk.cyan('faf trust')}    ${colors_1.chalk.gray('# Build AI trust & confidence')}
  ${championship_style_1.FAF_COLORS.fafOrange('4.')} ${colors_1.chalk.cyan('faf bi-sync')}  ${colors_1.chalk.gray('# Set & forget - persistent context-mirroring')}

${championship_style_1.FAF_COLORS.fafCyan('🎯 What is .faf?')}
  .faf = Foundational AI-context Format (Project DNA for AI✨)
  Just like JPEG makes images universal, .faf makes projects AI-readable.
  bi-sync = persistent context-mirroring through thick and thin
  Get high score, build trust, share freely!
  
${championship_style_1.FAF_COLORS.fafOrange('📚 Need more?')} ${colors_1.chalk.cyan('faf index')} ${colors_1.chalk.gray('# Complete A-Z reference guide')}
${championship_style_1.FAF_COLORS.fafOrange('🎯 VS Coders?')} ${colors_1.chalk.cyan('faf faq')} ${colors_1.chalk.gray('# VS Code extension & Command Palette info!')}
`);
// 🏎️ faf auto - The One Command Championship (PRIORITY #1)
commander_1.program
    .command('auto [directory]')
    .description('🏎️ ONE COMMAND TO RULE THEM ALL - Zero to Championship instantly!')
    .option('-f, --force', 'Force overwrite existing files')
    .option('-a, --ai', 'Include AI enhancement (requires API key)')
    .option('--no-show', 'Skip showing scorecard at end')
    .addHelpText('after', `
Examples:
  $ faf auto                     # Transform current directory to Championship
  $ faf auto ./my-project        # Transform specific project
  $ faf auto --ai                # Include AI enhancements
  $ faf auto --force             # Overwrite everything, fresh start

🏎️ What FAF AUTO Does (in 30 seconds):
  1. Creates perfect .faf file
  2. Syncs all dependencies
  3. Generates CLAUDE.md
  4. Sets up bi-directional sync
  5. Shows your Championship scorecard

From 0% to 99% in one command. No faffing about!`)
    .action(withAnalyticsTracking('auto', auto_1.autoCommand));
// Add all the command definitions back
commander_1.program
    .command('init [directory]')
    .description('Create .faf file from your project (detects React, Python, Node.js, etc.)')
    .option('-f, --force', 'Overwrite existing .faf file')
    .option('-n, --new', 'Create a fresh .faf file (friendlier than --force)')
    .option('-c, --choose', 'Interactive choice when .faf exists')
    .option('-t, --template <type>', 'Use specific template (svelte, react, vue, node)', 'auto')
    .option('-o, --output <file>', 'Output file path')
    .addHelpText('after', `
Examples:
  $ faf init                     # Detect project type automatically
  $ faf init --new               # Create a fresh .faf file
  $ faf init --choose            # Interactive choice when .faf exists
  $ faf init my-app              # Create .faf for different directory
  $ faf init -t react            # Force React template`)
    .action(withAnalyticsTracking('init', (directory, options) => (0, init_1.initFafFile)(directory, options)));
// 🇬🇧 faf innit - British slang fun version of init
commander_1.program
    .command('innit [directory]')
    .description('🇬🇧 British version of init - same championship, more bruv!')
    .option('-f, --force', 'Overwrite existing .faf file')
    .option('-n, --new', 'Create a fresh .faf file')
    .option('-c, --choose', 'Interactive choice when .faf exists')
    .option('-t, --template <type>', 'Use specific template', 'auto')
    .option('-o, --output <file>', 'Output file path')
    .addHelpText('after', `
Examples:
  $ faf innit                    # Init bruv!
  $ faf innit --new              # Fresh start innit
  $ faf innit my-app             # Create .faf for different directory

🇬🇧 Same as 'faf init', just more British! Proper cheeky!`)
    .action(withAnalyticsTracking('innit', (directory, options) => {
    console.log(championship_style_1.FAF_COLORS.fafOrange('🇬🇧 doing it now Bruv'));
    console.log('');
    return (0, init_1.initFafFile)(directory, options);
}));
// 🧬 faf dna - Show your journey at a glance
commander_1.program
    .command('dna')
    .description('🧬 Show your FAF DNA journey (22% → 85% → 99% ← 92%)')
    .addHelpText('after', `
Examples:
  $ faf dna                      # See your journey at a glance

🧬 Shows instantly:
  • Your complete journey line
  • Quick stats and growth
  • Achievements unlocked
  • Links to detailed info`)
    .action(withAnalyticsTracking('dna', () => {
    const dnaCommand = require('./commands/faf-dna');
    return dnaCommand.default?.();
}));
// 🔐 faf auth - Authenticate your FAF DNA
commander_1.program
    .command('auth')
    .description('🔐 Authenticate your FAF project with a birth certificate')
    .option('--verify <certificate>', 'Verify an existing certificate')
    .option('--show', 'Show current authentication status')
    .addHelpText('after', `
Examples:
  $ faf auth                     # Authenticate your project
  $ faf auth --show              # Show authentication status
  $ faf auth --verify FAF-2025-PROJECT-XXXX  # Verify certificate

🔐 Birth Certificate:
  • Proves origin of your context
  • Tracks evolution from birth weight
  • Enables Context-Mirroring recovery`)
    .action(withAnalyticsTracking('auth', () => {
    const authCommand = require('./commands/faf-auth');
    return authCommand.default?.();
}));
// 📜 faf log - View context evolution history
commander_1.program
    .command('log')
    .description('📜 View complete evolution history of your FAF context')
    .option('--milestones', 'Show milestones only')
    .option('--analytics', 'Show growth analytics')
    .option('--json', 'Output as JSON')
    .addHelpText('after', `
Examples:
  $ faf log                      # Full evolution history
  $ faf log --milestones         # Key milestones only
  $ faf log --analytics          # Growth analytics
  $ faf log --json               # Export as JSON

📜 Shows Your Journey:
  • Birth weight (from CLAUDE.md)
  • Every version and growth
  • Milestones achieved
  • Current position vs peak`)
    .action(withAnalyticsTracking('log', () => {
    const logCommand = require('./commands/faf-log');
    return logCommand.default?.();
}));
// 💾 faf update - Save your current version
commander_1.program
    .command('update')
    .description('💾 Save your current FAF version (checkpoint your progress)')
    .addHelpText('after', `
Examples:
  $ faf update                   # Save current version

💾 Simple checkpoint:
  • Marks current state as good
  • Creates reference point
  • Track future changes from here`)
    .action(withAnalyticsTracking('update', () => {
    const updateCommand = require('./commands/faf-update');
    return updateCommand.default?.();
}));
// 🚨 faf recover - Disaster Recovery
commander_1.program
    .command('recover')
    .description('🚨 Disaster recovery for corrupted or missing FAF files')
    .option('--auto', 'Attempt automatic recovery')
    .option('--backup', 'List available backups')
    .option('--check', 'Check health without recovery')
    .option('--force', 'Force recovery even if risky')
    .addHelpText('after', `
Examples:
  $ faf recover                  # Interactive recovery
  $ faf recover --auto           # Try automatic fix
  $ faf recover --backup         # List backups
  $ faf recover --check          # Health check only

🚨 Emergency Commands:
  • faf recover --auto: Try automatic recovery
  • git checkout HEAD -- .faf: Restore from git
  • faf init --force: Start fresh (loses history)`)
    .action(withAnalyticsTracking('recover', (options) => {
    const { spawn } = require('child_process');
    const recoverPath = require('path').join(__dirname, 'commands', 'faf-recover.ts');
    const args = ['ts-node', recoverPath];
    if (options.auto)
        args.push('--auto');
    if (options.backup)
        args.push('--backup');
    if (options.check)
        args.push('--check');
    if (options.force)
        args.push('--force');
    const child = spawn('npx', args, { stdio: 'inherit' });
    child.on('exit', (code) => {
        process.exit(code || 0);
    });
}));
// 😽 faf formats - TURBO-CAT Format Discovery
commander_1.program
    .command('formats [directory]')
    .description('😽 TURBO-CAT™ discovers all formats in your project (154 validated types!)')
    .option('-e, --export', 'Export as JSON')
    .option('-c, --category', 'Show by category')
    .addHelpText('after', `
Examples:
  $ faf formats                  # List all discovered formats
  $ faf formats --category       # Show by category
  $ faf formats --export         # Export as JSON`)
    .action(withAnalyticsTracking('formats', (directory, options) => (0, formats_1.formatsCommand)(directory, options)));
// 🏆 faf version - Show version with MK2 status
commander_1.program
    .command('version')
    .description('🏆 Show FAF version with MK2 Engine and TURBO-CAT status')
    .action(withAnalyticsTracking('version', () => (0, version_1.versionCommand)()));
// 🧡 faf trust - Consolidated Trust Dashboard (The Emotional Core)
commander_1.program
    .command('trust')
    .description('🧡 Unified trust dashboard - confidence, garage, panic, quality modes')
    .option('-d, --detailed', 'Show detailed trust metrics')
    .option('--confidence', 'Show AI confidence analysis')
    .option('--garage', 'Safe experimentation mode with backup')
    .option('--panic', 'Emergency context repair mode')
    .option('--quality', 'Quality checks and validation mode')
    .addHelpText('after', `
Examples:
  $ faf trust                        # Main trust dashboard
  $ faf trust --detailed             # Detailed metrics breakdown
  $ faf trust --confidence           # AI confidence analysis
  $ faf trust --garage               # Safe experiment mode
  $ faf trust --panic                # Emergency repair
  $ faf trust --quality              # Quality validation check
  
Trust Modes:
  • Confidence: AI confidence levels and boosting tips
  • Garage: Safe experimentation with automatic backup  
  • Panic: Emergency repair and restoration
  • Quality: Championship quality checks and validation`)
    .action(withAnalyticsTracking('trust', (options) => (0, trust_1.trustCommand)(options)));
// ⚡️ faf vibe - No-Code/Low-Code Builder Edition
commander_1.program
    .command('vibe')
    .description('⚡️ FAF VIBE - Detect your development platform')
    .option('-p, --preview', 'Preview TURBO-CAT discovery')
    .addHelpText('after', `
Examples:
  $ faf vibe                         # Check platform type
  $ faf vibe --preview               # Include TURBO-CAT preview

⚡️ FAF VIBE Features:
  • Auto-detects no-code platforms (Replit, Lovable, Wix, etc.)
  • FREE CLI tool for all platforms
  • TURBO-CAT format discovery
  • Lightning not rainbows!`)
    .action(withAnalyticsTracking('vibe', (options) => {
    const { vibeCommand } = require('./commands/vibe');
    return vibeCommand(options);
}));
// 🚀 faf status - Quick context health check (git status equivalent)
commander_1.program
    .command('status')
    .description('Show quick .faf context health status (<200ms)')
    .addHelpText('after', `
Examples:
  $ faf status                       # Quick health check
  
Shows:
  • Context health score (0-100%)
  • Files tracked and last sync time
  • AI readiness status
  • Performance metrics
  • Bi-sync (claude.md) status`)
    .action(withAnalyticsTracking('status', () => (0, status_1.statusCommand)()));
// 💎 faf credit - Technical Credit Dashboard (Revolutionary Psychology)
commander_1.program
    .command('credit')
    .description('💎 Technical Credit Dashboard - See your accumulated development credits')
    .option('-d, --detailed', 'Show detailed credit breakdown by category')
    .option('-h, --history', 'Show credit earning history')
    .option('-c, --clear', 'Clear credit history (confirmation required)')
    .addHelpText('after', `
Examples:
  $ faf credit                       # Show credit dashboard
  $ faf credit --detailed            # Detailed breakdown by category
  $ faf credit --history             # See credit earning timeline
  
💎 Technical Credit System:
  • Earn credit for every improvement (vs. technical debt)
  • Transform developer psychology from anxiety to confidence
  • Track AI happiness improvements and context quality
  • Build trust through measurable technical achievements
  • Championship levels: Beginner → Professional → Championship
  
Expected Impact:
  😰 "I hope this works" → 😎 "I trust my context"`)
    .action((options) => (0, credit_1.creditCommand)(options));
// 📝 faf todo - Claude-Inspired Todo System (The Gamifier)
commander_1.program
    .command('todo')
    .description('📝 Claude-inspired todo system - gamify your context improvements')
    .option('-s, --show', 'Show current todo list')
    .option('-c, --complete <task>', 'Mark task as completed (by number or keyword)')
    .option('-r, --reset', 'Reset current todo list')
    .addHelpText('after', `
Examples:
  $ faf todo                            # Generate new improvement plan
  $ faf todo --show                     # View current todo list
  $ faf todo --complete 1               # Complete task #1
  $ faf todo --complete readme          # Complete README task
  $ faf todo --reset                    # Start fresh
  
Philosophy:
  • Transform low scores into exciting improvement games
  • Claude-inspired task prioritization and celebrations
  • Gamified progress tracking with championship rewards
  • Turn "I need better context" → "I'm completing achievements!"
  
Expected Impact:
  📉 47% score → 📈 85% score through guided achievements`)
    .action((options) => (0, todo_1.todoCommand)(options));
// 🏆 faf fam - FAF Family Integration Marketplace
commander_1.program
    .command('fam [subcommand] [arg]')
    .description('🏆 FAF Family - Championship integration marketplace')
    .option('-d, --detected', 'Show only detected integrations')
    .option('-a, --available', 'Show only available integrations')
    .addHelpText('after', `
Examples:
  $ faf fam                         # Show all integrations + status
  $ faf fam show react              # Details about React integration
  $ faf fam install n8n             # Install integration (TURBO required)

🏆 FAF Family:
  • Discover 6 championship integrations (React, Next.js, Svelte, TypeScript, Vite, n8n)
  • See what's detected in YOUR project
  • Get MCP server recommendations
  • 74.8M+ developer ecosystem reach

Integrations:
  • Auto-detect modern stacks in your project
  • Smart .faf context generation
  • MCP server recommendations per stack
  • Quality-gated: 85% minimum (Bronze tier)`)
    .action(withAnalyticsTracking('fam', (subcommand, arg, options) => (0, fam_1.famCommand)(subcommand, arg, options)));
// 📚 faf index - Universal A-Z Reference (The Everything Catalog)
commander_1.program
    .command('index [term]')
    .description('📚 Universal A-Z reference - commands, concepts, features, everything!')
    .option('--category <category>', 'Filter by category (core, ai, trust, utilities, etc.)')
    .option('--search <query>', 'Search within index entries')
    .option('--examples', 'Show usage examples for commands')
    .addHelpText('after', `
Examples:
  $ faf index                           # Full A-Z catalog
  $ faf index trust                     # Everything about trust
  $ faf index --category ai             # All AI-related entries
  $ faf index --search "context"        # Search for "context" 
  $ faf index --examples                # Show usage examples
  
The Everything Catalog:
  • ⚡️ Commands: All available commands with usage
  • 💡 Concepts: Core FAF concepts (bi-sync, technical-credit, etc.)
  • 🧡 Features: Specialized features (garage, panic, quality modes)
  • 📂 Categories: core, ai, trust, utilities, improvement, psychology
  
Perfect for:
  • New users: "What can FAF do?" → faf index
  • Power users: "What were trust options?" → faf index trust
  • Discovery: "Show me AI features" → faf index --category ai`)
    .action((term, options) => (0, index_1.indexCommand)(term, options));
// 🚀 faf share - Universal .faf Distribution System  
commander_1.program
    .command('share [file]')
    .description('🚀 Secure .faf sharing with auto-sanitization')
    .option('-p, --private', 'Keep sensitive info (default: sanitize)')
    .option('-f, --format <format>', 'Output format: yaml|json|url', 'yaml')
    .option('-e, --expires <duration>', 'Expiration: 24h|7d|30d', '7d')
    .option('--password <password>', 'Password protect shared .faf')
    .option('-d, --description <text>', 'Share description')
    .option('-a, --anonymous', 'Remove author information')
    .addHelpText('after', `
Examples:
  $ faf share                        # Share with auto-sanitization
  $ faf share --private              # Share with sensitive info intact
  $ faf share --format json          # Share as JSON format
  $ faf share --expires 24h          # Expire in 24 hours
  $ faf share --anonymous            # Remove author info
  $ faf share --password secret123   # Password protect
  
Security Features:
  • 🔒 Auto-sanitization removes sensitive data by default
  • 🎭 Anonymous sharing option removes author info
  • ⏰ Configurable expiration (24h, 7d, 30d)
  • 🔐 Optional password protection
  • 📝 Multiple formats: YAML, JSON, shareable URLs
  
Perfect for:
  • Team handoffs: Clean context sharing
  • Community help: Sanitized project sharing
  • Documentation: Shareable project examples`)
    .action((file, options) => (0, share_1.shareCommand)(file, options));
// 🏆 GOLDEN RULE: faf convert - YAML to MD/TXT
commander_1.program
    .command('convert [file]')
    .alias('to-md')
    .description('🔄 Convert .faf YAML to Markdown or Text (Golden Rule: We SPEAK YAML)')
    .option('-f, --format <type>', 'Output format (md|txt)', 'md')
    .option('-o, --output <file>', 'Output file path')
    .option('-s, --save', 'Save to file (.faf.md or .faf.txt)')
    .addHelpText('after', `
Examples:
  $ faf convert              # Convert .faf to Markdown (console output)
  $ faf convert --save       # Save as .faf.md
  $ faf to-md                # Quick alias for Markdown
  $ faf convert -f txt       # Convert to plain text
  $ faf convert -f txt -s    # Save as .faf.txt

🏆 GOLDEN RULE: .faf = YAML ONLY
  • One source of truth: Pure YAML
  • Convert when needed: MD for docs, TXT for sharing
  • No parse errors ever again!`)
    .action(withAnalyticsTracking('convert', async (file, options) => {
    await (0, convert_1.convertCommand)(file, options);
}));
commander_1.program
    .command('to-txt [file]')
    .description('📝 Quick convert .faf YAML to plain text')
    .action(withAnalyticsTracking('to-txt', async (file) => {
    await (0, convert_1.toText)(file);
}));
// 👋 faf welcome - First-time user guide
commander_1.program
    .command('welcome')
    .description('👋 Welcome guide for new users')
    .action(withAnalyticsTracking('welcome', async () => {
    const { welcomeCommand } = await Promise.resolve().then(() => __importStar(require('./commands/welcome')));
    return welcomeCommand();
}));
// 🏥 faf doctor - Diagnose issues
commander_1.program
    .command('doctor')
    .description('🏥 Diagnose and fix common FAF issues')
    .addHelpText('after', `
Examples:
  $ faf doctor                       # Run health check

🏥 Health Checks:
  • .faf file validity
  • Score assessment
  • Project detection
  • Configuration status
  • Provides fixes for any issues found`)
    .action(withAnalyticsTracking('doctor', async () => {
    const { doctorCommand } = await Promise.resolve().then(() => __importStar(require('./commands/doctor')));
    return doctorCommand();
}));
// ⚡ faf quick - Lightning-fast one-liner .faf creation
commander_1.program
    .command('quick [input]')
    .description('⚡ Quick .faf creation - one-liner format for instant context')
    .option('--force', 'Overwrite existing .faf file')
    .addHelpText('after', `
Examples:
  $ faf quick "my-app, e-commerce platform, typescript, react, vercel"
  $ faf quick "api, REST API for mobile, python, fastapi, aws"
  $ faf quick "cli-tool, dev productivity, go"

⚡ Lightning Format:
  • Comma-separated: name, description, language, framework, hosting
  • Minimum: just name and description
  • Auto-detects the rest from your project
  • 0 to .faf in under 100ms!`)
    .action(withAnalyticsTracking('quick', async (input, options) => {
    const { quickCommand } = await Promise.resolve().then(() => __importStar(require('./commands/quick')));
    return quickCommand(input, options);
}));
// 🗣️ faf chat - Natural Language .faf Generation
commander_1.program
    .command('chat')
    .description('🗣️ Natural language .faf generation - conversation-driven context building')
    .addHelpText('after', `
Examples:
  $ faf chat                         # Start conversational .faf creation

🗣️ Simple Natural Language Interface:
  • Answer simple questions about your project
  • Choose from numbered options (KISS method)
  • Get perfect .faf file without technical flags
  • Same championship output, accessible input

Perfect for:
  • Non-technical team members
  • Quick project setup
  • Learning FAF concepts through conversation`)
    .action(withAnalyticsTracking('chat', () => (0, chat_1.chatCommand)()));
// 🤖 faf verify - AI Verification System (The Trust Builder)
commander_1.program
    .command('verify')
    .description('🤖 Test .faf context with Claude, ChatGPT & Gemini - prove AI understanding')
    .option('-d, --detailed', 'Show detailed verification results')
    .option('-m, --models <models>', 'Specify models to test (comma-separated)', 'claude,chatgpt,gemini')
    .option('-t, --timeout <ms>', 'Verification timeout in milliseconds', '30000')
    .addHelpText('after', `
Examples:
  $ faf verify                       # Test with all AI models
  $ faf verify --detailed            # Show detailed results & suggestions
  $ faf verify -m claude,chatgpt     # Test with specific models only
  
AI Verification Tests:
  • Claude: Context understanding & confidence
  • ChatGPT: Project comprehension & clarity  
  • Gemini: Technical stack recognition
  • Trust Score: Updated based on AI feedback
  
Expected Transformation:
  🔴 Needs improvement → ☑️ Perfect context`)
    .action((options) => {
    const models = options.models ? options.models.split(',').map((m) => m.trim()) : undefined;
    (0, verify_1.verifyCommand)({
        models,
        timeout: parseInt(options.timeout),
        detailed: options.detailed
    });
});
// 📊 faf stacks - STACKTISTICS: Stack Discovery & Collection
commander_1.program
    .command('stacks')
    .description('📊 Discover and collect technology stack signatures')
    .option('-s, --scan', 'Scan current project for stack signature')
    .option('-e, --export-gallery', 'Export stacks for Gallery-Svelte')
    .addHelpText('after', `
📊 STACKTISTICS Examples:
  $ faf stacks                       # List your discovered stacks
  $ faf stacks --scan                # Discover current project stack
  $ faf stacks --export-gallery      # Export for Gallery-Svelte

Stack Discovery:
  • Extends fab-formats intelligence - zero performance impact
  • Simple YAML lookup of known stack patterns  
  • Builds collection of your technology experiences`)
    .action(async (options) => {
    if (options.scan) {
        await (0, stacks_1.scanCurrentProject)();
    }
    else if (options['export-gallery']) {
        await (0, stacks_1.exportForGallery)();
    }
    else {
        await (0, stacks_1.listStacks)();
    }
});
// 🔍 faf check - Comprehensive validation & audit (merged validate + audit)
commander_1.program
    .command('check')
    .description('🔍 Comprehensive .faf validation and freshness check')
    .option('--format', 'Check format/validity only (old validate)')
    .option('--fresh', 'Check freshness/completeness only (old audit)')
    .option('--fix', 'Auto-fix issues where possible')
    .option('-d, --detailed', 'Show detailed check results')
    .addHelpText('after', `
Examples:
  $ faf check                    # Full check (format + freshness)
  $ faf check --format           # Format validation only
  $ faf check --fresh            # Freshness audit only
  $ faf check --fix              # Auto-fix issues
  $ faf check --detailed         # Detailed diagnostics
  
Combines old validate + audit:
  • Format validation (schema, YAML syntax, required fields)
  • Freshness audit (up-to-date, completeness, staleness)
  • Auto-fix capabilities for common issues`)
    .action((options) => (0, check_1.checkCommand)(options));
// ✅ faf validate - Check if .faf file is valid
commander_1.program
    .command('validate [file]')
    .description('Validate .faf file structure and content')
    .option('-v, --verbose', 'Show detailed validation output')
    .option('-s, --schema <path>', 'Custom schema file to validate against')
    .addHelpText('after', `
Examples:
  $ faf validate                 # Validate current .faf file
  $ faf validate --verbose       # Show detailed validation report`)
    .action(withAnalyticsTracking('validate', validate_1.validateFafFile));
// 🔍 faf audit - Check freshness and quality
commander_1.program
    .command('audit [file]')
    .description('Check .faf file freshness and identify improvement areas')
    .option('-w, --warn-days <days>', 'Days before warning about staleness', '7')
    .option('-e, --error-days <days>', 'Days before marking as stale', '30')
    .addHelpText('after', `
Examples:
  $ faf audit                    # Check freshness and quality
  $ faf audit --warn-days 3      # Warn if older than 3 days`)
    .action(withAnalyticsTracking('audit', audit_1.auditFafFile));
// 📈 faf score - See how complete your context is
commander_1.program
    .command('score [file]')
    .description('Rate your .faf completeness (0-100%). Aim for 🥉85% BRONZE+ for solid AI context you can build on')
    .option('-d, --details', 'Show detailed scoring breakdown')
    .option('-m, --minimum <score>', 'Minimum required score (fails if below)')
    .option('-c, --compiler', 'Use new compiler-based scoring (v3)')
    .option('--trace', 'Show compilation trace (with --compiler)')
    .option('--verify <checksum>', 'Verify checksum (with --compiler)')
    .option('--checksum', 'Show checksum for verification')
    .option('--breakdown', 'Show section breakdown (with --compiler)')
    .addHelpText('after', `
Examples:
  $ faf score                    # Quick score check
  $ faf score --details          # See what's missing for higher score
  $ faf score --minimum 80       # Fail if score below 80%
  $ faf score --compiler         # Use v3 compiler scoring
  $ faf score -c --trace         # Show compilation process
  $ faf score -c --checksum      # Get verification checksum`)
    .action(withAnalyticsTracking('score', score_1.scoreFafFile));
// 📝 faf edit - Edit helper
commander_1.program
    .command('edit [file]')
    .description('Get guidance on editing your .faf file to improve score')
    .option('-o, --open', 'Open in default editor')
    .addHelpText('after', `
Examples:
  $ faf edit                     # Show what to edit
  $ faf edit --open              # Open in $EDITOR

Helps you understand which fields to fill for a higher score.`)
    .action(withAnalyticsTracking('edit', edit_helper_1.editFafFile));
// 🏎️  faf show - FAF Stats Display
commander_1.program
    .command('show [directory]')
    .description('🏎️  Display FAF Stats with clean markdown output')
    .option('-r, --raw', 'Output raw markdown (for piping)')
    .addHelpText('after', `
Examples:
  $ faf show                     # Show score card for current directory
  $ faf show ./my-project        # Show score card for specific directory
  $ faf show --raw               # Output raw markdown for piping
  $ faf show --raw | pbcopy      # Copy score card to clipboard

🍫🍊 CHOCOLATE ORANGE - NO WRAPPERS!
Clean markdown output that displays naturally.`)
    .action(withAnalyticsTracking('show', show_1.showFafScoreCard));
// 🔄 faf sync - Keep .faf up-to-date automatically + Bi-directional sync
commander_1.program
    .command('sync [file]')
    .description('Update .faf when dependencies change OR sync with claude.md (bi-directional sync)')
    .option('-a, --auto', 'Automatically apply detected changes')
    .option('-d, --dry-run', 'Show changes without applying')
    .option('-b, --bi-sync', '🔗 Bi-directional sync .faf ↔ claude.md')
    .option('-w, --watch', 'Start real-time file watching (with --bi-sync)')
    .addHelpText('after', `
Examples:
  $ faf sync                     # Show what needs updating
  $ faf sync --auto              # Update automatically
  $ faf sync --dry-run           # Preview changes only
  
🔗 Bi-Sync Examples:
  $ faf sync --bi-sync           # Real-time .faf ↔ claude.md sync
  $ faf sync --bi-sync --watch   # Continuous real-time monitoring
  $ faf sync --bi-sync --auto    # Automatic conflict-free sync

Championship Bi-Sync Features:
  • ⚡ Sub-40ms sync time (faster than most file operations)
  • 🧠 Smart merge algorithms prevent conflicts and data corruption
  • 🔄 Self-healing: Auto-recovers from file locks/system issues
  • 💎 Credit propagation: Technical credit updates both files
  • 🧡 Trust synchronization: AI compatibility scores stay aligned
  • 🛡️ Conflict prevention: Detects simultaneous edits safely`)
    .action(async (file, options) => {
    if (options.biSync) {
        // Bi-directional sync mode
        await (0, bi_sync_1.biSyncCommand)({
            auto: options.auto,
            watch: options.watch,
            force: false
        });
    }
    else {
        // Original sync functionality
        await (0, sync_1.syncFafFile)(file, options);
    }
});
// 🛂 faf tsa - Dependency Inspector (The TSA of Dependencies!)
commander_1.program
    .command('tsa')
    .description('🛂 Inspect dependencies - The TSA of package.json')
    .option('-d, --detailed', 'Show detailed analysis')
    .action(withAnalyticsTracking('tsa', async (options) => {
    const { tsaCommand } = await Promise.resolve().then(() => __importStar(require('./commands/tsa')));
    await tsaCommand(options);
}));
// 🔗 faf bi-sync - Standalone bi-directional sync command
commander_1.program
    .command('bi-sync')
    .description('🔗 Bi-directional sync .faf ↔ claude.md')
    .option('-a, --auto', 'Automatic sync without prompts')
    .option('-w, --watch', 'Start real-time file watching')
    .option('-f, --force', 'Force overwrite conflicts')
    .addHelpText('after', `
Examples:
  $ faf bi-sync                  # Create claude.md and sync
  $ faf bi-sync --auto           # Automatic conflict-free sync
  $ faf bi-sync --watch          # Continuous real-time monitoring
  
Championship Bi-Sync Features:
  • ⚡ Sub-40ms sync time (faster than most file operations)
  • 🧠 Smart merge algorithms prevent conflicts and data corruption
  • 🔄 Self-healing: Auto-recovers from file locks/system issues
  • 💎 Credit propagation: Technical credit updates both files
  • 🧡 Trust synchronization: AI compatibility scores stay aligned
  • 🛡️ Conflict prevention: Detects simultaneous edits safely`)
    .action(async (options) => {
    await (0, bi_sync_1.biSyncCommand)({
        auto: options.auto,
        watch: options.watch,
        force: options.force || false
    });
});
// 📧 faf notifications - Version update notifications
commander_1.program
    .command('notifications')
    .description('📧 Add your email for new version notifications')
    .option('--email <email>', 'Add email for notifications')
    .option('--status', 'Check notification status')
    .option('--remove', 'Remove email from notifications')
    .option('-q, --quiet', 'Skip interactive prompts')
    .addHelpText('after', `
Examples:
  $ faf notifications            # Interactive email add
  $ faf notifications --email me@example.com  # Direct add
  $ faf notifications --status   # Check if email added
  $ faf notifications --remove   # Remove your email

What you get notified about:
  • New versions with features
  • Breaking changes that affect you
  • Critical security updates
  • Only major releases (not every patch)`)
    .action((options) => (0, notifications_1.notificationsCommand)(options));
// 🧹 faf clear - Reset caches and state (Claude Code consistency)
commander_1.program
    .command('clear')
    .description('🧹 Clear caches, temporary files, and reset state')
    .option('--cache', 'Clear trust cache only')
    .option('--todos', 'Clear todo lists only')
    .option('--backups', 'Clear backup files only')
    .option('--all', 'Clear everything (default)')
    .addHelpText('after', `
Examples:
  $ faf clear                    # Clear all caches and temp files
  $ faf clear --cache            # Clear trust cache only
  $ faf clear --todos            # Clear todo lists only
  $ faf clear --backups          # Clear backup files only
  
Claude Code Consistency:
  • Similar to /clear command in Claude Code
  • Fresh start for .faf system
  • Removes temporary files and cached data`)
    .action((options) => (0, clear_1.clearCommand)(options));
// ✏️ faf edit - Interactive .faf editor (Claude Code consistency)  
commander_1.program
    .command('edit')
    .description('✏️ Interactive .faf editor with validation')
    .option('--editor <editor>', 'Specific editor to use (code, vim, nano)')
    .option('--section <section>', 'Edit specific section (project, stack, etc.)')
    .option('--no-validate', 'Skip validation after editing')
    .addHelpText('after', `
Examples:
  $ faf edit                     # Open .faf in default editor
  $ faf edit --editor vim        # Use specific editor
  $ faf edit --section project   # Edit project section only
  $ faf edit --no-validate       # Skip post-edit validation
  
Claude Code Consistency:
  • Similar to /edit command in Claude Code
  • Automatic backup before editing
  • Post-edit validation with restore on errors`)
    .action((options) => (0, edit_1.editCommand)(options));
// 🔍 faf search - Search .faf content (Claude Code consistency)
commander_1.program
    .command('search <query>')
    .description('🔍 Search within .faf file content with highlighting')
    .option('--section <section>', 'Search in specific section only')
    .option('--case', 'Case sensitive search')
    .option('--keys', 'Search keys only')
    .option('--values', 'Search values only')
    .option('--count', 'Show match count only')
    .addHelpText('after', `
Examples:
  $ faf search "react"           # Search for "react" anywhere
  $ faf search "api" --section project  # Search in project section only
  $ faf search "test" --keys     # Search in keys only
  $ faf search "node" --case     # Case sensitive search
  $ faf search "component" --count  # Just show match count
  
Claude Code Consistency:
  • Similar to /search command in Claude Code
  • Intelligent highlighting of matches
  • Section-aware searching with path display`)
    .action(withAnalyticsTracking('search', (query, options) => (0, search_1.searchCommand)(query, options)));
// 🎸 faf skills - Claude Code Skills Integration
commander_1.program
    .command('skills')
    .description('🎸 List Claude Code skills from .faf file')
    .option('-p, --path <path>', 'Path to .faf file or directory')
    .addHelpText('after', `
Examples:
  $ faf skills                   # List skills from .faf
  $ faf skills --path ./project  # Check specific project

Claude Code Skills:
  • Skills are loaded from ~/.claude/skills/
  • Configure in .faf: skills: [faf, wjttc-tester]
  • See: https://github.com/anthropics/skills`)
    .action(withAnalyticsTracking('skills', (options) => (0, skills_1.skillsCommand)(options)));
// 📊 faf analytics - Analytics & Telemetry Management
commander_1.program
    .command('analytics')
    .description('📊 View usage analytics and manage telemetry settings')
    .option('-s, --summary', 'Show analytics summary')
    .option('-d, --disable', 'Disable telemetry collection')
    .option('-e, --enable', 'Enable telemetry collection')
    .option('--reset', 'Reset all analytics data')
    .addHelpText('after', `
Examples:
  $ faf analytics --summary          # View usage statistics
  $ faf analytics --disable          # Turn off telemetry
  $ faf analytics --enable           # Turn on telemetry
  $ faf analytics --reset            # Clear analytics data
  
Championship Analytics:
  • 📊 Performance metrics (F1-inspired speed tracking)
  • 📊 Command usage patterns and favorites
  • 📈 Trust score improvements over time
  • 🔒 Privacy-first: All data anonymized and local
  • 🚀 Help make FAF better for everyone!
  
Privacy Controls:
  • Telemetry can be disabled anytime
  • No sensitive data collected (keys, tokens filtered)
  • All metrics stored locally first
  • Opt-in for improvement insights`)
    .action(withAnalyticsTracking('analytics', async (options) => {
    if (options.summary) {
        await analytics_1.analytics.showAnalyticsSummary();
    }
    else if (options.disable) {
        await analytics_1.analytics.disableTelemetry();
    }
    else if (options.enable) {
        await analytics_1.analytics.enableTelemetry();
    }
    else if (options.reset) {
        console.log(colors_1.chalk.yellow('⚠️  Analytics reset not available'));
        console.log(colors_1.chalk.gray('   Use: faf analytics --disable to turn off analytics'));
    }
    else {
        // Default: show summary
        await analytics_1.analytics.showAnalyticsSummary();
    }
}));
// 🩵 faf faq - Show FAQ
commander_1.program
    .command('faq')
    .description('🩵 Frequently Asked Questions - Get help with common issues')
    .option('-s, --search <term>', 'Search FAQ for specific topic')
    .addHelpText('after', `
Examples:
  $ faf faq                      # Show full FAQ
  $ faf faq --search spacebar    # Search for spacebar info
  $ faf faq --search commands    # Search for command info`)
    .action(withAnalyticsTracking('faq', async (options) => {
    const faqCommand = await Promise.resolve().then(() => __importStar(require('./commands/faq')));
    await faqCommand.faqCommand(options);
}));
// 🔧 faf lint - Clean up formatting automatically
commander_1.program
    .command('lint [file]')
    .description('Fix .faf formatting and style issues')
    .option('-f, --fix', 'Automatically fix formatting issues')
    .option('--schema-version <version>', 'Validate against specific schema version')
    .addHelpText('after', `
Examples:
  $ faf lint                     # Check formatting issues
  $ faf lint --fix               # Fix formatting automatically
  $ faf lint --schema-version 2.4.0  # Use specific schema`)
    .action(lint_1.lintFafFile);
// 🚀 faf enhance - REAL Enhancement based on facts
commander_1.program
    .command('enhance [file]')
    .description('🚀 REAL Enhancement - Analyzes your project for actual improvements')
    .option('-v, --verbose', 'Show detailed changes')
    .option('--dry-run', 'Preview improvements without applying')
    .option('--auto-fill', 'Automatically fill all detectable fields')
    .option('-t, --target-score <score>', 'Target score to achieve (default: 100)', '100')
    .option('-i, --interactive <bool>', 'Ask for missing data (default: true)', 'true')
    .addHelpText('after', `
🚀 REAL Enhancement:
  $ faf enhance              # Apply real improvements from project analysis
  $ faf enhance --dry-run    # Preview what will be improved
  $ faf enhance --verbose    # Show detailed changes
  $ faf enhance -t 90        # RELENTLESSLY enhance until 90% score

✅ No BS, No Placeholders - Only facts from your actual project!
🎯 Relentless mode: Keeps enhancing until target score achieved`)
    .action((file, options) => {
    const enhanceOptions = {
        verbose: options.verbose,
        dryRun: options.dryRun,
        autoFill: options.autoFill,
        targetScore: parseInt(options.targetScore),
        interactive: options.interactive !== 'false'
    };
    return (0, enhance_real_1.realEnhanceFaf)(file, enhanceOptions);
});
// 🔍 faf analyze - Claude-First, Big-3 Compatible Analysis
commander_1.program
    .command('analyze [file]')
    .description('🔍 Claude-First AI Analysis - Big-3 Compatible Intelligence')
    .option('-m, --model <model>', 'AI model: claude|chatgpt|gemini|big3|universal', 'claude')
    .option('-f, --focus <area>', 'Focus: completeness|quality|ai-readiness|human-context|claude-exclusive')
    .option('-v, --verbose', 'Show detailed section breakdown')
    .option('-s, --suggestions', 'Include automated suggestions')
    .option('-c, --comparative', 'Compare perspectives from multiple models')
    .addHelpText('after', `
🤖 Claude-First Analysis:
  $ faf analyze                            # Claude intelligence (default)
  $ faf analyze --model big3               # Big-3 perspective analysis
  $ faf analyze --focus claude-exclusive   # Claude's championship analysis
  $ faf analyze --comparative              # Multi-model comparison
  $ faf analyze --verbose --suggestions    # Detailed analysis + tips

🚀 NO EXTERNAL DEPENDENCIES - Uses our own Big-3 verification engine!`)
    .action(ai_analyze_1.analyzeFafWithAI);
// Handle unknown commands with helpful suggestions
commander_1.program
    .command('*')
    .action((cmd) => {
    console.log(colors_1.chalk.red(`❌ Unknown command: ${cmd}`));
    console.log('');
    console.log(championship_style_1.FAF_COLORS.fafOrange('💡 Did you mean:'));
    console.log('  ' + colors_1.chalk.cyan('faf init') + '     # Create .faf file');
    console.log('  ' + colors_1.chalk.cyan('faf score') + '    # Check completeness');
    console.log('  ' + colors_1.chalk.cyan('faf --help') + '   # See all commands');
    process.exit(1);
});
/**
 * Interactive welcome screen with persistent bottom command line
 */
async function showInteractiveWelcome() {
    // Check if we're in an interactive terminal
    if (!process.stdin.isTTY) {
        console.log('\n🏎️ FAF Interactive Menu requires an interactive terminal\n');
        console.log('💡 When using AI assistants or CI/CD:\n');
        console.log('   faf init      - Create .faf file');
        console.log('   faf auto      - Automatically enhance context');
        console.log('   faf score     - Check your score');
        console.log('   faf --help    - See all commands\n');
        return;
    }
    // Clear screen and set up persistent layout
    console.clear();
    // ASCII Header
    console.log((0, championship_style_1.generateFAFHeader)());
    console.log('');
    console.log(colors_1.chalk.dim('Using faf menu'));
    console.log('');
    // Hello User
    const username = require('os').userInfo().username;
    console.log(colors_1.chalk.cyan.bold(`  👋 Hello ${username}!`));
    console.log('');
    // Ready message
    console.log(colors_1.chalk.white('  Ready to make your AI happy again?'));
    console.log('');
    try {
        const answer = await inquirer_1.default.prompt([
            {
                type: 'list',
                name: 'action',
                message: 'Select an option',
                choices: [
                    { name: '1. Create your first .faf file', value: 'init' },
                    { name: '2. Interactive context builder', value: 'chat' },
                    { name: '3. See all commands', value: 'help' },
                    { name: '4. FAQ - Get help & answers', value: 'faq' },
                    { name: '5. Browse everything A-Z', value: 'index' },
                    { name: '6. Switch to command line', value: 'commandline' },
                    new inquirer_1.default.Separator('')
                ]
            }
        ]);
        // If user selected command line mode, switch to persistent typing
        if (answer.action === 'commandline') {
            console.clear();
            console.log((0, championship_style_1.generateFAFHeader)());
            console.log('');
            console.log(colors_1.chalk.dim('Using faf CLI'));
            console.log('');
            console.log(colors_1.chalk.cyan.bold('⌨️  Command Line Mode'));
            console.log(colors_1.chalk.gray('Type commands, "menu" for menu, or "index" for the .faf A-Z'));
            console.log('');
            // Persistent command line loop with spacebar detection
            let inCommandMode = true;
            while (inCommandMode) {
                const cmdAnswer = await new Promise((resolve) => {
                    let inputBuffer = '';
                    // Show prompt
                    process.stdout.write('> ');
                    // Set up raw keyboard input for spacebar detection
                    if (process.stdin.isTTY) {
                        process.stdin.setRawMode(true);
                        process.stdin.resume();
                        process.stdin.setEncoding('utf8');
                        const keyHandler = (key) => {
                            // Spacebar pressed - toggle to menu
                            if (key === ' ' && inputBuffer === '') {
                                process.stdin.setRawMode(false);
                                process.stdin.removeListener('data', keyHandler);
                                console.log('\n' + colors_1.chalk.dim('🎯 Switching to menu...'));
                                resolve({ command: 'menu' });
                                return;
                            }
                            // Escape pressed - exit
                            if (key === '\u001b') {
                                process.stdin.setRawMode(false);
                                process.stdin.removeListener('data', keyHandler);
                                console.log('\n👋 Goodbye!');
                                process.exit(0);
                            }
                            // Enter pressed - execute command
                            if (key === '\r' || key === '\n') {
                                process.stdin.setRawMode(false);
                                process.stdin.removeListener('data', keyHandler);
                                console.log('');
                                resolve({ command: inputBuffer });
                                return;
                            }
                            // Backspace
                            if (key === '\u007f') {
                                if (inputBuffer.length > 0) {
                                    inputBuffer = inputBuffer.slice(0, -1);
                                    process.stdout.write('\b \b');
                                }
                                return;
                            }
                            // Regular character
                            if (key >= ' ' && key <= '~') {
                                inputBuffer += key;
                                process.stdout.write(key);
                            }
                        };
                        process.stdin.on('data', keyHandler);
                    }
                    else {
                        // Fallback for non-TTY - use regular inquirer
                        inquirer_1.default.prompt([{
                                type: 'input',
                                name: 'command',
                                message: '>'
                            }]).then(resolve);
                    }
                });
                const command = cmdAnswer.command.trim().toLowerCase();
                // Handle mode switching commands
                if (command === 'exit' || command === 'quit') {
                    console.log('👋 Goodbye!');
                    process.exit(0);
                }
                if (command === 'menu') {
                    inCommandMode = false;
                    console.log(colors_1.chalk.dim('↩️  Returning to menu...'));
                    console.log('');
                    // Recursively call showInteractiveWelcome to return to menu
                    await showInteractiveWelcome();
                    return;
                }
                // Execute typed command
                switch (command) {
                    case 'init':
                        await (0, init_1.initFafFile)();
                        break;
                    case 'chat':
                        await (0, chat_1.chatCommand)();
                        break;
                    case 'help':
                        commander_1.program.help();
                        break;
                    case 'index':
                        await (0, index_1.indexCommand)();
                        break;
                    case 'status':
                        await (0, status_1.statusCommand)();
                        break;
                    case 'faq':
                        const faqCommand = await Promise.resolve().then(() => __importStar(require('./commands/faq')));
                        await faqCommand.faqCommand();
                        break;
                    case '':
                        // Empty command, just continue
                        break;
                    default:
                        // Check if user tried a slash command
                        if (command.startsWith('/')) {
                            const commandWithoutSlash = command.slice(1);
                            console.log(colors_1.chalk.red(`❌ Unknown command: ${command}`));
                            console.log(championship_style_1.FAF_COLORS.fafCyan('🎉 Good news! You don\'t need a slash in FAF CLI mode'));
                            console.log(championship_style_1.FAF_COLORS.fafOrange(`💡 Try: ${commandWithoutSlash} (without the /)`));
                        }
                        else {
                            console.log(colors_1.chalk.red(`❌ Unknown command: ${command}`));
                            console.log(championship_style_1.FAF_COLORS.fafOrange('💡 Try: init, chat, help, index, status, score, exit'));
                        }
                        break;
                }
                console.log('');
            }
        }
        else {
            // Execute selected menu item
            const action = answer.action;
            switch (action) {
                case 'init':
                    await (0, init_1.initFafFile)();
                    break;
                case 'chat':
                    await (0, chat_1.chatCommand)();
                    break;
                case 'help':
                    commander_1.program.help();
                    break;
                case 'faq':
                    const faqMenuCommand = await Promise.resolve().then(() => __importStar(require('./commands/faq')));
                    await faqMenuCommand.faqCommand();
                    break;
                case 'index':
                    await (0, index_1.indexCommand)();
                    break;
            }
        }
    }
    catch (error) {
        if (error instanceof Error && error.message.includes('User force closed')) {
            console.log(`\n${colors_1.chalk.cyan('👋 See you later!')}\n`);
        }
        else {
            console.error(`\n${colors_1.chalk.red('❌ Error:')} ${error}\n`);
        }
    }
}
// Show header based on command used BEFORE parsing
const commandUsed = process.argv[2];
// Special case: No arguments at all - use smart FAF logic
if (!commandUsed) {
    Promise.resolve().then(() => __importStar(require('./smart-faf'))).then(module => {
        const SmartFaf = module.default;
        const smartFaf = new SmartFaf();
        return smartFaf.execute();
    }).then(() => process.exit(0)).catch(err => {
        console.error(err);
        process.exit(1);
    });
}
else {
    // Parse CLI arguments to check for gearbox flags
    const parsed = commander_1.program.parse(process.argv);
    const options = commander_1.program.opts();
    // Gearbox system: Auto/Manual mode detection
    const isAutoMode = options.auto;
    const isManualMode = options.manual;
    // Auto mode - show interactive welcome
    if (isAutoMode) {
        showInteractiveWelcome().then(() => process.exit(0)).catch(err => {
            console.error(err);
            process.exit(1);
        });
    }
    else {
        const isHelp = commandUsed === '--help' || commandUsed === '-h' || commandUsed === 'help';
        showHeaderIfAppropriate(isHelp ? 'help' : commandUsed);
        // Check for updates (non-blocking, respects quiet mode)
        (0, update_checker_1.checkForUpdates)({ quiet: options.quiet }).catch(() => {
            // Silent fail - update check is not critical
        });
        // Show v2.4.0 announcement to existing users (one time only)
        (0, announcements_1.showV240Announcement)();
        // Apply color accessibility settings after parsing
        if (options.noColor || process.env.NO_COLOR) {
            (0, color_utils_1.setColorOptions)(false);
        }
        else if (options.colorScheme) {
            const scheme = options.colorScheme;
            const validSchemes = ['normal', 'deuteranopia', 'protanopia', 'tritanopia'];
            if (validSchemes.includes(scheme)) {
                (0, color_utils_1.setColorOptions)(true, scheme);
            }
            else {
                console.log(colors_1.chalk.red(`❌ Invalid color scheme: ${scheme}`));
                console.log(championship_style_1.FAF_COLORS.fafOrange(`💡 Valid schemes: ${validSchemes.join(', ')}`));
                process.exit(1);
            }
        }
        // Execute the parsed command
        commander_1.program.execute(parsed).catch(err => {
            console.error(err);
            process.exit(1);
        });
    }
}
//# sourceMappingURL=cli.js.map