/**
 * DSS Sync Command
 *
 * Sync design tokens from Figma to local files.
 */

import chalk from 'chalk';
import ora from 'ora';
import { writeFileSync, existsSync, mkdirSync } from 'fs';
import { dirname, join } from 'path';
import { getConfig, getProjectRoot } from '../lib/config.js';
import { getApiClient } from '../lib/api.js';
import { isServerRunning } from '../lib/server.js';

interface SyncOptions {
  format: string;
  output?: string;
  fileKey?: string;
}

export async function syncCommand(options: SyncOptions): Promise<void> {
  const config = getConfig();
  const cwd = getProjectRoot();

  // Check if server is running
  if (!isServerRunning(cwd)) {
    console.log(chalk.yellow('  DSS server is not running'));
    console.log(chalk.dim('  Start it with: dss start'));
    console.log('');
    console.log(chalk.dim('  Or sync directly via API if running remotely'));
    process.exit(1);
  }

  const fileKey = options.fileKey || config.figmaFileKey;
  if (!fileKey) {
    console.log(chalk.red('  No Figma file key configured'));
    console.log(chalk.dim('  Set it with: dss config --set figmaFileKey=YOUR_KEY'));
    process.exit(1);
  }

  const format = options.format || config.tokenFormat || 'css';
  const outputPath = options.output || getDefaultOutputPath(format, cwd);

  const spinner = ora(`Syncing tokens from Figma (${format})...`).start();

  try {
    const api = getApiClient({ port: config.port });

    // Extract tokens
    spinner.text = 'Extracting tokens from Figma...';
    const result = await api.extractTokens(fileKey, format);

    if (!result.success) {
      throw new Error('Token extraction failed');
    }

    // Write output file
    spinner.text = `Writing ${result.tokens_count} tokens to ${outputPath}...`;

    const dir = dirname(outputPath);
    if (!existsSync(dir)) {
      mkdirSync(dir, { recursive: true });
    }

    writeFileSync(outputPath, result.formatted_output);

    spinner.succeed(`Synced ${result.tokens_count} tokens`);
    console.log('');
    console.log(chalk.green('  Output:'), chalk.dim(outputPath));
    console.log('');

    // Show token summary
    const categories = result.tokens.reduce((acc, t) => {
      acc[t.category] = (acc[t.category] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    console.log(chalk.dim('  Token breakdown:'));
    Object.entries(categories).forEach(([cat, count]) => {
      console.log(chalk.dim(`    ${cat}: ${count}`));
    });
    console.log('');

  } catch (error) {
    spinner.fail('Sync failed');
    console.error(chalk.red(`  ${(error as Error).message}`));
    process.exit(1);
  }
}

function getDefaultOutputPath(format: string, cwd: string): string {
  const extensions: Record<string, string> = {
    css: 'tokens.css',
    scss: '_tokens.scss',
    json: 'tokens.json',
    ts: 'tokens.ts',
    js: 'tokens.js',
  };

  const filename = extensions[format] || 'tokens.css';
  return join(cwd, '.dss', 'output', filename);
}
