/**
 * DSS Start Command
 *
 * Start the DSS server.
 */

import chalk from 'chalk';
import ora from 'ora';
import { exec } from 'child_process';
import { getConfig, getProjectRoot, hasProjectConfig } from '../lib/config.js';
import {
  startServer,
  isServerRunning,
  getServerPid,
  waitForServer,
  stopServer,
} from '../lib/server.js';

interface StartOptions {
  port: string;
  dev: boolean;
  open: boolean;
}

export async function startCommand(options: StartOptions): Promise<void> {
  const port = parseInt(options.port, 10);
  const cwd = getProjectRoot();
  const config = getConfig();

  // Check if already running
  if (isServerRunning(cwd)) {
    const pid = getServerPid(cwd);
    console.log(chalk.yellow(`  DSS is already running (PID: ${pid})`));
    console.log(chalk.dim(`  Dashboard: http://localhost:${port}`));
    console.log('');
    console.log(chalk.dim('  To restart: dss stop && dss start'));
    return;
  }

  const spinner = ora('Starting DSS server...').start();

  try {
    // Start server
    const serverProcess = await startServer({
      port,
      dev: options.dev,
      cwd,
    });

    if (options.dev) {
      spinner.succeed('DSS running in development mode');
      console.log(chalk.dim('  Press Ctrl+C to stop'));
      console.log('');

      // In dev mode, we're attached to the process
      serverProcess.on('exit', (code) => {
        console.log(chalk.dim(`\n  Server exited with code ${code}`));
        process.exit(code || 0);
      });

      // Handle Ctrl+C
      process.on('SIGINT', () => {
        console.log(chalk.dim('\n  Stopping server...'));
        serverProcess.kill('SIGTERM');
      });
    } else {
      // Wait for server to be ready
      spinner.text = 'Waiting for server to be ready...';
      const ready = await waitForServer(port, 15000);

      if (!ready) {
        spinner.fail('Server failed to start');
        console.error(chalk.red('  Check logs: .dss/dss.log'));
        await stopServer(cwd);
        process.exit(1);
      }

      spinner.succeed(`DSS started (PID: ${serverProcess.pid})`);
      console.log('');
      console.log(chalk.green('  Dashboard:'), chalk.blue(`http://localhost:${port}`));
      console.log(chalk.green('  API:      '), chalk.blue(`http://localhost:${port}/api`));
      console.log(chalk.green('  Docs:     '), chalk.blue(`http://localhost:${port}/docs`));
      console.log('');
      console.log(chalk.dim('  Logs: .dss/dss.log'));
      console.log(chalk.dim('  Stop: dss stop'));
      console.log('');

      // Show Figma status
      if (config.figmaFileKey) {
        console.log(chalk.dim(`  Figma file: ${config.figmaFileKey}`));
      } else {
        console.log(chalk.yellow('  No Figma file configured'));
        console.log(chalk.dim('  Run: dss config --set figmaFileKey=YOUR_KEY'));
      }

      // Open browser if requested
      if (options.open) {
        const url = `http://localhost:${port}`;
        const openCmd = process.platform === 'darwin' ? 'open' :
                        process.platform === 'win32' ? 'start' : 'xdg-open';
        exec(`${openCmd} ${url}`);
      }
    }
  } catch (error) {
    spinner.fail('Failed to start DSS');
    console.error(chalk.red(`  ${(error as Error).message}`));
    process.exit(1);
  }
}
