"use strict";
/**
 * 🏆 faf fam - FAF Family Integration Marketplace
 *
 * Discovery, status, and marketplace for championship integrations
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.famCommand = famCommand;
const colors_1 = require("../fix-once/colors");
const championship_style_1 = require("../utils/championship-style");
const registry_1 = require("../family/registry");
/**
 * Get tier emoji
 */
function getTierEmoji(tier) {
    const emojis = {
        trophy: '🏆',
        gold: '🥇',
        silver: '🥈',
        bronze: '🥉',
    };
    return emojis[tier] || '⚪';
}
/**
 * Format large numbers with commas
 */
function formatNumber(num) {
    return num.toLocaleString();
}
/**
 * Check if integration requires TURBO
 */
function requiresTurbo(name) {
    // n8n is our LEAD integration requiring TURBO
    return name === 'n8n';
}
/**
 * Main faf fam command - show integrations
 */
async function famCommand(subcommand, arg, options) {
    // Handle subcommands
    if (subcommand === 'show') {
        return await showIntegration(arg);
    }
    else if (subcommand === 'install') {
        return await installIntegration(arg);
    }
    else if (subcommand === 'detect') {
        return await detectCommand();
    }
    // Default: List all integrations
    return await listIntegrations(options);
}
/**
 * List all integrations with status
 */
async function listIntegrations(options) {
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafCyan('🏆 FAF Family - Championship Integrations'));
    console.log(championship_style_1.FAF_COLORS.fafCyan('═'.repeat(50)));
    console.log();
    try {
        // Get current directory for detection
        const projectPath = process.cwd();
        const detected = await registry_1.integrationRegistry.detectAll(projectPath);
        const stats = registry_1.integrationRegistry.getStats();
        // Show detected integrations in project
        if (detected.length > 0) {
            console.log(championship_style_1.FAF_COLORS.fafOrange('YOUR PROJECT:'));
            console.log();
            detected.forEach((integration) => {
                const emoji = getTierEmoji(integration.tier);
                console.log(`  ${colors_1.chalk.green('✅')} ${colors_1.chalk.bold(integration.displayName)}`);
                console.log(`     ${emoji} ${colors_1.chalk.cyan(integration.tier)} tier`);
                console.log(`     ${colors_1.chalk.gray(formatNumber(integration.weeklyAdoption) + ' weekly developers')}`);
                console.log();
            });
            // Show MCP recommendations
            const allMcpServers = detected.flatMap(d => d.mcpServers);
            if (allMcpServers.length > 0) {
                console.log(championship_style_1.FAF_COLORS.fafCyan('  🎯 Recommended MCP Servers:'));
                allMcpServers.forEach(server => {
                    console.log(`     ${colors_1.chalk.gray('•')} ${colors_1.chalk.cyan(server)}`);
                });
                console.log();
            }
            console.log(colors_1.chalk.gray('─'.repeat(50)));
            console.log();
        }
        else {
            console.log(championship_style_1.FAF_COLORS.fafOrange('YOUR PROJECT:'));
            console.log();
            console.log(colors_1.chalk.gray('  No integrations detected in current project'));
            console.log();
            console.log(colors_1.chalk.gray('─'.repeat(50)));
            console.log();
        }
        // Show available integrations
        console.log(championship_style_1.FAF_COLORS.fafOrange('AVAILABLE INTEGRATIONS:'));
        console.log();
        // Get all integrations and sort by weekly adoption
        const allIntegrations = Array.from(registry_1.integrationRegistry.integrations.values())
            .sort((a, b) => b.weeklyAdoption - a.weeklyAdoption);
        // Filter out already detected ones for "available" section
        const notDetected = allIntegrations.filter(integration => !detected.find(d => d.name === integration.name));
        if (notDetected.length > 0) {
            notDetected.forEach((integration) => {
                const emoji = getTierEmoji(integration.tier);
                const turboTag = requiresTurbo(integration.name)
                    ? ` ${championship_style_1.FAF_COLORS.fafOrange('[TURBO ONLY]')}`
                    : '';
                console.log(`  ${emoji} ${colors_1.chalk.bold(integration.displayName)}${turboTag}`);
                console.log(`     ${colors_1.chalk.gray(integration.tier + ' tier • ' + formatNumber(integration.weeklyAdoption) + ' weekly developers')}`);
                console.log(`     ${colors_1.chalk.gray(integration.mcpServers.length + ' MCP server(s) • ' + integration.contextContribution.length + ' context slots')}`);
                console.log();
            });
        }
        // Show registry stats
        console.log(colors_1.chalk.gray('─'.repeat(50)));
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafCyan('📊 ECOSYSTEM STATS:'));
        console.log();
        console.log(`  Total integrations: ${colors_1.chalk.cyan(stats.total.toString())}`);
        console.log(`  Total reach: ${colors_1.chalk.cyan(formatNumber(stats.totalWeeklyAdoption))} developers/week`);
        console.log();
        // Show tier breakdown
        console.log('  By tier:');
        Object.entries(stats.byTier).forEach(([tier, count]) => {
            const emoji = getTierEmoji(tier);
            console.log(`    ${emoji} ${tier}: ${colors_1.chalk.cyan(count.toString())}`);
        });
        console.log();
        // Show help
        console.log(colors_1.chalk.gray('─'.repeat(50)));
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange('💡 COMMANDS:'));
        console.log();
        console.log(`  ${colors_1.chalk.cyan('faf fam')}              ${colors_1.chalk.gray('# Show all integrations (this view)')}`);
        console.log(`  ${colors_1.chalk.cyan('faf fam detect')}       ${colors_1.chalk.gray('# Auto-detect integrations in current project')}`);
        console.log(`  ${colors_1.chalk.cyan('faf fam show react')}   ${colors_1.chalk.gray('# Details about React integration')}`);
        console.log(`  ${colors_1.chalk.cyan('faf fam install n8n')}  ${colors_1.chalk.gray('# Install integration (coming soon)')}`);
        console.log();
    }
    catch (error) {
        console.error(colors_1.chalk.red('❌ Error loading integrations:'), error);
    }
}
/**
 * Show details about a specific integration
 */
