#!/usr/bin/env node

import { Command } from 'commander';
import { Configurator } from '../dist/configurator.js';
import { IDEDetector } from '../dist/ide-detector.js';
import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import { promises as fs } from 'fs';
import path from 'path';

const program = new Command();

program
  .name('ai-sprint-setup')
  .description('Auto-configure AI Sprint for your IDE')
  .version('1.0.0')
  .option('-p, --project-id <id>', 'Project ID (will be generated if not provided)')
  .option('-e, --endpoint <url>', 'API endpoint URL', 'https://portal.unblockd.com')
  .option('-k, --api-key <key>', 'API key for authentication')
  .option('--no-interactive', 'Run in non-interactive mode')
  .option('--project-path <path>', 'Project path (defaults to current directory)')
  .parse(process.argv);

const options = program.opts();

async function main() {
  console.log(chalk.bold.blue('\n🚀 AI Sprint Setup\n'));

  const configurator = new Configurator(options.projectPath);
  const detector = new IDEDetector(options.projectPath);

  // Check if already configured
  const configPath = path.join(process.cwd(), '.ai-sprint.json');
  let existingConfig = null;
  try {
    existingConfig = JSON.parse(await fs.readFile(configPath, 'utf-8'));
  } catch {
    // No existing config
  }

  if (existingConfig && options.interactive !== false) {
    const { reconfigure } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'reconfigure',
        message: 'AI Sprint is already configured. Do you want to reconfigure?',
        default: false
      }
    ]);

    if (!reconfigure) {
      console.log(chalk.yellow('\n⏹️  Setup cancelled.'));
      process.exit(0);
    }
  }

  // Detect IDEs
  const spinner = ora('Detecting IDE environment...').start();
  const detectedIDEs = await detector.detectAll();
  spinner.stop();

  if (detectedIDEs.length === 0) {
    console.log(chalk.yellow('⚠️  No supported IDE detected. Using generic configuration.'));
  } else {
    console.log(chalk.green(`✅ Detected: ${detectedIDEs.map(ide => ide.name).join(', ')}`));
  }

  // Gather configuration
  let setupOptions = {
    projectId: options.projectId || existingConfig?.projectId,
    apiEndpoint: options.endpoint,
    apiKey: options.apiKey,
    projectPath: options.projectPath || process.cwd()
  };

  if (options.interactive !== false && !setupOptions.projectId) {
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'projectName',
        message: 'What is your project name?',
        default: path.basename(process.cwd())
      },
      {
        type: 'confirm',
        name: 'hasPortalAccount',
        message: 'Do you have a BizOps Portal account?',
        default: false
      }
    ]);

    if (answers.hasPortalAccount) {
      const portalAnswers = await inquirer.prompt([
        {
          type: 'input',
          name: 'projectId',
          message: 'Enter your BizOps Portal project ID:',
          when: !setupOptions.projectId
        },
        {
          type: 'input',
          name: 'apiEndpoint',
          message: 'Portal API endpoint:',
          default: setupOptions.apiEndpoint
        },
        {
          type: 'password',
          name: 'apiKey',
          message: 'API key (optional, press enter to skip):',
          when: !setupOptions.apiKey
        }
      ]);

      setupOptions = { ...setupOptions, ...portalAnswers };
    }
  }

  // Run setup
  console.log(chalk.blue('\n📦 Configuring AI Sprint...\n'));
  
  try {
    await configurator.setup(setupOptions);
    
    console.log(chalk.bold.green('\n✨ Setup complete!\n'));
    
    // Show IDE-specific instructions
    if (detectedIDEs.some(ide => ide.type === 'claude')) {
      console.log(chalk.cyan('📌 Claude Code Instructions:'));
      console.log('   • Restart Claude Code to load the configuration');
      console.log('   • Use commands: /session-start, /session-update, /sprint-create');
      console.log('   • Or use MCP tools directly\n');
    }
    
    if (detectedIDEs.some(ide => ide.type === 'cursor')) {
      console.log(chalk.cyan('📌 Cursor Instructions:'));
      console.log('   • Restart Cursor to load the configuration');
      console.log('   • The SDLC tracker tools are now available\n');
    }
    
    if (detectedIDEs.some(ide => ide.type === 'vscode')) {
      console.log(chalk.cyan('📌 VS Code Instructions:'));
      console.log('   • Reload VS Code window');
      console.log('   • Install MCP extension if not already installed\n');
    }

    console.log(chalk.gray('For more information: https://github.com/unblockd/ai-sprint'));
    
  } catch (error) {
    console.error(chalk.red('\n❌ Setup failed:'), error);
    process.exit(1);
  }
}

// Handle errors
process.on('unhandledRejection', (error) => {
  console.error(chalk.red('\n❌ Unexpected error:'), error);
  process.exit(1);
});

// Run main function
main().catch((error) => {
  console.error(chalk.red('\n❌ Setup error:'), error);
  process.exit(1);
});