/**
 * Template generators for create-llmhosts scaffolder.
 * Produces docker-compose.yml, .env.example, llmhosts.toml, README.md.
 */

import type { ProjectConfig } from "./types.js";

export function generateDockerCompose(config: ProjectConfig): string {
  const { hasGpu, dockerCompose } = config.answers;
  if (!dockerCompose) return "";

  const gpuConfig = hasGpu
    ? `
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]`
    : "";

  return `# LLMHosts + Ollama - Scaffolded by create-llmhosts
# Usage: docker compose up
# Docs: https://llmhosts.com/docs

services:
  llmhost:
    image: python:3.12-slim
    command: sh -c "pip install --no-cache-dir llmhost && llmhosts serve --config /app/llmhosts.toml"
    ports:
      - "\${LLMHOST_PORT:-4000}:4000"
    volumes:
      - ./llmhosts.toml:/app/llmhosts.toml:ro
      - llmhost-data:/root/.llmhost
    environment:
      - LLMHOST_SERVER_PORT=4000
      - OPENAI_API_KEY=\${OPENAI_API_KEY:-}
      - ANTHROPIC_API_KEY=\${ANTHROPIC_API_KEY:-}
    depends_on:
      ollama:
        condition: service_healthy
    restart: unless-stopped

  ollama:
    image: ollama/ollama:latest
    ports:
      - "11434:11434"
    volumes:
      - ollama-data:/root/.ollama${gpuConfig}
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:11434/api/tags"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 30s

volumes:
  llmhost-data:
  ollama-data:
`;
}

export function generateEnvExample(config: ProjectConfig): string {
  const { cloudProviders } = config.answers;
  const lines: string[] = [
    "# LLMHosts - Environment variables",
    "# Copy to .env and fill in: cp .env.example .env",
    "# WARNING: .env is gitignored. Never commit secrets.",
    "",
    "# Proxy port (default 4000)",
    "LLMHOST_PORT=4000",
    "",
  ];

  if (cloudProviders.includes("openai")) {
    lines.push("# OpenAI API key (get from platform.openai.com)");
    lines.push("OPENAI_API_KEY=your-key-here");
    lines.push("");
  }
  if (cloudProviders.includes("anthropic")) {
    lines.push("# Anthropic API key (get from console.anthropic.com)");
    lines.push("ANTHROPIC_API_KEY=your-key-here");
    lines.push("");
  }
  if (cloudProviders.includes("google")) {
    lines.push("# Google AI API key (get from aistudio.google.com)");
    lines.push("GOOGLE_AI_API_KEY=your-key-here");
    lines.push("");
  }
  if (cloudProviders.includes("aws")) {
    lines.push("# AWS Bedrock credentials");
    lines.push("AWS_ACCESS_KEY_ID=your-key-here");
    lines.push("AWS_SECRET_ACCESS_KEY=your-secret-here");
    lines.push("AWS_REGION=us-east-1");
    lines.push("");
  }

  if (config.answers.tunnelSupport) {
    lines.push("# Tunnel (optional - for remote access)");
    lines.push("# TAILSCALE_AUTHKEY=tskey-REPLACE_ME");
    lines.push("# CLOUDFLARE_TUNNEL_TOKEN=REPLACE_ME");
  }

  return lines.join("\n");
}

export function generateLlmhostsToml(config: ProjectConfig): string {
  const { cloudProviders, hasGpu, dockerCompose } = config.answers;
  const hasCloud = cloudProviders.some((p) => p !== "none");
  const ollamaHost = dockerCompose ? "http://ollama:11434" : "http://127.0.0.1:11434";

  return `# LLMHosts configuration - Scaffolded by create-llmhosts
# Docs: https://llmhosts.com/docs/config
# Env overrides: LLMHOST_<SECTION>_<KEY>=<VALUE>

[server]
host = "0.0.0.0"
port = 4000
workers = 1
log_level = "info"
cors_origins = ["*"]

[ollama]
host = "${ollamaHost}"
timeout = 120.0
auto_discover = true

[router]
prefer_local = ${hasGpu}
cost_optimize = true
fallback_to_cloud = ${hasCloud}
enable_knn = false
enable_modernbert = false
enable_qwen = false

[cache]
enabled = true
max_size_mb = 512
ttl_seconds = 3600
enable_namespace = false
enable_vcache = false
delta = 0.01

[dashboard]
enabled = true
tui = true
web = true

[engine]
type = "ollama"
vllm_host = "http://localhost:8000"
`;
}

export function generateReadme(config: ProjectConfig): string {
  const { projectName, dockerCompose } = config.answers;
  const providers = config.answers.cloudProviders.filter((p) => p !== "none");
  const providerList =
    providers.length > 0
      ? providers.map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join(", ")
      : "None (local Ollama only)";

  let body = `# ${projectName}

LLMHosts AI proxy project scaffolded by \`create-llmhosts\`.

## Configured

- **Cloud providers**: ${providerList}
- **Docker Compose**: ${dockerCompose ? "Yes" : "No"}
- **Tunnel support**: ${config.answers.tunnelSupport ? "Yes" : "No"}

## Quick Start

`;

  if (dockerCompose) {
    body += `\`\`\`bash
cp .env.example .env
# Add your API keys to .env
docker compose up
\`\`\`

The proxy will be available at \`http://localhost:4000\`.
`;
  } else {
    body += `\`\`\`bash
cp .env.example .env
# Add your API keys to .env
pip install llmhosts
llmhosts serve --config llmhosts.toml
\`\`\`

The proxy will be available at \`http://localhost:4000\`.
`;
  }

  body += `
## Integrate with your tools

| Tool | Configuration |
|------|---------------|
| **Cursor** | Add OpenAI-compatible provider: \`http://localhost:4000/v1\` |
| **Claude Code** | Set OpenAI API base URL: \`http://localhost:4000/v1\` |
| **Continue.dev** | Add base URL: \`http://localhost:4000/v1\` |
| **Open WebUI** | Set OpenAI API URL: \`http://localhost:4000/v1\` |

## Docs

- [LLMHosts Documentation](https://llmhosts.com/docs)
- [Configuration Reference](https://llmhosts.com/docs/config)
`;

  return body;
}