async function showIntegration(name) {
    console.log();
    const integration = registry_1.integrationRegistry.get(name);
    if (!integration) {
        console.log(colors_1.chalk.red(`❌ Integration not found: ${name}`));
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange('💡 Available integrations:'));
        const all = registry_1.integrationRegistry.list();
        all.forEach(n => console.log(`  • ${n}`));
        console.log();
        return;
    }
    const emoji = getTierEmoji(integration.tier);
    const turboTag = requiresTurbo(integration.name)
        ? ` ${championship_style_1.FAF_COLORS.fafOrange('[TURBO ONLY]')}`
        : '';
    console.log(championship_style_1.FAF_COLORS.fafCyan(`${emoji} ${integration.displayName}${turboTag}`));
    console.log(championship_style_1.FAF_COLORS.fafCyan('═'.repeat(50)));
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafOrange('OVERVIEW:'));
    console.log(`  Tier: ${colors_1.chalk.cyan(integration.tier)}`);
    console.log(`  Quality Score: ${colors_1.chalk.cyan(integration.qualityScore + '/100')}`);
    console.log(`  Weekly Adoption: ${colors_1.chalk.cyan(formatNumber(integration.weeklyAdoption))} developers`);
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafOrange('MCP SERVERS:'));
    integration.mcpServers.forEach(server => {
        console.log(`  ${colors_1.chalk.cyan('•')} ${server}`);
    });
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafOrange('CONTEXT CONTRIBUTION:'));
    console.log(`  Fills ${colors_1.chalk.cyan(integration.contextContribution.length.toString())} .faf slots:`);
    integration.contextContribution.forEach(slot => {
        console.log(`  ${colors_1.chalk.cyan('•')} ${slot}`);
    });
    console.log();
    // Check if detected in current project
    const projectPath = process.cwd();
    const isDetected = await integration.detect(projectPath);
    if (isDetected) {
        console.log(colors_1.chalk.green('✅ DETECTED in your project!'));
        console.log();
    }
    else {
        console.log(colors_1.chalk.gray('❌ Not detected in your project'));
        console.log();
    }
    // Show TURBO info if applicable
    if (requiresTurbo(integration.name)) {
        console.log(championship_style_1.FAF_COLORS.fafOrange('🚀 TURBO FEATURE:'));
        console.log(`  This integration requires ${colors_1.chalk.cyan('FAF TURBO')} ($19)`);
        console.log();
        console.log('  What you get:');
        console.log(`  ${colors_1.chalk.cyan('✅')} ${integration.displayName} auto-detection`);
        console.log(`  ${colors_1.chalk.cyan('✅')} MCP server recommendations`);
        console.log(`  ${colors_1.chalk.cyan('✅')} Smart .faf context generation`);
        console.log(`  ${colors_1.chalk.cyan('✅')} Priority integration updates`);
        console.log();
    }
    console.log(colors_1.chalk.gray('─'.repeat(50)));
    console.log();
}
/**
 * Install integration (placeholder for now)
 */
