/**
 * Deploy command - Deploy to hardware (Mac Mini/Mac Studio)
 */

import { Command } from 'commander'
import * as fs from 'fs'
import * as path from 'path'

interface DeployOptions {
  target?: string
  config?: string
  dryRun?: boolean
}

export const deployCommand = new Command('deploy')
  .description('Deploy compliance services to hardware')
  .option('-t, --target <target>', 'Deployment target (mac-mini, mac-studio, cloud)', 'mac-mini')
  .option('-c, --config <path>', 'Path to config file', './breakpilot.config.json')
  .option('--dry-run', 'Show what would be deployed without actually deploying', false)
  .action(async (options: DeployOptions) => {
    const chalk = (await import('chalk')).default
    const ora = (await import('ora')).default
    const inquirer = (await import('inquirer')).default

    console.log(chalk.bold.blue('\n🚀 BreakPilot Compliance SDK - Deployment\n'))

    // Check for config file
    const configPath = path.resolve(options.config || './breakpilot.config.json')
    if (!fs.existsSync(configPath)) {
      console.log(chalk.yellow('⚠️  No config file found. Run `breakpilot init` first.'))
      process.exit(1)
    }

    const config = JSON.parse(fs.readFileSync(configPath, 'utf-8'))

    // Prompt for deployment details
    const answers = await inquirer.prompt([
      {
        type: 'list',
        name: 'target',
        message: 'Select deployment target:',
        choices: [
          { name: 'Mac Mini M4 Pro (64GB RAM, Qwen 2.5 32B)', value: 'mac-mini' },
          { name: 'Mac Studio M2 Ultra (512GB RAM, Qwen 2.5 40B)', value: 'mac-studio' },
          { name: 'Cloud (BreakPilot Servers)', value: 'cloud' },
        ],
        default: options.target,
      },
      {
        type: 'input',
        name: 'hostname',
        message: 'Target hostname/IP:',
        when: (answers) => answers.target !== 'cloud',
        default: 'localhost',
      },
      {
        type: 'input',
        name: 'sshUser',
        message: 'SSH username:',
        when: (answers) => answers.target !== 'cloud',
        default: process.env.USER || 'admin',
      },
      {
        type: 'confirm',
        name: 'installLLM',
        message: 'Install/update LLM model?',
        when: (answers) => answers.target !== 'cloud',
        default: true,
      },
    ])

    if (options.dryRun) {
      console.log(chalk.yellow('\n📋 Dry run - no changes will be made\n'))
    }

    const spinner = ora('Preparing deployment...').start()

    try {
      // Generate docker-compose.yml
      const dockerCompose = generateDockerCompose(answers.target, config)

      if (options.dryRun) {
        spinner.info('Would generate docker-compose.yml:')
        console.log(chalk.gray(dockerCompose))
        return
      }

      // For actual deployment, we'd:
      // 1. SSH to target machine
      // 2. Copy docker-compose.yml
      // 3. Run docker-compose up -d
      // 4. Install LLM if requested

      spinner.text = 'Connecting to target...'
      await sleep(1000) // Simulated

      spinner.text = 'Deploying services...'
      await sleep(2000) // Simulated

      if (answers.installLLM) {
        spinner.text = 'Installing LLM model (this may take a while)...'
        await sleep(2000) // Simulated
      }

      spinner.succeed('Deployment complete!')

      console.log(chalk.green('\n✅ Services deployed successfully'))
      console.log(chalk.gray('\nDeployed services:'))
      console.log(chalk.gray('  - API Gateway (port 443)'))
      console.log(chalk.gray('  - Compliance Engine'))
      console.log(chalk.gray('  - RAG Service'))
      console.log(chalk.gray('  - Security Scanner'))
      console.log(chalk.gray('  - PostgreSQL'))
      console.log(chalk.gray('  - Qdrant'))
      console.log(chalk.gray('  - MinIO'))
      if (answers.installLLM) {
        const model = answers.target === 'mac-studio' ? 'qwen2.5:40b' : 'qwen2.5:32b'
        console.log(chalk.gray(`  - Ollama (${model})`))
      }

      console.log(chalk.blue('\n🔗 Access your services at:'))
      console.log(chalk.white(`   https://${answers.hostname || 'localhost'}/api/v1`))
    } catch (error) {
      spinner.fail('Deployment failed')
      console.error(chalk.red('Error:'), error)
      process.exit(1)
    }
  })

function generateDockerCompose(target: string, config: Record<string, unknown>): string {
  const llmModel = target === 'mac-studio' ? 'qwen2.5:40b' : 'qwen2.5:32b'

  return `# Generated by BreakPilot CLI
# Target: ${target}

version: '3.8'

services:
  api-gateway:
    image: ghcr.io/breakpilot/compliance-sdk-gateway:latest
    ports:
      - "443:443"
      - "80:80"
    environment:
      - DATABASE_URL=postgres://breakpilot:breakpilot@postgres:5432/compliance
      - QDRANT_URL=http://qdrant:6333
      - OLLAMA_URL=http://host.docker.internal:11434
      - MINIO_URL=http://minio:9000
    depends_on:
      - postgres
      - qdrant
      - minio
    restart: unless-stopped

  compliance-engine:
    image: ghcr.io/breakpilot/compliance-engine:latest
    environment:
      - DATABASE_URL=postgres://breakpilot:breakpilot@postgres:5432/compliance
    depends_on:
      - postgres
    restart: unless-stopped

  rag-service:
    image: ghcr.io/breakpilot/rag-service:latest
    environment:
      - QDRANT_URL=http://qdrant:6333
      - OLLAMA_URL=http://host.docker.internal:11434
      - EMBEDDING_MODEL=bge-m3
    depends_on:
      - qdrant
    restart: unless-stopped

  security-scanner:
    image: ghcr.io/breakpilot/security-scanner:latest
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    restart: unless-stopped

  postgres:
    image: postgres:16-alpine
    environment:
      - POSTGRES_USER=breakpilot
      - POSTGRES_PASSWORD=breakpilot
      - POSTGRES_DB=compliance
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

  qdrant:
    image: qdrant/qdrant:v1.12.1
    volumes:
      - qdrant_data:/qdrant/storage
    restart: unless-stopped

  minio:
    image: minio/minio:latest
    command: server /data --console-address ":9001"
    environment:
      - MINIO_ROOT_USER=breakpilot
      - MINIO_ROOT_PASSWORD=breakpilot123
    volumes:
      - minio_data:/data
    restart: unless-stopped

volumes:
  postgres_data:
  qdrant_data:
  minio_data:

# Note: Ollama runs on the host system
# Install with: ollama pull ${llmModel}
`
}

function sleep(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms))
}
