/**
 * Vigthoria CLI - Hub/Marketplace Commands
 *
 * In-flow marketplace discovery and module activation
 * Enables pay-as-you-go module usage directly from the terminal
 */
import chalk from 'chalk';
const API_BASE = 'https://api.vigthoria.io';
export class HubCommand {
    config;
    logger;
    constructor(config, logger) {
        this.config = config;
        this.logger = logger;
    }
    /**
     * Search for modules by natural language query
     */
    async search(query) {
        console.log(chalk.cyan('\n🔍 Searching Vigthoria Module Hub...\n'));
        try {
            const response = await fetch(`${API_BASE}/api/modules/search`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ query })
            });
            if (!response.ok) {
                throw new Error(`Search failed: ${response.statusText}`);
            }
            const data = await response.json();
            if (data.results.length === 0) {
                console.log(chalk.yellow('No modules found matching your query.'));
                console.log(chalk.gray('Try: vigthoria hub list  to see all available modules\n'));
                return;
            }
            console.log(chalk.green(`Found ${data.results.length} module(s):\n`));
            data.results.forEach((module, index) => {
                const statusColor = module.status === 'active' ? chalk.green : chalk.gray;
                console.log(chalk.bold.white(`  ${index + 1}. ${module.name}`));
                console.log(chalk.gray(`     ${module.description.substring(0, 80)}...`));
                console.log(chalk.cyan(`     💰 ${module.pricing.example}`));
                console.log(statusColor(`     📊 Status: ${module.status.toUpperCase()}`));
                console.log(chalk.gray(`     🔗 ${module.documentation}`));
                console.log();
            });
            if (data.suggestion) {
                console.log(chalk.cyan(`💡 ${data.suggestion}`));
            }
            console.log(chalk.gray('\nTo activate a module: vigthoria hub activate <module-name>'));
            console.log(chalk.gray('Example: vigthoria hub activate music\n'));
        }
        catch (error) {
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`Error: ${errMsg}`));
            console.log(chalk.gray('Make sure you have an active internet connection.'));
        }
    }
    /**
     * List all available modules
     */
    async list(options) {
        console.log(chalk.cyan('\n📦 Vigthoria Module Hub\n'));
        try {
            let url = `${API_BASE}/api/modules`;
            if (options.category) {
                url += `?category=${options.category}`;
            }
            const response = await fetch(url);
            const data = await response.json();
            console.log(chalk.bold.white('Available Modules:\n'));
            // Group by category
            const grouped = data.modules.reduce((acc, module) => {
                if (!acc[module.category])
                    acc[module.category] = [];
                acc[module.category].push(module);
                return acc;
            }, {});
            Object.entries(grouped).forEach(([category, modules]) => {
                console.log(chalk.cyan.bold(`  ${category.toUpperCase()}`));
                console.log(chalk.gray('  ' + '─'.repeat(50)));
                modules.forEach((module) => {
                    console.log(chalk.white(`  📦 ${module.name.padEnd(25)} ${chalk.gray(module.id)}`));
                    console.log(chalk.gray(`     ${module.description.substring(0, 60)}...`));
                    console.log(chalk.yellow(`     ${module.pricing.example}`));
                    console.log();
                });
            });
            console.log(chalk.gray('─'.repeat(60)));
            console.log(chalk.cyan('\nCommands:'));
            console.log(chalk.gray('  vigthoria hub search "generate music"  - Semantic search'));
            console.log(chalk.gray('  vigthoria hub activate <module>        - Activate module'));
            console.log(chalk.gray('  vigthoria hub active                   - Show active modules'));
            console.log(chalk.gray('  vigthoria hub info <module>            - Module details\n'));
        }
        catch (error) {
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`Error: ${errMsg}`));
        }
    }
    /**
     * Activate a module for the current user
     */
    async activate(moduleId) {
        const authToken = this.config.get('authToken');
        if (!authToken) {
            console.log(chalk.red('\n❌ Not authenticated. Run: vigthoria login\n'));
            return;
        }
        console.log(chalk.cyan(`\n🔌 Activating module: ${moduleId}...\n`));
        try {
            const response = await fetch(`${API_BASE}/api/modules/${moduleId}/activate`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${authToken}`,
                    'Content-Type': 'application/json'
                }
            });
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || response.statusText);
            }
            const data = await response.json();
            console.log(chalk.green(`✅ ${data.message}`));
            console.log();
            console.log(chalk.white('📚 Documentation:'));
            console.log(chalk.gray(`   ${data.documentation}`));
            console.log();
            console.log(chalk.white('🔗 Available Endpoints:'));
            data.endpoints.forEach((ep) => {
                console.log(chalk.gray(`   ${ep.method.padEnd(6)} ${ep.path}`));
                console.log(chalk.gray(`         ${ep.description}`));
            });
            console.log();
            console.log(chalk.cyan('💡 Quick Start:'));
            console.log(chalk.gray(`   Use your API key in requests:`));
            console.log(chalk.gray(`   Authorization: Bearer ${authToken.substring(0, 8)}...`));
            console.log();
        }
        catch (error) {
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`❌ Activation failed: ${errMsg}`));
            console.log(chalk.gray('\nMake sure the module ID is correct.'));
            console.log(chalk.gray('Run: vigthoria hub list  to see available modules.'));
        }
    }
    /**
     * Show currently active modules for user
     */
    async active() {
        const authToken = this.config.get('authToken');
        if (!authToken) {
            console.log(chalk.red('\n❌ Not authenticated. Run: vigthoria login\n'));
            return;
        }
        console.log(chalk.cyan('\n📦 Your Active Modules\n'));
        try {
            const response = await fetch(`${API_BASE}/api/modules/active`, {
                headers: {
                    'Authorization': `Bearer ${authToken}`
                }
            });
            if (!response.ok) {
                throw new Error(`Failed to fetch: ${response.statusText}`);
            }
            const data = await response.json();
            if (data.allAccess) {
                console.log(chalk.green('🌟 You have access to ALL modules!\n'));
            }
            console.log(chalk.white(`Tier: ${chalk.cyan.bold(data.tier.toUpperCase())}`));
            console.log();
            if (data.activeModules.length === 0) {
                console.log(chalk.yellow('No modules activated yet.'));
                console.log(chalk.gray('\nActivate modules with: vigthoria hub activate <module>'));
            }
            else {
                console.log(chalk.white('Active modules:'));
                data.activeModules.forEach((module) => {
                    console.log(chalk.green(`  ✅ ${module.name}`));
                    console.log(chalk.gray(`     Endpoint: ${module.endpoint}`));
                    console.log(chalk.yellow(`     Cost: ${module.pricing.example}`));
                    console.log();
                });
            }
        }
        catch (error) {
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`Error: ${errMsg}`));
        }
    }
    /**
     * Get detailed info about a specific module
     */
    async info(moduleId) {
        console.log(chalk.cyan(`\n📖 Module Info: ${moduleId}\n`));
        try {
            const response = await fetch(`${API_BASE}/api/modules/${moduleId}`);
            if (!response.ok) {
                throw new Error('Module not found');
            }
            const module = await response.json();
            console.log(chalk.bold.white(`${module.name}`));
            console.log(chalk.gray('─'.repeat(50)));
            console.log();
            console.log(chalk.white('Description:'));
            console.log(chalk.gray(`  ${module.description}`));
            console.log();
            console.log(chalk.white('Category:'), chalk.cyan(module.category));
            console.log(chalk.white('Tags:'), chalk.gray(module.tags.join(', ')));
            console.log();
            console.log(chalk.white('💰 Pricing:'));
            console.log(chalk.yellow(`  ${module.pricing.example}`));
            console.log(chalk.gray(`  Billed per ${module.pricing.unit}`));
            console.log();
            if (module.rateLimits) {
                console.log(chalk.white('📊 Rate Limits:'));
                Object.entries(module.rateLimits).forEach(([tier, limit]) => {
                    console.log(chalk.gray(`  ${tier.padEnd(12)} ${limit} requests/minute`));
                });
                console.log();
            }
            if (module.endpoints) {
                console.log(chalk.white('🔗 Endpoints:'));
                module.endpoints.forEach((ep) => {
                    console.log(chalk.cyan(`  ${ep.method.padEnd(6)} ${ep.path}`));
                    console.log(chalk.gray(`         ${ep.description}`));
                });
                console.log();
            }
            // Show code examples if available
            if (module.codeExamples && Object.keys(module.codeExamples).length > 0) {
                console.log(chalk.white('📝 Code Examples:'));
                if (module.codeExamples.curl) {
                    console.log(chalk.cyan('\n  cURL:'));
                    console.log(chalk.gray('  ' + module.codeExamples.curl.split('\n').join('\n  ')));
                }
                if (module.codeExamples.node) {
                    console.log(chalk.cyan('\n  Node.js:'));
                    console.log(chalk.gray('  ' + module.codeExamples.node.split('\n').join('\n  ')));
                }
            }
            console.log();
            console.log(chalk.gray(`Documentation: ${module.documentation}`));
            if (module.external) {
                console.log(chalk.gray(`External URL: ${module.external}`));
            }
            console.log();
            console.log(chalk.cyan('To activate: ') + chalk.white(`vigthoria hub activate ${moduleId}`));
            console.log();
        }
        catch (error) {
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`Error: ${errMsg}`));
            console.log(chalk.gray('\nAvailable modules: pay, meet, llm, music, voice, images'));
        }
    }
    /**
     * Interactive discover mode - prompts user with suggestions
     */
    async discover() {
        console.log(chalk.cyan('\n🚀 Vigthoria Module Discovery\n'));
        console.log(chalk.white('What are you building? Describe your project:\n'));
        // Show common use cases
        console.log(chalk.gray('Examples of what you can build:'));
        console.log(chalk.gray('  • "I need background music for my app"'));
        console.log(chalk.gray('  • "voice narration for videos"'));
        console.log(chalk.gray('  • "AI chatbot for customer support"'));
        console.log(chalk.gray('  • "payment processing for my SaaS"'));
        console.log(chalk.gray('  • "image generation for social media"\n'));
        console.log(chalk.cyan('Use: vigthoria hub search "<your use case>"'));
        console.log(chalk.gray('The AI will find the best modules for your needs.\n'));
        // Show pricing tiers
        console.log(chalk.white('💳 Subscription Tiers:'));
        console.log(chalk.gray('  Starter    €49/mo   50 credits'));
        console.log(chalk.gray('  Business   €199/mo  500 credits'));
        console.log(chalk.gray('  Enterprise €499/mo  2000 credits'));
        console.log();
        console.log(chalk.cyan('Get started: https://landing.vigthoria.io/api-keys.html\n'));
    }
}
