#!/usr/bin/env bun

// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: GPL-3.0-or-later

import { runWebCommand } from "./commands/web.js";
import { runRepoCommand } from "./commands/repo.js";
import { RumiloError } from "../util/errors.js";
import { parseArgs } from "./parse-args.js";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";

const VERSION = "0.1.0";

async function main() {
  const { command, options, positional } = parseArgs(process.argv);

  // Handle version flag coming before any command (e.g., rumilo -v)
  // When short flags come right after process.argv, they end up in 'command'
  if (command && (command === "-v" || command === "--version") && Object.keys(options).length === 0 && positional.length === 0) {
    console.log(`rumilo v${VERSION}`);
    process.exit(0);
  }

  const actualCommand = command?.startsWith("-") ? undefined : command;

  // Handle version/short version as flag (before command) or as command
  if (options["version"] || actualCommand === "version" || actualCommand === "v") {
    console.log(`rumilo v${VERSION}`);
    process.exit(0);
  }

  if (!actualCommand || actualCommand === "help" || actualCommand === "--help" || actualCommand === "-h" || options["help"]) {
    console.log(`Rúmilo v${VERSION} — dispatch AI research subagents

Commands:
  web   Search the web and synthesize an answer
  repo  Clone and explore a git repository

Usage:
  rumilo web <query> [-u <url>] [options]
  rumilo repo -u <uri> <query> [options]

Options:
  -u <url>                 Seed URL to pre-fetch (web) or repository to clone (repo)
  --model <provider:model> Override the default model
  --ref <ref>              Checkout a specific ref after cloning (repo only)
  --full                   Full clone instead of shallow (repo only)
  --verbose                Show tool calls and results on stderr
  --no-cleanup             Preserve the workspace directory after exit
  -v, --version            Print version and exit

Configuration:
  $XDG_CONFIG_HOME/rumilo/config.toml`);
    process.exit(0);
  }

  try {
    if (command === "web") {
      const query = positional.join(" ");
      if (!query) {
        throw new RumiloError("Missing query. Usage: rumilo web <query>", "CLI_ERROR");
      }

      await runWebCommand({
        query,
        url: options["uri"] ? String(options["uri"]) : undefined,
        model: options["model"] ? String(options["model"]) : undefined,
        verbose: Boolean(options["verbose"]),
        cleanup: !options["no-cleanup"],
      });
      return;
    }

    if (command === "repo") {
      const query = positional.join(" ");
      const uri = options["uri"] ? String(options["uri"]) : undefined;
      if (!uri) {
        throw new RumiloError("Missing repository URI. Usage: rumilo repo -u <uri> <query>", "CLI_ERROR");
      }
      if (!query) {
        throw new RumiloError("Missing query. Usage: rumilo repo -u <uri> <query>", "CLI_ERROR");
      }

      await runRepoCommand({
        query,
        uri,
        ref: options["ref"] ? String(options["ref"]) : undefined,
        full: Boolean(options["full"]),
        model: options["model"] ? String(options["model"]) : undefined,
        verbose: Boolean(options["verbose"]),
        cleanup: !options["no-cleanup"],
      });
      return;
    }

    throw new RumiloError(`Unknown command: ${command}`, "CLI_ERROR");
  } catch (error: any) {
    const message = error instanceof Error ? error.message : String(error);
    console.error(message);
    process.exitCode = 1;
  }
}

main();
