/**
 * Rules/Templates commands.
 */

import { Command } from 'commander';
import { EmdashClient } from '../client.js';
import { getServerManager } from '../server-manager.js';
import { style } from '../design.js';

export const rulesCommand = new Command('rules')
  .description('Rules and templates management')
  .addCommand(
    new Command('list')
      .description('List all templates')
      .action(async () => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const templates = await client.rulesList();
          console.log('Available Templates:');
          for (const template of templates) {
            console.log(`  - ${template}`);
          }
        } catch (error) {
          console.error(style.error('Failed to list templates:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('get')
      .description("Get a template's content")
      .argument('<name>', 'Template name')
      .action(async (name: string) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const template = await client.rulesGet(name);
          console.log(JSON.stringify(template, null, 2));
        } catch (error) {
          console.error(style.error('Failed to get template:'), (error as Error).message);
          process.exit(1);
        }
      })
  )
  .addCommand(
    new Command('init')
      .description('Initialize custom templates')
      .option('-g, --global', 'Initialize global templates')
      .option('-f, --force', 'Force overwrite existing templates')
      .action(async (options: { global?: boolean; force?: boolean }) => {
        const manager = getServerManager();
        const url = await manager.ensureServer();
        const client = new EmdashClient(url);

        try {
          const result = await client.rulesInit(
            options.global ?? false,
            options.force ?? false
          );
          console.log(style.success('Templates initialized'));
          console.log(JSON.stringify(result, null, 2));
        } catch (error) {
          console.error(style.error('Failed to initialize templates:'), (error as Error).message);
          process.exit(1);
        }
      })
  );