async function installIntegration(name) {
    console.log();
    const integration = registry_1.integrationRegistry.get(name);
    if (!integration) {
        console.log(colors_1.chalk.red(`❌ Integration not found: ${name}`));
        console.log();
        return;
    }
    // Check if requires TURBO
    if (requiresTurbo(integration.name)) {
        console.log(championship_style_1.FAF_COLORS.fafOrange(`🥇 ${integration.displayName} Integration`));
        console.log();
        console.log(colors_1.chalk.yellow('⚠️  This integration requires FAF TURBO'));
        console.log();
        console.log('What you get:');
        console.log(`  ${colors_1.chalk.cyan('✅')} Auto-detection and smart .faf generation`);
        console.log(`  ${colors_1.chalk.cyan('✅')} MCP server setup (${integration.mcpServers.join(', ')})`);
        console.log(`  ${colors_1.chalk.cyan('✅')} ${integration.contextContribution.length} context slots auto-filled`);
        console.log(`  ${colors_1.chalk.cyan('✅')} Priority support and updates`);
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange('💰 Upgrade to TURBO:'));
        console.log(`  Visit: ${colors_1.chalk.cyan('https://faf.one/pricing')}`);
        console.log();
        return;
    }
    // For free integrations (future)
    console.log(championship_style_1.FAF_COLORS.fafCyan(`🎯 Installing ${integration.displayName}...`));
    console.log();
    console.log(colors_1.chalk.yellow('⚠️  Installation feature coming soon!'));
    console.log();
    console.log('For now:');
    console.log(`  1. Add ${integration.displayName} to your project`);
    console.log(`  2. Run ${colors_1.chalk.cyan('faf init')} to detect it`);
    console.log(`  3. Run ${colors_1.chalk.cyan('faf fam')} to see it in YOUR PROJECT`);
    console.log();
}
/**
 * Detect integrations in current project (focused view)
 */
