#!/usr/bin/env node
/**
 * create-llmhosts - Scaffold a project with LLMHosts AI proxy pre-configured.
 * Usage: npx create-llmhosts my-project
 */

import { program } from "commander";
import inquirer from "inquirer";
import chalk from "chalk";
import ora from "ora";
import { mkdir, writeFile } from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";
import type { CloudProvider, WizardAnswers, ProjectConfig } from "./types.js";
import {
  generateDockerCompose,
  generateEnvExample,
  generateLlmhostsToml,
  generateReadme,
} from "./templates.js";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

program
  .name("create-llmhosts")
  .description("Scaffold a project with LLMHosts AI proxy pre-configured")
  .argument("[project-name]", "Project directory name (e.g. my-ai-project)")
  .option("-y, --yes", "Use defaults, skip prompts")
  .action(async (projectNameArg: string | undefined, opts: { yes?: boolean }) => {
    await run(projectNameArg, opts.yes ?? false);
  });

async function run(projectNameArg: string | undefined, skipPrompts: boolean) {
  console.log(chalk.bold.cyan("\n  LLMHosts Project Scaffolder\n"));

  let projectName: string;
  let answers: WizardAnswers;

  if (skipPrompts) {
    projectName = projectNameArg || "my-llmhost-project";
    answers = {
      projectName,
      hasGpu: true,
      cloudProviders: ["openai"],
      dockerCompose: true,
      tunnelSupport: false,
    };
  } else {
    projectName = projectNameArg?.trim() || "my-llmhost-project";

    const { hasGpu } = await inquirer.prompt<{ hasGpu: boolean }>([
      {
        type: "confirm",
        name: "hasGpu",
        message: "Do you have a GPU?",
        default: true,
      },
    ]);

    const { cloudProviders } = await inquirer.prompt<{
      cloudProviders: CloudProvider[];
    }>([
      {
        type: "checkbox",
        name: "cloudProviders",
        message: "Which cloud providers do you use? (select multiple)",
        choices: [
          { name: "OpenAI", value: "openai", checked: true },
          { name: "Anthropic", value: "anthropic", checked: false },
          { name: "Google AI", value: "google", checked: false },
          { name: "AWS Bedrock", value: "aws", checked: false },
          { name: "None", value: "none", checked: false },
        ],
      },
    ]);

    const { dockerCompose } = await inquirer.prompt<{
      dockerCompose: boolean;
    }>([
      {
        type: "confirm",
        name: "dockerCompose",
        message: "Do you want Docker Compose setup?",
        default: true,
      },
    ]);

    const { tunnelSupport } = await inquirer.prompt<{
      tunnelSupport: boolean;
    }>([
      {
        type: "confirm",
        name: "tunnelSupport",
        message: "Include tunnel support for remote access?",
        default: false,
      },
    ]);

    const providers: CloudProvider[] = cloudProviders.includes("none")
      ? ["none"]
      : (cloudProviders as CloudProvider[]).length > 0
        ? (cloudProviders as CloudProvider[])
        : ["none"];
    answers = {
      projectName,
      hasGpu,
      cloudProviders: providers,
      dockerCompose,
      tunnelSupport,
    };
  }

  const cwd = process.cwd();
  const targetPath = path.resolve(cwd, projectName);

  const config: ProjectConfig = {
    answers,
    targetPath,
  };

  const spinner = ora(`Creating project: ${projectName}`).start();

  try {
    await mkdir(targetPath, { recursive: true });

    const files: { path: string; content: string }[] = [
      { path: "llmhosts.toml", content: generateLlmhostsToml(config) },
      { path: ".env.example", content: generateEnvExample(config) },
      { path: "README.md", content: generateReadme(config) },
    ];

    if (answers.dockerCompose) {
      files.push({
        path: "docker-compose.yml",
        content: generateDockerCompose(config),
      });
    }

    for (const f of files) {
      const filePath = path.join(targetPath, f.path);
      await writeFile(filePath, f.content, "utf-8");
      spinner.text = `  Writing ${f.path}`;
      spinner.render();
    }

    spinner.succeed("Done!");

    console.log(chalk.green("\nNext steps:"));
    console.log(chalk.white(`  cd ${projectName}`));
    console.log(chalk.white("  cp .env.example .env"));
    console.log(chalk.gray("  # Add your API keys to .env"));
    if (answers.dockerCompose) {
      console.log(chalk.white("  docker compose up"));
    } else {
      console.log(chalk.white("  pip install llmhosts"));
      console.log(chalk.white("  llmhosts serve --config llmhosts.toml"));
    }
    console.log(chalk.gray("  # Or: pip install llmhosts && llmhosts serve"));
    console.log();
  } catch (err) {
    spinner.fail("Failed");
    console.error(chalk.red(err instanceof Error ? err.message : String(err)));
    process.exit(1);
  }
}

program.parse();
