/**
 * Squad Template CLI command
 *
 * Usage:
 *   morph-spec squad-template list
 *   morph-spec squad-template use <template-id> --feature=<feature>
 *   morph-spec squad-template show <template-id>
 */

import chalk from 'chalk';
import { readFileSync, existsSync, readdirSync } from 'fs';
import { join } from 'path';

const SQUAD_TEMPLATES_DIR = join(process.cwd(), 'framework/squad-templates');

function loadTemplate(id) {
  const filePath = join(SQUAD_TEMPLATES_DIR, `${id}.json`);
  if (!existsSync(filePath)) return null;
  try {
    return JSON.parse(readFileSync(filePath, 'utf8'));
  } catch {
    return null;
  }
}

function listAllTemplates() {
  if (!existsSync(SQUAD_TEMPLATES_DIR)) return [];
  return readdirSync(SQUAD_TEMPLATES_DIR)
    .filter(f => f.endsWith('.json'))
    .map(f => {
      try {
        return JSON.parse(readFileSync(join(SQUAD_TEMPLATES_DIR, f), 'utf8'));
      } catch {
        return null;
      }
    })
    .filter(Boolean);
}

export async function squadTemplateListCommand(options) {
  try {
    const templates = listAllTemplates();

    if (templates.length === 0) {
      console.log(chalk.gray('\n  No squad templates found.\n'));
      return;
    }

    console.log(chalk.cyan(`\n  Squad Templates (${templates.length})\n`));

    for (const t of templates) {
      console.log(`  ${chalk.bold(t.id)} — ${t.name}`);
      console.log(`  ${chalk.gray(t.description)}`);
      console.log(`  Agents: ${t.agents.map(a => a.id).join(', ')}`);
      console.log(`  Parallel: ${t.parallel ? chalk.green('yes') : chalk.gray('no')} | Coordination: ${t.coordination}`);
      console.log(`  Gain: ${chalk.cyan(t.estimatedParallelGain)}`);
      console.log('');
    }
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function squadTemplateUseCommand(templateId, options) {
  try {
    if (!options.feature) {
      console.error(chalk.red('--feature is required'));
      process.exit(1);
    }

    const template = loadTemplate(templateId);
    if (!template) {
      console.error(chalk.red(`Template not found: ${templateId}`));
      console.error(chalk.gray('Run `morph-spec squad-template list` to see available templates'));
      process.exit(1);
    }

    console.log(chalk.cyan(`\n  Configuring Squad Template: ${templateId}\n`));
    console.log(`  Feature: ${options.feature}`);
    console.log(`  Template: ${template.name}`);
    console.log(`  Agents: ${template.agents.length}`);
    console.log(`  Parallel: ${template.parallel ? 'yes' : 'no'}`);

    // Show spawn-team configuration
    console.log(chalk.yellow('\n  To spawn this squad, use the Task tool with these configs:\n'));

    for (const agent of template.agents) {
      console.log(`  Agent: ${chalk.bold(agent.id)} (${agent.role})`);
      console.log(`  Standards: ${agent.standards?.join(', ') || '(none)'}`);
      const deliverable = template.deliverables?.[agent.id];
      if (deliverable) {
        console.log(`  Deliverable: ${deliverable}`);
      }
      console.log('');
    }

    console.log(chalk.gray('  See: morph-spec spawn-team --template=' + templateId + ' --feature=' + options.feature));
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}

export async function squadTemplateShowCommand(templateId, options) {
  try {
    const template = loadTemplate(templateId);
    if (!template) {
      console.error(chalk.red(`Template not found: ${templateId}`));
      process.exit(1);
    }

    if (options.json) {
      console.log(JSON.stringify(template, null, 2));
      return;
    }

    console.log(chalk.cyan(`\n  Squad Template: ${template.id}\n`));
    console.log(`  Name:        ${template.name}`);
    console.log(`  Description: ${template.description}`);
    console.log(`  Parallel:    ${template.parallel ? chalk.green('yes') : chalk.gray('no')}`);
    console.log(`  Coordinator: ${template.coordination}`);
    console.log(`  Wait all:    ${template.waitForAll ? 'yes' : 'no'}`);
    console.log(`  Gain:        ${template.estimatedParallelGain}`);

    console.log('\n  Agents:');
    for (const agent of template.agents) {
      console.log(`    ${chalk.bold(agent.id)} — ${agent.role} (${agent.domain})`);
      if (agent.standards?.length > 0) {
        console.log(`      Standards: ${agent.standards.join(', ')}`);
      }
    }

    if (template.deliverables) {
      console.log('\n  Deliverables:');
      for (const [agent, deliverable] of Object.entries(template.deliverables)) {
        console.log(`    ${agent}: ${deliverable}`);
      }
    }
    console.log('');
  } catch (err) {
    console.error(chalk.red(`Error: ${err.message}`));
    process.exit(1);
  }
}
