/**
 * Token research agent.
 *
 * Uses the research model (Claude Sonnet via OpenRouter) for deep model
 * research — finding best models for hardware, comparing benchmarks, etc.
 * Results are cached with TTL to avoid repeated expensive calls.
 */

import { logger } from "@/lib/logger";

const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";

const RESEARCH_SYSTEM_PROMPT = `You are Token's Research Agent — a specialist in LLM model research and recommendations for self-hosted deployments.

## Your Expertise
- Local model library (primary source — all recommendations should be locally installable)
- HuggingFace model repository (for reference and benchmarks)
- VRAM requirements and quantization trade-offs (Q4_K_M, Q5_K_M, Q8, FP16)
- Benchmark performance (MMLU, HumanEval, MT-Bench, chatbot-arena ELO)
- Cost comparison: self-hosted vs cloud API (OpenAI, Anthropic, Google pricing)

## Output Format
Structure your research as:

### Summary
One paragraph answering the user's question directly.

### Recommendations
For each recommended model:
- **Model name** (e.g. \`qwen3:8b\`, \`llama3.2\`)
- **VRAM required**: X GB (quantization level)
- **Best for**: use cases
- **Benchmark highlights**: key scores
- **Trade-offs**: what you give up

### Comparison Table
| Model | VRAM | Speed | Quality | Best For |
|-------|------|-------|---------|----------|

### Cost Analysis
Compare self-hosted cost (electricity + hardware amortization) vs cloud API pricing for typical usage.

## Rules
- Only recommend models available for local inference via LLMHosts
- Always include VRAM requirements — this is critical for self-hosted users
- If the user's hardware is known, filter recommendations to what actually fits
- Be specific with numbers (token/s, GB, $/M tokens)
- Acknowledge when data may be outdated and suggest the user check the model library`;

export interface ResearchRequest {
  query: string;
  model: string;
  fleetContext: string;
  conversationHistory?: Array<{ role: string; content: string }>;
  temperature?: number;
  maxTokens?: number;
}

export interface ResearchResult {
  content: string;
  model: string;
  inputTokens: number;
  outputTokens: number;
  costUsd: number;
  latencyMs: number;
}

export async function runResearch(req: ResearchRequest): Promise<ResearchResult> {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    throw new Error("OPENROUTER_API_KEY not configured");
  }

  const start = Date.now();

  const messages = [
    { role: "system", content: RESEARCH_SYSTEM_PROMPT + "\n\n## User's Fleet\n" + req.fleetContext },
    ...(req.conversationHistory ?? []),
    { role: "user", content: req.query },
  ];

  const res = await fetch(OPENROUTER_URL, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json",
      "HTTP-Referer": "https://llmhosts.com",
      "X-Title": "LLMHosts Token Research Agent",
    },
    body: JSON.stringify({
      model: req.model,
      messages,
      temperature: req.temperature ?? 0.3,
      max_tokens: req.maxTokens ?? 8192,
    }),
  });

  if (!res.ok) {
    const errorText = await res.text().catch(() => "Unknown error");
    logger.error(
      { action: "token_research_error", status: res.status },
      "Research agent API error",
    );
    throw new Error(`Research API error (${res.status}): ${errorText}`);
  }

  const data = await res.json();
  const latencyMs = Date.now() - start;
  const choice = data.choices?.[0]?.message;
  const usage = data.usage ?? {};

  const inputTokens = usage.prompt_tokens ?? 0;
  const outputTokens = usage.completion_tokens ?? 0;
  const costUsd = parseFloat(res.headers.get("x-openrouter-cost") ?? "0");

  logger.info(
    {
      action: "token_research_complete",
      model: req.model,
      input_tokens: inputTokens,
      output_tokens: outputTokens,
      latency_ms: latencyMs,
      cost_usd: costUsd,
    },
    "Research agent complete",
  );

  return {
    content: choice?.content ?? "",
    model: data.model ?? req.model,
    inputTokens,
    outputTokens,
    costUsd,
    latencyMs,
  };
}
