/**
 * Vigthoria CLI - Deploy Commands
 *
 * Deploy and host projects on Vigthoria infrastructure
 *
 * Usage:
 *   vig deploy                    - Interactive deploy wizard
 *   vig deploy --subdomain <name> - Deploy to name.vigthoria.io
 *   vig deploy --domain <domain>  - Deploy to custom domain
 *   vig deploy status             - Show deployment status
 *   vig deploy list               - List all deployments
 *   vig deploy remove <domain>    - Remove a deployment
 */
import chalk from 'chalk';
import * as fs from 'fs';
import * as path from 'path';
import { createSpinner, CH } from '../utils/logger.js';
import inquirer from 'inquirer';
export class DeployCommand {
    config;
    logger;
    apiBase;
    constructor(config, logger) {
        this.config = config;
        this.logger = logger;
        this.apiBase = this.config.get('apiUrl') || 'https://coder.vigthoria.io';
    }
    getAuthHeaders() {
        const token = this.config.get('authToken');
        return {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };
    }
    isAuthenticated() {
        return !!this.config.get('authToken');
    }
    requireAuth() {
        if (!this.isAuthenticated()) {
            console.log(chalk.red('\n❌ Authentication required'));
            console.log(chalk.gray('   Run `vig login` to authenticate first.\n'));
            process.exit(1);
        }
    }
    /**
     * Interactive deploy wizard
     */
    async deploy(options = {}) {
        this.requireAuth();
        console.log(chalk.cyan('\n🚀 Vigthoria Deploy - Host Your Project\n'));
        // If subdomain or domain specified, deploy directly
        if (options.subdomain) {
            await this.deployToSubdomain(options.subdomain, options.project);
            return;
        }
        if (options.domain) {
            await this.deployToCustomDomain(options.domain, options.project);
            return;
        }
        // Interactive wizard
        const { deployType } = await inquirer.prompt([{
                type: 'list',
                name: 'deployType',
                message: 'How would you like to deploy?',
                choices: [
                    { name: '🆓 Preview URL (Free) - coder.vigthoria.io/preview/...', value: 'preview' },
                    { name: '🌐 Vigthoria Subdomain (€4.99/mo) - yourapp.vigthoria.io', value: 'subdomain' },
                    { name: '🔗 Custom Domain (€9.99/mo) - yourdomain.com', value: 'custom' },
                    { name: '📊 View Hosting Plans', value: 'plans' }
                ]
            }]);
        switch (deployType) {
            case 'preview':
                await this.deployToPreview(options.project);
                break;
            case 'subdomain':
                await this.promptSubdomainDeploy(options.project);
                break;
            case 'custom':
                await this.promptCustomDomainDeploy(options.project);
                break;
            case 'plans':
                await this.showPlans();
                break;
        }
    }
    /**
     * Deploy to preview URL (free)
     */
    async deployToPreview(projectPath) {
        this.requireAuth();
        const spinner = createSpinner('Deploying to preview...').start();
        try {
            const projectDir = projectPath || process.cwd();
            const projectInfo = this.detectProjectInfo(projectDir);
            const response = await fetch(`${this.apiBase}/api/hosting/deploy/preview`, {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({
                    projectName: projectInfo.name,
                    projectPath: projectDir
                })
            });
            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to deploy');
            }
            const data = await response.json();
            spinner.succeed(chalk.green('Deployed to preview!'));
            console.log(chalk.cyan('\n🔗 Preview URL:'));
            console.log(chalk.white(`   ${data.url}`));
            console.log(chalk.gray('\n   Note: Preview URLs may expire after 7 days of inactivity.'));
            console.log(chalk.gray('   Upgrade to a subdomain for permanent hosting.\n'));
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Deploy failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
            process.exitCode = 1;
        }
    }
    /**
     * Deploy to Vigthoria subdomain
     */
    async deployToSubdomain(subdomain, projectPath) {
        const spinner = createSpinner(`Deploying to ${subdomain}.vigthoria.io...`).start();
        try {
            // Validate subdomain format
            if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(subdomain) || subdomain.length < 3) {
                throw new Error('Subdomain must be 3+ chars, lowercase alphanumeric with hyphens');
            }
            const projectDir = projectPath || process.cwd();
            const projectInfo = this.detectProjectInfo(projectDir);
            const response = await fetch(`${this.apiBase}/api/hosting/deploy/subdomain`, {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({
                    subdomain,
                    projectName: projectInfo.name,
                    projectPath: projectDir
                })
            });
            const data = await response.json();
            if (!response.ok || !data.success) {
                if (data.requiresSubscription) {
                    spinner.stop();
                    console.log(chalk.yellow(`\n${CH.warnEmoji}  Subdomain hosting requires a subscription (€4.99/mo)`));
                    const { proceed } = await inquirer.prompt([{
                            type: 'confirm',
                            name: 'proceed',
                            message: 'Would you like to subscribe now?',
                            default: true
                        }]);
                    if (proceed && data.checkoutUrl) {
                        console.log(chalk.cyan(`\n🔗 Opening checkout: ${data.checkoutUrl}`));
                        console.log(chalk.gray('Please open this URL in your browser to subscribe.\n'));
                    }
                    return;
                }
                throw new Error(data.error || 'Failed to deploy');
            }
            spinner.succeed(chalk.green(`Deployed to ${subdomain}.vigthoria.io!`));
            console.log(chalk.cyan('\n🌐 Your Site is Live:'));
            console.log(chalk.bold.white(`   https://${subdomain}.vigthoria.io`));
            console.log(chalk.gray('\n   ✓ SSL certificate auto-configured'));
            console.log(chalk.gray('   ✓ Global CDN enabled'));
            console.log(chalk.gray('   ✓ Unlimited traffic included\n'));
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Deploy failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Deploy to custom domain
     */
    async deployToCustomDomain(domain, projectPath) {
        const spinner = createSpinner(`Setting up ${domain}...`).start();
        try {
            const projectDir = projectPath || process.cwd();
            const projectInfo = this.detectProjectInfo(projectDir);
            const response = await fetch(`${this.apiBase}/api/hosting/deploy/custom`, {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({
                    domain,
                    projectName: projectInfo.name,
                    projectPath: projectDir
                })
            });
            const data = await response.json();
            if (!response.ok || !data.success) {
                if (data.requiresSubscription) {
                    spinner.stop();
                    console.log(chalk.yellow(`\n${CH.warnEmoji}  Custom domain hosting requires a subscription (€9.99/mo)`));
                    const { proceed } = await inquirer.prompt([{
                            type: 'confirm',
                            name: 'proceed',
                            message: 'Would you like to subscribe now?',
                            default: true
                        }]);
                    if (proceed && data.checkoutUrl) {
                        console.log(chalk.cyan(`\n🔗 Checkout URL: ${data.checkoutUrl}`));
                        console.log(chalk.gray('Please open this URL in your browser to subscribe.\n'));
                    }
                    return;
                }
                throw new Error(data.error || 'Failed to deploy');
            }
            spinner.succeed(chalk.green('Domain registered!'));
            if (data.dnsRecords) {
                console.log(chalk.cyan('\n📝 Configure your DNS records:'));
                console.log(chalk.gray('─'.repeat(60)));
                for (const record of data.dnsRecords) {
                    console.log(chalk.white(`   Type: ${record.type.padEnd(6)} Name: ${record.name.padEnd(20)} Value: ${record.value}`));
                }
                console.log(chalk.gray('─'.repeat(60)));
                console.log(chalk.yellow('\n⏳ After adding DNS records, run:'));
                console.log(chalk.white(`   vig deploy verify ${domain}\n`));
            }
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Deploy failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Interactive subdomain prompt
     */
    async promptSubdomainDeploy(projectPath) {
        const { subdomain } = await inquirer.prompt([{
                type: 'input',
                name: 'subdomain',
                message: 'Enter your desired subdomain:',
                suffix: chalk.gray('.vigthoria.io'),
                validate: (input) => {
                    if (!/^[a-z0-9][a-z0-9-]*[a-z0-9]$/.test(input) || input.length < 3) {
                        return 'Subdomain must be 3+ chars, lowercase alphanumeric with hyphens';
                    }
                    return true;
                }
            }]);
        await this.deployToSubdomain(subdomain, projectPath);
    }
    /**
     * Interactive custom domain prompt
     */
    async promptCustomDomainDeploy(projectPath) {
        const { domain } = await inquirer.prompt([{
                type: 'input',
                name: 'domain',
                message: 'Enter your domain:',
                suffix: chalk.gray(' (e.g., myapp.com)'),
                validate: (input) => {
                    if (!/^[a-z0-9][a-z0-9.-]+\.[a-z]{2,}$/i.test(input)) {
                        return 'Please enter a valid domain name';
                    }
                    return true;
                }
            }]);
        await this.deployToCustomDomain(domain, projectPath);
    }
    /**
     * Show hosting plans
     */
    async showPlans() {
        const spinner = createSpinner('Fetching hosting plans...').start();
        try {
            const response = await fetch(`${this.apiBase}/api/hosting/plans`, {
                headers: this.getAuthHeaders()
            });
            if (!response.ok) {
                throw new Error('Failed to fetch plans');
            }
            const data = await response.json();
            spinner.stop();
            console.log(chalk.cyan('\n📊 Vigthoria Hosting Plans\n'));
            console.log(chalk.gray('═'.repeat(70)));
            for (const plan of data.plans) {
                const price = plan.price_monthly === 0
                    ? chalk.green('FREE')
                    : chalk.yellow(`€${plan.price_monthly.toFixed(2)}/mo`);
                console.log(chalk.bold.white(`\n  ${plan.display_name} - ${price}`));
                console.log(chalk.gray('  ' + '─'.repeat(50)));
                const features = [];
                if (plan.subdomain_allowed)
                    features.push('✓ Vigthoria subdomain');
                if (plan.custom_domain_allowed)
                    features.push('✓ Custom domain');
                features.push(`✓ ${plan.max_projects === -1 ? 'Unlimited' : plan.max_projects} project(s)`);
                features.push(`✓ ${plan.storage_mb >= 1024 ? (plan.storage_mb / 1024) + 'GB' : plan.storage_mb + 'MB'} storage`);
                features.forEach(f => console.log(chalk.gray(`    ${f}`)));
            }
            console.log(chalk.gray('\n' + '═'.repeat(70)));
            console.log(chalk.cyan('\n  Subscribe: vig deploy --subdomain myapp\n'));
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Failed to fetch plans');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * List all deployments
     */
    async list() {
        this.requireAuth();
        const spinner = createSpinner('Fetching deployments...').start();
        try {
            const response = await fetch(`${this.apiBase}/api/hosting/domains`, {
                headers: this.getAuthHeaders()
            });
            if (!response.ok) {
                throw new Error('Failed to fetch deployments');
            }
            const data = await response.json();
            spinner.stop();
            if (data.domains.length === 0) {
                console.log(chalk.yellow('\n📦 No deployments yet.\n'));
                console.log(chalk.gray('   Run `vig deploy` to deploy your first project.\n'));
                return;
            }
            console.log(chalk.cyan(`\n🌐 Your Deployments (${data.domains.length})\n`));
            for (const domain of data.domains) {
                const statusIcon = domain.is_active ? '🟢' : '🔴';
                const sslIcon = domain.ssl_status === 'active' ? CH.lock : CH.warnEmoji;
                const url = domain.domain_type === 'subdomain'
                    ? `${domain.subdomain}.vigthoria.io`
                    : domain.domain_type === 'custom'
                        ? domain.custom_domain
                        : domain.url;
                console.log(chalk.white(`  ${statusIcon} ${url}`));
                console.log(chalk.gray(`     Project: ${domain.project_name} | SSL: ${sslIcon} ${domain.ssl_status} | Tier: ${domain.hosting_tier}`));
                console.log();
            }
        }
        catch (error) {
            spinner.stop();
            this.logger.error('List failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Check deployment status
     */
    async status(domain) {
        this.requireAuth();
        const spinner = createSpinner('Checking status...').start();
        try {
            const endpoint = domain
                ? `${this.apiBase}/api/hosting/domain/${encodeURIComponent(domain)}/status`
                : `${this.apiBase}/api/hosting/status`;
            const response = await fetch(endpoint, {
                headers: this.getAuthHeaders()
            });
            if (!response.ok) {
                throw new Error('Failed to fetch status');
            }
            const data = await response.json();
            spinner.stop();
            console.log(chalk.cyan('\n📊 Deployment Status\n'));
            console.log(JSON.stringify(data, null, 2));
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Status check failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Verify DNS for custom domain
     */
    async verify(domain) {
        this.requireAuth();
        const spinner = createSpinner(`Verifying DNS for ${domain}...`).start();
        try {
            const response = await fetch(`${this.apiBase}/api/hosting/domain/verify`, {
                method: 'POST',
                headers: this.getAuthHeaders(),
                body: JSON.stringify({ domain })
            });
            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error(data.error || 'Verification failed');
            }
            if (data.verified) {
                spinner.succeed(chalk.green('Domain verified!'));
                console.log(chalk.cyan(`\n🎉 Your site is now live at: https://${domain}`));
                console.log(chalk.gray(`   SSL Status: ${data.sslStatus || 'Provisioning...'}\n`));
            }
            else {
                spinner.warn(chalk.yellow('DNS not propagated yet'));
                console.log(chalk.gray('\n   DNS changes can take up to 48 hours to propagate.'));
                console.log(chalk.gray('   Try again later with: vig deploy verify ' + domain + '\n'));
            }
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Verification failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Remove a deployment
     */
    async remove(domain) {
        this.requireAuth();
        const { confirm } = await inquirer.prompt([{
                type: 'confirm',
                name: 'confirm',
                message: chalk.red(`Are you sure you want to remove ${domain}?`),
                default: false
            }]);
        if (!confirm) {
            console.log(chalk.yellow(`\n${CH.warnEmoji} Removal cancelled.\n`));
            return;
        }
        const spinner = createSpinner(`Removing ${domain}...`).start();
        try {
            const response = await fetch(`${this.apiBase}/api/hosting/domain/${encodeURIComponent(domain)}`, {
                method: 'DELETE',
                headers: this.getAuthHeaders()
            });
            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to remove');
            }
            spinner.succeed(chalk.green('Domain removed'));
            console.log(chalk.gray('\n   Your project files are still in your repository.\n'));
        }
        catch (error) {
            spinner.stop();
            this.logger.error('Remove failed');
            const errMsg = error instanceof Error ? error.message : 'Unknown error';
            console.log(chalk.red(`\n❌ Error: ${errMsg}\n`));
        }
    }
    /**
     * Detect project info from directory
     */
    detectProjectInfo(projectPath) {
        const packageJsonPath = path.join(projectPath, 'package.json');
        let name = path.basename(projectPath);
        const techStack = [];
        if (fs.existsSync(packageJsonPath)) {
            try {
                const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
                name = pkg.name || name;
                const deps = { ...pkg.dependencies, ...pkg.devDependencies };
                if (deps.react)
                    techStack.push('React');
                if (deps.vue)
                    techStack.push('Vue');
                if (deps.next)
                    techStack.push('Next.js');
                if (deps.express)
                    techStack.push('Express');
                if (deps.typescript)
                    techStack.push('TypeScript');
            }
            catch (e) {
                // Ignore parse errors
            }
        }
        // Check for other frameworks
        if (fs.existsSync(path.join(projectPath, 'requirements.txt'))) {
            techStack.push('Python');
        }
        if (fs.existsSync(path.join(projectPath, 'index.html'))) {
            techStack.push('Static HTML');
        }
        return { name, techStack };
    }
}
