import { Command } from 'commander';
import { describe, it, expect } from 'vitest';

import { registerLogCommand } from './cli.js';

function buildTestProgram(): Command {
  const program = new Command('mosaic');
  program.exitOverride(); // prevent process.exit in tests
  registerLogCommand(program);
  return program;
}

describe('registerLogCommand', () => {
  it('registers a "log" subcommand on the parent', () => {
    const program = buildTestProgram();
    const names = program.commands.map((c) => c.name());
    expect(names).toContain('log');
  });

  it('log command has tail, search, export, and level subcommands', () => {
    const program = buildTestProgram();
    const logCmd = program.commands.find((c) => c.name() === 'log');
    expect(logCmd).toBeDefined();
    const subNames = logCmd!.commands.map((c) => c.name());
    expect(subNames).toContain('tail');
    expect(subNames).toContain('search');
    expect(subNames).toContain('export');
    expect(subNames).toContain('level');
  });

  it('tail subcommand has expected options', () => {
    const program = buildTestProgram();
    const logCmd = program.commands.find((c) => c.name() === 'log')!;
    const tailCmd = logCmd.commands.find((c) => c.name() === 'tail')!;
    const optionNames = tailCmd.options.map((o) => o.long);
    expect(optionNames).toContain('--agent');
    expect(optionNames).toContain('--level');
    expect(optionNames).toContain('--category');
    expect(optionNames).toContain('--tier');
    expect(optionNames).toContain('--limit');
    expect(optionNames).toContain('--db');
  });

  it('search subcommand accepts a positional query argument', () => {
    const program = buildTestProgram();
    const logCmd = program.commands.find((c) => c.name() === 'log')!;
    const searchCmd = logCmd.commands.find((c) => c.name() === 'search')!;
    // Commander stores positional args in _args
    const argNames = searchCmd.registeredArguments.map((a) => a.name());
    expect(argNames).toContain('query');
  });

  it('export subcommand accepts a positional path argument', () => {
    const program = buildTestProgram();
    const logCmd = program.commands.find((c) => c.name() === 'log')!;
    const exportCmd = logCmd.commands.find((c) => c.name() === 'export')!;
    const argNames = exportCmd.registeredArguments.map((a) => a.name());
    expect(argNames).toContain('path');
  });

  it('level subcommand accepts a positional level argument', () => {
    const program = buildTestProgram();
    const logCmd = program.commands.find((c) => c.name() === 'log')!;
    const levelCmd = logCmd.commands.find((c) => c.name() === 'level')!;
    const argNames = levelCmd.registeredArguments.map((a) => a.name());
    expect(argNames).toContain('level');
  });
});
