#!/usr/bin/env node

// Load .env file from project root (Node >= 20.12 built-in, no dotenv needed).
// Silent no-op if the file doesn't exist.
try { process.loadEnvFile(); } catch { /* .env not found — that's fine */ }

import { Command } from 'commander';
import { registerStartCommand } from './start.js';
import { registerSendCommand } from './send.js';
import { registerSessionsCommand } from './sessions.js';
import { registerDoctorCommand } from './doctor.js';
import { registerConfigCommand } from './config-cmd.js';
import { registerTuiCommand } from './tui.js';
import { registerCompletionCommand } from './completion.js';
import { registerSetupCommand } from './setup.js';
import { registerGmailAuthCommand } from './gmail-auth.js';
import { registerGcalAuthCommand } from './gcal-auth.js';
import { registerGdocsAuthCommand } from './gdocs-auth.js';
import { registerGdriveAuthCommand } from './gdrive-auth.js';
import { registerGtasksAuthCommand } from './gtasks-auth.js';
import { registerOpenaiAuthCommand } from './openai-auth.js';
import { registerOpenaiKeyCommand } from './openai-key.js';
import { registerZaiAuthCommand } from './zai-auth.js';
import { registerAnthropicAuthCommand } from './anthropic-auth.js';
import { registerSkillsCommand } from './skills.js';

export function createProgram(): Command {
  const program = new Command();

  program
    .name('flynn')
    .description('Flynn — self-hosted personal AI agent')
    .version('0.1.0');

  registerStartCommand(program);
  registerTuiCommand(program);
  registerSendCommand(program);
  registerSessionsCommand(program);
  registerDoctorCommand(program);
  registerConfigCommand(program);
  registerCompletionCommand(program);
  registerSetupCommand(program);
  registerGmailAuthCommand(program);
  registerGcalAuthCommand(program);
  registerGdocsAuthCommand(program);
  registerGdriveAuthCommand(program);
  registerGtasksAuthCommand(program);
  registerOpenaiAuthCommand(program);
  registerOpenaiKeyCommand(program);
  registerZaiAuthCommand(program);
  registerAnthropicAuthCommand(program);
  registerSkillsCommand(program);

  return program;
}

// Only run when executed directly (not imported in tests)
const isDirectRun = process.argv[1] &&
  (process.argv[1].endsWith('/cli/index.js') ||
   process.argv[1].endsWith('/cli/index.ts'));

if (isDirectRun) {
  const program = createProgram();
  program.parse(process.argv);
}
