/**
 * DSS Init Command
 *
 * Initialize DSS in the current project.
 */

import chalk from 'chalk';
import ora from 'ora';
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import {
  getProjectRoot,
  hasProjectConfig,
  saveProjectConfig,
  setGlobalConfig,
  type DSSConfig,
} from '../lib/config.js';

interface InitOptions {
  figmaKey?: string;
  figmaToken?: string;
}

export async function initCommand(options: InitOptions): Promise<void> {
  const spinner = ora('Initializing DSS...').start();

  try {
    const projectRoot = getProjectRoot();
    const dssDir = join(projectRoot, '.dss');

    // Check if already initialized
    if (hasProjectConfig()) {
      spinner.warn('DSS is already initialized in this project');
      console.log(chalk.dim(`  Config: ${join(dssDir, 'config.json')}`));
      return;
    }

    // Create .dss directory
    if (!existsSync(dssDir)) {
      mkdirSync(dssDir, { recursive: true });
    }

    // Create output directory
    const outputDir = join(dssDir, 'output');
    if (!existsSync(outputDir)) {
      mkdirSync(outputDir, { recursive: true });
    }

    // Build config
    const config: DSSConfig = {
      port: 3456,
      outputDir: '.dss/output',
      tokenFormat: 'css',
      componentFramework: 'react',
    };

    if (options.figmaKey) {
      config.figmaFileKey = options.figmaKey;
    }

    // Save Figma token globally (not in project config for security)
    if (options.figmaToken) {
      setGlobalConfig('figmaToken', options.figmaToken);
      spinner.info('Figma token saved to global config');
    }

    // Save project config
    saveProjectConfig(config);

    spinner.succeed('DSS initialized successfully!');

    console.log('');
    console.log(chalk.green('  Created:'));
    console.log(chalk.dim(`    .dss/config.json`));
    console.log(chalk.dim(`    .dss/output/`));
    console.log('');

    // Next steps
    console.log(chalk.blue('  Next steps:'));
    if (!options.figmaToken) {
      console.log(chalk.dim('    1. Set your Figma token:'));
      console.log(chalk.white('       dss config --set figmaToken=figd_xxxxx'));
    }
    if (!options.figmaKey) {
      console.log(chalk.dim(`    ${options.figmaToken ? '1' : '2'}. Set your Figma file key:`));
      console.log(chalk.white('       dss config --set figmaFileKey=abc123'));
    }
    console.log(chalk.dim(`    ${options.figmaToken && options.figmaKey ? '1' : '3'}. Start the server:`));
    console.log(chalk.white('       dss start'));
    console.log('');

    // Add to .gitignore if exists
    const gitignorePath = join(projectRoot, '.gitignore');
    if (existsSync(gitignorePath)) {
      const { readFileSync, appendFileSync } = await import('fs');
      const gitignore = readFileSync(gitignorePath, 'utf-8');
      if (!gitignore.includes('.dss/')) {
        appendFileSync(gitignorePath, '\n# DSS\n.dss/\n');
        console.log(chalk.dim('  Added .dss/ to .gitignore'));
      }
    }
  } catch (error) {
    spinner.fail('Failed to initialize DSS');
    console.error(chalk.red(`  ${(error as Error).message}`));
    process.exit(1);
  }
}
