/**
 * Init command - Initialize a new compliance project
 */

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

interface InitOptions {
  template?: string
  force?: boolean
}

export const initCommand = new Command('init')
  .description('Initialize a new compliance project')
  .argument('[directory]', 'Directory to initialize', '.')
  .option('-t, --template <template>', 'Project template (react, vue, vanilla)', 'react')
  .option('-f, --force', 'Overwrite existing files', false)
  .action(async (directory: string, options: InitOptions) => {
    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 - Project Setup\n'))

    // Prompt for configuration
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'projectName',
        message: 'Project name:',
        default: path.basename(path.resolve(directory)),
      },
      {
        type: 'list',
        name: 'template',
        message: 'Select a template:',
        choices: [
          { name: 'React (Recommended)', value: 'react' },
          { name: 'Vue 3', value: 'vue' },
          { name: 'Vanilla JS', value: 'vanilla' },
        ],
        default: options.template,
      },
      {
        type: 'input',
        name: 'apiEndpoint',
        message: 'API Endpoint:',
        default: 'https://compliance.breakpilot.app/api/v1',
      },
      {
        type: 'confirm',
        name: 'includeComponents',
        message: 'Include pre-built UI components?',
        default: true,
      },
    ])

    const spinner = ora('Setting up project...').start()

    try {
      const targetDir = path.resolve(directory)

      // Create directory if it doesn't exist
      if (!fs.existsSync(targetDir)) {
        fs.mkdirSync(targetDir, { recursive: true })
      }

      // Create config file
      const configPath = path.join(targetDir, 'breakpilot.config.json')
      const config = {
        projectName: answers.projectName,
        template: answers.template,
        apiEndpoint: answers.apiEndpoint,
        version: '0.0.1',
        features: {
          dsgvo: true,
          compliance: true,
          rag: true,
          security: true,
        },
      }

      fs.writeFileSync(configPath, JSON.stringify(config, null, 2))

      // Create .env.example
      const envExamplePath = path.join(targetDir, '.env.example')
      const envContent = `# BreakPilot Compliance SDK Configuration
BREAKPILOT_API_ENDPOINT=${answers.apiEndpoint}
BREAKPILOT_API_KEY=pk_live_xxx
BREAKPILOT_TENANT_ID=your_tenant_id
`
      fs.writeFileSync(envExamplePath, envContent)

      // Create example usage file based on template
      const examplePath = path.join(targetDir, `compliance-example.${getExtension(answers.template)}`)
      fs.writeFileSync(examplePath, getExampleCode(answers.template, answers.apiEndpoint))

      spinner.succeed('Project initialized successfully!')

      console.log(chalk.green('\n✅ Project created at:'), chalk.white(targetDir))
      console.log(chalk.gray('\nNext steps:'))
      console.log(chalk.gray('  1. Copy .env.example to .env and fill in your API key'))
      console.log(chalk.gray(`  2. Install the SDK: npm install @breakpilot/compliance-sdk-${answers.template}`))
      console.log(chalk.gray('  3. Import and use the SDK in your application'))
      console.log(chalk.gray('\nDocumentation: https://docs.breakpilot.app/sdk'))
    } catch (error) {
      spinner.fail('Failed to initialize project')
      console.error(chalk.red('Error:'), error)
      process.exit(1)
    }
  })

function getExtension(template: string): string {
  switch (template) {
    case 'react':
      return 'tsx'
    case 'vue':
      return 'vue'
    default:
      return 'js'
  }
}

function getExampleCode(template: string, apiEndpoint: string): string {
  switch (template) {
    case 'react':
      return `// Example React integration
import {
  ComplianceProvider,
  ConsentBanner,
  DSRPortal,
  useCompliance
} from '@breakpilot/compliance-sdk-react';

function App() {
  return (
    <ComplianceProvider
      apiEndpoint="${apiEndpoint}"
      apiKey={process.env.BREAKPILOT_API_KEY}
      tenantId={process.env.BREAKPILOT_TENANT_ID}
    >
      <ConsentBanner position="BOTTOM" theme="LIGHT" />
      <MyApp />
    </ComplianceProvider>
  );
}

function MyApp() {
  const { state, compliance, rag } = useCompliance();

  const askQuestion = async () => {
    const answer = await rag.ask('Was ist bei Art. 9 DSGVO zu beachten?');
    console.log(answer);
  };

  return (
    <div>
      <h1>Compliance Score: {compliance.calculateComplianceScore().overall}%</h1>
      <button onClick={askQuestion}>Frage stellen</button>
    </div>
  );
}

export default App;
`
    case 'vue':
      return `<!-- Example Vue 3 integration -->
<script setup lang="ts">
import { useCompliance, useRAG } from '@breakpilot/compliance-sdk-vue';

const { state, complianceScore } = useCompliance();
const { ask, chatHistory, isLoading } = useRAG();

const askQuestion = async () => {
  await ask('Was ist bei Art. 9 DSGVO zu beachten?');
};
</script>

<template>
  <div>
    <h1>Compliance Score: {{ complianceScore }}%</h1>
    <button @click="askQuestion" :disabled="isLoading">
      {{ isLoading ? 'Lädt...' : 'Frage stellen' }}
    </button>
    <div v-for="msg in chatHistory" :key="msg.id">
      <strong>{{ msg.role }}:</strong> {{ msg.content }}
    </div>
  </div>
</template>
`
    default:
      return `// Example Vanilla JS integration
import { BreakPilotSDK } from '@breakpilot/compliance-sdk-vanilla';

BreakPilotSDK.init({
  apiEndpoint: '${apiEndpoint}',
  apiKey: 'pk_live_xxx',
  autoInjectBanner: true,
  bannerConfig: {
    position: 'BOTTOM',
    theme: 'LIGHT',
    language: 'de'
  },
  onConsentChange: (consents) => {
    console.log('Consents updated:', consents);
    if (consents.ANALYTICS) {
      // Load analytics
    }
  },
  onReady: () => {
    console.log('SDK ready!');
  }
});

// Or use Web Components:
// <breakpilot-consent-banner api-key="pk_live_xxx" theme="light" position="bottom">
// </breakpilot-consent-banner>
`
  }
}
