/**
 * Token intent classifier.
 *
 * Uses the classification model (Gemini Flash Lite via OpenRouter) to classify
 * user messages into intent categories, then routes to the appropriate model.
 * Cheapest model tier — runs before every message to determine routing.
 */

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

export type TokenIntent = "chat" | "research" | "fleet_action" | "analysis";

export interface ClassificationResult {
  intent: TokenIntent;
  confidence: number;
  reasoning: string;
}

const CLASSIFICATION_PROMPT = `You are an intent classifier for Token, an AI fleet management assistant. Classify the user's message into exactly one category.

Categories:
- "chat": General conversation, greetings, simple questions about models or hardware, cost comparisons, troubleshooting help, explanations
- "research": Requests to find, compare, or evaluate specific models. Questions like "what's the best model for X", "find me a vision model", "latest coding models", "benchmark comparison"
- "fleet_action": Direct commands to modify the fleet. Examples: "install qwen3:8b on my desktop", "remove llama from server", "restart the engine", "pull this model", "update model X"
- "analysis": Complex multi-device optimization, deployment planning, capacity analysis. Examples: "plan a deployment across my 3 machines", "optimize my fleet", "how should I distribute models", "analyze my fleet utilization"

Respond with ONLY a JSON object, no markdown:
{"intent": "<category>", "confidence": <0.0-1.0>, "reasoning": "<brief explanation>"}`;

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

export async function classifyIntent(
  message: string,
  model: string,
): Promise<ClassificationResult> {
  const apiKey = process.env.OPENROUTER_API_KEY;
  if (!apiKey) {
    logger.warn({ action: "token_classify_no_key" }, "No OpenRouter key, defaulting to chat");
    return { intent: "chat", confidence: 1.0, reasoning: "No API key configured" };
  }

  try {
    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 Classifier",
      },
      body: JSON.stringify({
        model,
        messages: [
          { role: "system", content: CLASSIFICATION_PROMPT },
          { role: "user", content: message },
        ],
        temperature: 0.0,
        max_tokens: 200,
      }),
    });

    if (!res.ok) {
      logger.warn(
        { action: "token_classify_error", status: res.status },
        "Classification API failed, defaulting to chat",
      );
      return { intent: "chat", confidence: 1.0, reasoning: "Classification API error" };
    }

    const data = await res.json();
    const content = data.choices?.[0]?.message?.content ?? "";

    // Parse JSON from response (handle possible markdown wrapping)
    const jsonMatch = content.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      logger.warn(
        { action: "token_classify_parse_fail", content },
        "Failed to parse classification JSON",
      );
      return { intent: "chat", confidence: 1.0, reasoning: "Parse failure" };
    }

    const parsed = JSON.parse(jsonMatch[0]);
    const intent = parsed.intent as TokenIntent;
    const confidence = typeof parsed.confidence === "number" ? parsed.confidence : 0.5;
    const reasoning = parsed.reasoning || "";

    // Validate intent is a known value
    const validIntents: TokenIntent[] = ["chat", "research", "fleet_action", "analysis"];
    if (!validIntents.includes(intent)) {
      return { intent: "chat", confidence: 1.0, reasoning: "Unknown intent, defaulting to chat" };
    }

    // Fall back to chat if confidence is below threshold
    if (confidence < CONFIDENCE_THRESHOLD) {
      logger.info(
        { action: "token_classify_low_confidence", intent, confidence },
        "Low confidence classification, using chat",
      );
      return { intent: "chat", confidence, reasoning: `Low confidence (${confidence}): ${reasoning}` };
    }

    logger.info(
      { action: "token_classify", intent, confidence },
      "Message classified",
    );

    return { intent, confidence, reasoning };
  } catch (err) {
    logger.error(
      { action: "token_classify_error", err },
      "Classification failed, defaulting to chat",
    );
    return { intent: "chat", confidence: 1.0, reasoning: "Classification error" };
  }
}

/**
 * Given a classification result and TokenConfig, return the model to use.
 */
export function selectModelForIntent(
  intent: TokenIntent,
  config: {
    chatModel: string;
    researchModel: string;
    reasoningModel: string;
  },
): string {
  switch (intent) {
    case "research":
      return config.researchModel;
    case "analysis":
      return config.reasoningModel;
    case "fleet_action":
      return config.chatModel; // Fleet actions use chat model with special system prompt
    case "chat":
    default:
      return config.chatModel;
  }
}
