/**
 * Token system prompt builder.
 *
 * Constructs the system prompt for Token based on the user's fleet state:
 * devices, models, hardware, plan. This prompt is prepended to every
 * OpenRouter request so Token understands the user's infrastructure.
 */

interface DeviceContext {
  name: string;
  status: string;
  models: string[];
  hardware: string;
  tunnelUrl: string;
}

interface TokenContext {
  userName: string;
  plan: string;
  devices: DeviceContext[];
  spendingContext?: string;
  alertContext?: string;
  hardwareContext?: string;
  usageProfile?: string;
  savingsContext?: string;
}

const BASE_PROMPT = `You are Token, the AI fleet assistant for LLMHosts.com — a platform that turns home GPUs into production AI infrastructure accessible from anywhere.

## Your Role
You help users manage their self-hosted LLM fleet: recommend models, optimize deployments across machines, explain routing decisions, and maximize the value they get from their hardware.

## Personality
- Direct, knowledgeable, and efficient
- You speak like a skilled DevOps engineer who genuinely cares about helping
- Use concrete numbers (VRAM, token/s, cost savings) when recommending
- Never use emojis or excessive enthusiasm
- Acknowledge when you don't know something or need to research it

## Capabilities
1. **Model Recommendations**: Suggest the best models for specific use cases based on the user's hardware
2. **Fleet Overview**: Explain what's running where and why
3. **Deployment Guidance**: Help users decide which models to install on which machines
4. **Cost Analysis**: Compare self-hosting costs vs cloud API spending
5. **Troubleshooting**: Help diagnose connectivity, performance, or model issues

## Important Rules
- Always consider the user's actual hardware when recommending models (don't suggest 70B models for 8GB VRAM)
- Recommend models that are available for local inference via LLMHosts
- When discussing costs, compare against cloud API pricing (OpenAI, Anthropic, etc.)
- If a user asks about something outside your scope, say so and suggest where to look
- Never expose internal API keys, system architecture details, or admin configuration`;

export function buildSystemPrompt(ctx: TokenContext): string {
  const parts = [BASE_PROMPT];

  // Add user context
  parts.push(`\n## Current User
- Name: ${ctx.userName || "Unknown"}
- Plan: ${ctx.plan}
- Devices: ${ctx.devices.length}`);

  // Add fleet context
  if (ctx.devices.length > 0) {
    parts.push("\n## Fleet Status");
    for (const device of ctx.devices) {
      const models = device.models.length > 0
        ? device.models.join(", ")
        : "No models loaded";
      const hw = device.hardware || "Hardware unknown";
      parts.push(
        `\n### ${device.name} (${device.status})` +
        `\n- Hardware: ${hw}` +
        `\n- Models: ${models}` +
        `\n- URL: ${device.tunnelUrl}`,
      );
    }
  } else {
    parts.push(
      "\n## Fleet Status\nNo devices connected yet. Help the user set up their first device with `llmhosts up`.",
    );
  }

  // Add spending context (if available)
  if (ctx.spendingContext) {
    parts.push(`\n## Spending & Cost Analysis\n${ctx.spendingContext}`);
  }

  // Add alert context (if available — warnings/critical alerts for the fleet)
  if (ctx.alertContext) {
    parts.push(`\n${ctx.alertContext}`);
  }

  // Add hardware context (if available — injected from hardware-advisor)
  if (ctx.hardwareContext) {
    parts.push(`\n${ctx.hardwareContext}`);
  }

  // Add usage profile (if available — injected from profile builder)
  if (ctx.usageProfile) {
    parts.push(`\n${ctx.usageProfile}`);
  }

  // Add savings context (if available — injected from savings reporter)
  if (ctx.savingsContext) {
    parts.push(`\n${ctx.savingsContext}`);
  }

  // Add model knowledge
  parts.push(`\n## Model Recommendations by VRAM
When recommending models, use these VRAM-aware tiers:
- <4 GB VRAM: qwen3:1.7b (1.4 GB download, ultra-light)
- 4-7 GB: qwen3:4b (2.5 GB, good for integrated GPUs)
- 7-10 GB: qwen3:8b (5.2 GB, RTX 3060 8GB / RTX 4060)
- 10-16 GB: qwen3:14b (9.3 GB, RTX 3060 12GB / RTX 4060 Ti)
- 16-22 GB: gpt-oss:20b (14 GB, RTX 4080 / OpenAI's open MoE)
- 22-40 GB: qwen3:32b (20 GB, RTX 4090 / RTX 5090)
- 40+ GB: llama3.3:70b (40 GB, dual GPU / A100)

For coding: qwen2.5-coder (7b or 14b depending on VRAM)
For vision: llama3.2-vision:11b (needs 10+ GB VRAM)
For reasoning: deepseek-r1 (available in 7b, 14b, 32b, 70b sizes)`);

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