/**
 * MORPH-SPEC Cost Command
 * CLI wrapper for cost calculation operations
 */

import ora from 'ora';
import chalk from 'chalk';
import { logger } from '../utils/logger.js';
import * as CostCalculator from '../lib/cost-calculator.js';

// ============================================================================
// Command Function
// ============================================================================

/**
 * Calculate Azure infrastructure costs from Bicep files
 * @param {string} bicepFiles - File path or glob pattern
 * @param {Object} options - CLI options
 */
export async function costCommand(bicepFiles, options) {
  if (!bicepFiles) {
    logger.error('Bicep file path required');
    logger.dim('  Usage: morph-spec cost <bicep-files>');
    logger.blank();
    logger.dim('  Examples:');
    logger.dim('    morph-spec cost infra/main.bicep');
    logger.dim('    morph-spec cost "infra/**/*.bicep"');
    process.exit(1);
  }

  logger.header('MORPH-SPEC Cost Calculator');
  logger.blank();

  const spinner = ora('Parsing Bicep files...').start();

  try {
    // Calculate costs
    const result = CostCalculator.calculateBicepCost(bicepFiles, {
      configPath: options.config
    });

    spinner.succeed(`Found ${result.breakdown.length} resources`);
    logger.blank();

    // JSON output
    if (options.json) {
      console.log(JSON.stringify(result, null, 2));
      return;
    }

    // Verbose output (table format)
    if (options.verbose) {
      displayVerbose(result);
    } else {
      displaySummary(result);
    }

    // Exit code based on cost thresholds
    if (result.requiresADR && options.strict) {
      logger.blank();
      logger.error('Cost exceeds ADR threshold!');
      logger.dim('  Add ADR in decisions.md or use --no-strict');
      process.exit(1);
    }

  } catch (error) {
    spinner.fail('Cost calculation failed');
    logger.error(error.message);
    process.exit(1);
  }
}

// ============================================================================
// Display Functions
// ============================================================================

/**
 * Display summary (default output)
 */
function displaySummary(result) {
  logger.header('Cost Summary');
  logger.blank();

  // Total cost
  const costColor = result.requiresADR ? 'red' : result.requiresApproval ? 'yellow' : 'green';
  logger.info(`Monthly Cost: ${chalk[costColor](`$${result.monthly.toFixed(2)}`)}`);
  logger.dim(`  Currency: ${result.currency}`);
  logger.dim(`  Region: ${result.region}`);
  logger.blank();

  // Status
  if (result.isFreeTier) {
    logger.success('✓ All resources use free tier');
  } else {
    if (result.requiresADR) {
      logger.warn('⚠️  Requires ADR in decisions.md (cost > $' + result.limits.requiresADR + ')');
    } else if (result.requiresApproval) {
      logger.warn('⚠️  Requires approval (cost > $' + result.limits.freeTierOnly + ')');
    } else {
      logger.success('✓ Within free tier limits');
    }
  }
  logger.blank();

  // Top 3 expensive resources
  if (result.breakdown.length > 0) {
    logger.header('Top Resources:');
    const sorted = [...result.breakdown].sort((a, b) => b.cost - a.cost);
    sorted.slice(0, 3).forEach(item => {
      const costStr = chalk.cyan(`$${item.cost.toFixed(2)}/mo`);
      logger.dim(`  - ${item.name} (${item.sku}): ${costStr}`);
    });
    logger.blank();
  }

  // Warnings
  if (result.warnings.length > 0) {
    logger.header('Warnings:');
    result.warnings.forEach(warning => {
      logger.warn(`  ${warning}`);
    });
    logger.blank();
  }

  // Next steps
  if (result.requiresADR) {
    logger.header('Next Steps:');
    logger.dim('  1. Document cost justification in decisions.md');
    logger.dim('  2. Include ADR with cost breakdown');
    logger.dim('  3. Get approval before deploying');
    logger.blank();
  }
}

/**
 * Display verbose (table format)
 */
function displayVerbose(result) {
  logger.blank();
  console.log('╔════════════════════════════════════════════════════════════════╗');
  console.log('║                 MORPH-SPEC COST CALCULATOR                     ║');
  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log(`║ Region: ${result.region.padEnd(54)}║`);
  console.log(`║ Currency: ${result.currency.padEnd(52)}║`);
  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log('║ RESOURCES                                                      ║');
  console.log('╠════════════════════════════════════════════════════════════════╣');

  for (const item of result.breakdown) {
    const costStr = `$${item.cost.toFixed(2)}/mo`;
    const nameStr = `${item.name} (${item.sku})`;
    console.log(`║ ${nameStr.substring(0, 40).padEnd(40)} ${costStr.padStart(20)}║`);
  }

  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log('║ SUMMARY                                                        ║');
  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log(`║ Total Monthly Cost: $${result.monthly.toFixed(2).padStart(42)}║`);
  console.log(`║ Requires Approval: ${(result.requiresApproval ? 'YES' : 'NO').padStart(43)}║`);
  console.log(`║ Requires ADR: ${(result.requiresADR ? 'YES' : 'NO').padStart(48)}║`);

  if (result.warnings.length > 0) {
    console.log('╠════════════════════════════════════════════════════════════════╣');
    console.log('║ WARNINGS                                                       ║');
    console.log('╠════════════════════════════════════════════════════════════════╣');
    for (const warning of result.warnings) {
      const chunks = warning.match(/.{1,62}/g) || [warning];
      chunks.forEach(chunk => {
        console.log(`║ ${chunk.padEnd(62)}║`);
      });
    }
  }

  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log('║ LIMITS (from config)                                           ║');
  console.log('╠════════════════════════════════════════════════════════════════╣');
  console.log(`║ Free Tier Only: $${result.limits.freeTierOnly.toFixed(2).padStart(44)}║`);
  console.log(`║ With Approval: $${result.limits.withApproval.toFixed(2).padStart(45)}║`);
  console.log(`║ Requires ADR: $${result.limits.requiresADR.toFixed(2).padStart(46)}║`);
  console.log('╚════════════════════════════════════════════════════════════════╝\n');
}
