import Anthropic from "@anthropic-ai/sdk";
import { CORRECT_CITY_SCHEMA, CORRECT_CITY_SYSTEM, buildUserMessage, usageCostUsd } from "./prompt.js";

export const name = "anthropic";

// Per-million-token rates. Verified against
// https://docs.claude.com/en/docs/about-claude/pricing
// (5-minute ephemeral cache rates: write 1.25x base, read 0.10x base).
export const pricingByModel = {
  "claude-haiku-4-5-20251001":  { inputUsdPerM: 1.00, outputUsdPerM: 5.00,  cacheWriteUsdPerM: 1.25,  cacheReadUsdPerM: 0.10 },
  "claude-sonnet-4-5-20250929": { inputUsdPerM: 3.00, outputUsdPerM: 15.00, cacheWriteUsdPerM: 3.75,  cacheReadUsdPerM: 0.30 },
  "claude-opus-4-1-20250805":   { inputUsdPerM: 15.00,outputUsdPerM: 75.00, cacheWriteUsdPerM: 18.75, cacheReadUsdPerM: 1.50 },
};

export const defaultModel = "claude-haiku-4-5-20251001";

export function activeModel() {
  return process.env.ANTHROPIC_MODEL || defaultModel;
}

export function isAvailable() {
  return Boolean(process.env.ANTHROPIC_API_KEY);
}

let _client = null;
function getClient() {
  if (_client) return _client;
  _client = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
  return _client;
}

const TOOL = {
  name: "correct_city",
  description: "Pick the closest matching US city/town/CDP name from the provided list for the user's input, or return null if nothing reasonable matches.",
  input_schema: CORRECT_CITY_SCHEMA,
};

export async function correctCity({ city, stateCode, candidates }) {
  const model = activeModel();
  const pricing = pricingByModel[model] || pricingByModel[defaultModel];
  const resp = await getClient().messages.create({
    model,
    max_tokens: 200,
    system: [{ type: "text", text: CORRECT_CITY_SYSTEM, cache_control: { type: "ephemeral" } }],
    tools: [TOOL],
    tool_choice: { type: "tool", name: TOOL.name },
    messages: [{ role: "user", content: buildUserMessage({ city, stateCode, candidates }) }],
  });
  const toolUse = resp.content.find((b) => b.type === "tool_use");
  if (!toolUse) throw new Error("Anthropic did not return a tool_use block");
  const input = toolUse.input;
  const u = resp.usage || {};
  const usage = {
    input_tokens:                Number(u.input_tokens ?? 0),
    output_tokens:               Number(u.output_tokens ?? 0),
    cache_creation_input_tokens: Number(u.cache_creation_input_tokens ?? 0),
    cache_read_input_tokens:     Number(u.cache_read_input_tokens ?? 0),
  };
  return {
    provider: name,
    model,
    correctedCityName: input.correctedCityName ?? null,
    confidence: input.confidence ?? "low",
    reasoning: input.reasoning ?? "",
    usage,
    costUsd: usageCostUsd(usage, pricing),
    pricingPerMTok: {
      input: pricing.inputUsdPerM,
      output: pricing.outputUsdPerM,
      cacheWrite: pricing.cacheWriteUsdPerM,
      cacheRead: pricing.cacheReadUsdPerM,
    },
  };
}
