import fs from 'fs-extra';
import chalk from 'chalk';
import inquirer from 'inquirer';
import { TARGETS } from './constants.js';
import { performSync } from './ide-adapters.js';
import { rescaffold } from './cli-helpers.js';

/**
 * Flow: Migrate existing setup.
 */
export async function migrateExisting(options = {}) {
  const masterPath = '.ai/master-skill.md';
  const existing = await findExistingAgentFiles(options.source);

  if (existing.length === 0) {
    console.log(chalk.red('No existing agent files found. Try "Scaffold new agentic coding setup" instead.'));
    return;
  }

  if (!(await fs.pathExists(masterPath))) {
    const { sourceChoice } = await inquirer.prompt([{
      type: 'list',
      name: 'sourceChoice',
      message: 'Create .ai/master-skill.md from which source?',
      choices: [
        ...existing.filter(f => !f.endsWith('/')),
        'Merge all (concatenate)'
      ]
    }]);

    await fs.ensureDir('.ai');

    if (sourceChoice === 'Merge all (concatenate)') {
      let merged = '';
      for (const f of existing.filter(x => !x.endsWith('/'))) {
        const content = await fs.readFile(f, 'utf8');
        merged += `\n\n<!-- Source: ${f} -->\n\n` + content;
      }
      await fs.writeFile(masterPath, merged.trimStart());
      console.log(chalk.blue(`Merged files into ${masterPath}`));
    } else {
      const content = await fs.readFile(sourceChoice, 'utf8');
      const header = `<!-- Generated by rosetta from ${sourceChoice} -->\n\n`;
      await fs.writeFile(masterPath, header + content);
      console.log(chalk.blue(`Created ${masterPath} from ${sourceChoice}`));
    }
  }

  const { regenerate } = await inquirer.prompt([{
    type: 'confirm',
    name: 'regenerate',
    message: 'Would you like to (re)generate IDE wrappers from Rosetta templates?',
    default: false
  }]);

  if (regenerate) {
    const { ides } = await inquirer.prompt([{
      type: 'checkbox',
      name: 'ides',
      message: 'Select IDEs to (re)generate wrappers for:',
      choices: TARGETS.map(t => t.label)
    }]);

    await performSync({ interactive: true, regenerateWrappers: true, selectedIdes: ides });
  }

  console.log(chalk.bold.green('Migration complete.'));
}

/**
 * Finds existing agent-specific configuration files.
 */
export async function findExistingAgentFiles(customSource) {
  const result = [];
  if (customSource) {
    if (await fs.pathExists(customSource)) {
      result.push(customSource);
    } else {
      console.log(chalk.yellow(`Warning: Custom source "${customSource}" not found.`));
    }
  }

  if (await fs.pathExists('CLAUDE.md')) result.push('CLAUDE.md');
  if (await fs.pathExists('.cursorrules')) result.push('.cursorrules');
  if (await fs.pathExists('.github/copilot-instructions.md')) result.push('.github/copilot-instructions.md');
  if (await fs.pathExists('.windsurf/rules')) result.push('.windsurf/rules/');
  if (await fs.pathExists('.codex/rules.md')) result.push('.codex/rules.md');
  if (await fs.pathExists('.kilo/rules.md')) result.push('.kilo/rules.md');
  if (await fs.pathExists('.continue/config.md')) result.push('.continue/config.md');
  if (await fs.pathExists('skills')) result.push('skills/');
  if (await fs.pathExists('.agent/skills')) result.push('.agent/skills/');
  return result;
}

/**
 * Migration from specific source.
 */
export async function migrateFromSource(source) {
  if (!(await fs.pathExists(source))) {
    console.error(chalk.red(`Source file ${source} not found.`));
    return;
  }
  const content = await fs.readFile(source, 'utf8');
  const masterPath = '.ai/master-skill.md';
  await fs.ensureDir('.ai');

  const header = `<!-- Generated by rosetta from ${source} -->\n\n`;
  await fs.writeFile(masterPath, header + content);
  console.log(chalk.bold.green(`Migrated ${source} to ${masterPath}`));

  const { scaffoldOthers } = await inquirer.prompt([{
    type: 'confirm',
    name: 'scaffoldOthers',
    message: 'Would you like to scaffold the rest of the .ai/ structure (AGENT.md, task.md, memory)?',
    default: true
  }]);

  if (scaffoldOthers) {
    await rescaffold('all');
  }
}