async function detectCommand() {
    console.log();
    console.log(championship_style_1.FAF_COLORS.fafCyan('🔍 Scanning project...'));
    console.log();
    try {
        const projectPath = process.cwd();
        const detected = await registry_1.integrationRegistry.detectAll(projectPath);
        const allIntegrations = Array.from(registry_1.integrationRegistry.integrations.values());
        const stats = registry_1.integrationRegistry.getStats();
        if (detected.length === 0) {
            console.log(colors_1.chalk.gray('❌ No FAF integrations detected in current project'));
            console.log();
            console.log(championship_style_1.FAF_COLORS.fafOrange('💡 TIP:'));
            console.log(`  Run ${colors_1.chalk.cyan('faf fam')} to see all available integrations`);
            console.log();
            return;
        }
        // Show detected integrations
        console.log(championship_style_1.FAF_COLORS.fafCyan('🏆 DETECTED INTEGRATIONS:'));
        console.log();
        // Sort by tier quality
        const tierOrder = { trophy: 1, gold: 2, silver: 3, bronze: 4 };
        const sortedDetected = detected.sort((a, b) => {
            return tierOrder[a.tier] - tierOrder[b.tier];
        });
        sortedDetected.forEach((integration) => {
            const emoji = getTierEmoji(integration.tier);
            const turboTag = requiresTurbo(integration.name)
                ? ` ${championship_style_1.FAF_COLORS.fafOrange('[TURBO ONLY]')}`
                : '';
            console.log(`  ${colors_1.chalk.green('✅')} ${colors_1.chalk.bold(integration.displayName)}${turboTag}`);
            console.log(`     ${emoji} ${colors_1.chalk.cyan(integration.tier)} tier • ${colors_1.chalk.gray(formatNumber(integration.weeklyAdoption) + ' weekly devs')}`);
            // Show MCP servers
            if (integration.mcpServers.length > 0) {
                console.log(`     ${colors_1.chalk.gray('MCP Servers:')}`);
                integration.mcpServers.forEach(server => {
                    console.log(`       ${colors_1.chalk.cyan('•')} ${server}`);
                });
            }
            console.log();
        });
        // Calculate total MCP servers and ecosystem reach
        const allMcpServers = detected.flatMap(d => d.mcpServers);
        const uniqueMcpServers = [...new Set(allMcpServers)];
        const totalReach = detected.reduce((sum, d) => sum + d.weeklyAdoption, 0);
        // Determine stack quality
        const avgScore = detected.reduce((sum, d) => sum + d.qualityScore, 0) / detected.length;
        let qualityTier = '🤍 Unrated';
        if (avgScore >= 99)
            qualityTier = '🏆 Trophy Tier';
        else if (avgScore >= 95)
            qualityTier = '🥇 Gold Tier';
        else if (avgScore >= 90)
            qualityTier = '🥈 Silver Tier';
        else if (avgScore >= 85)
            qualityTier = '🥉 Bronze Tier';
        // Show summary
        console.log(championship_style_1.FAF_COLORS.fafOrange('📊 STACK QUALITY:') + ` ${qualityTier}`);
        console.log(`📈 Total ecosystem reach: ${colors_1.chalk.cyan(formatNumber(totalReach))} developers`);
        console.log(`🔧 ${colors_1.chalk.cyan(uniqueMcpServers.length.toString())} unique MCP servers recommended`);
        console.log(`✨ ${colors_1.chalk.cyan(detected.reduce((sum, d) => sum + d.contextContribution.length, 0).toString())} .faf context slots filled`);
        console.log();
        // Show NOT detected
        const notDetected = allIntegrations.filter(integration => !detected.find(d => d.name === integration.name));
        if (notDetected.length > 0) {
            console.log(championship_style_1.FAF_COLORS.fafOrange('❌ NOT DETECTED:'));
            const names = notDetected.map(i => i.displayName).join(', ');
            console.log(`  ${colors_1.chalk.gray(names)}`);
            console.log();
        }
        console.log(colors_1.chalk.gray('─'.repeat(50)));
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafOrange('💡 NEXT STEPS:'));
        console.log(`  ${colors_1.chalk.cyan('faf fam show <name>')}  - Details about specific integration`);
        console.log(`  ${colors_1.chalk.cyan('faf init')}             - Generate .faf with detected stack`);
        console.log(`  ${colors_1.chalk.cyan('faf fam')}              - See all available integrations`);
        console.log();
    }
    catch (error) {
        console.error(colors_1.chalk.red('❌ Error detecting integrations:'), error);
    }
}
//# sourceMappingURL=fam.js.map