/**
 * Context Prime CLI command — Load minimal context priming files
 *
 * Usage:
 *   morph-spec prime feature   (outputs feature-prime.md to stdout)
 *   morph-spec prime bug
 *   morph-spec prime refactor
 *   morph-spec prime design
 *   morph-spec prime infra
 */

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

const PRIME_FILES = {
  feature: '.morph/context/feature-prime.md',
  bug: '.morph/context/bug-prime.md',
  refactor: '.morph/context/refactor-prime.md',
  design: '.morph/context/design-prime.md',
  infra: '.morph/context/infra-prime.md'
};

const PRIME_TYPES = Object.keys(PRIME_FILES);

export async function contextPrimeCommand(type, options) {
  if (!type) {
    console.log(chalk.cyan('\n  Available prime types:\n'));
    for (const [key, path] of Object.entries(PRIME_FILES)) {
      const exists = existsSync(join(process.cwd(), path));
      const status = exists ? chalk.green('✓') : chalk.red('✗');
      console.log(`  ${status} ${key.padEnd(10)} → ${path}`);
    }
    console.log('');
    console.log(chalk.gray('  Usage: morph-spec prime <type>'));
    console.log(chalk.gray('  Example: morph-spec prime feature\n'));
    return;
  }

  if (!PRIME_TYPES.includes(type)) {
    console.error(chalk.red(`Unknown prime type: ${type}`));
    console.error(chalk.gray(`Valid types: ${PRIME_TYPES.join(', ')}`));
    process.exit(1);
  }

  const filePath = join(process.cwd(), PRIME_FILES[type]);

  if (!existsSync(filePath)) {
    console.error(chalk.red(`Prime file not found: ${filePath}`));
    console.error(chalk.gray('Run `morph-spec init` to initialize MORPH-SPEC files.'));
    process.exit(1);
  }

  const content = readFileSync(filePath, 'utf8');

  if (options.json) {
    console.log(JSON.stringify({ type, path: filePath, content }));
    return;
  }

  // Output to stdout — designed to be read into context
  console.log(content);
}
