/**
 * Internal AI gateway (BRD §8.2). Features never call a model provider directly; they call `complete()`.
 * - Provider-agnostic: swap AI_PROVIDER / models without touching features (Anthropic Claude by default)
 * - Cost control: credits metered per workspace, cache of repeated prompts, cheaper model for simple tasks
 * - Guardrails: full audit of prompts, tool calls and results in ai_logs
 */
import Anthropic from "@anthropic-ai/sdk";
import { and, desc, eq, gte } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { sha256 } from "@/lib/util";
import { aiCreditsRemaining, recordUsage } from "@/lib/services/billing";
import { ApiError } from "@/lib/api";

export const MODELS = {
  smart: process.env.AI_MODEL_SMART ?? "claude-opus-5-5",
  fast: process.env.AI_MODEL_FAST ?? "claude-haiku-5-5",
};

export class AiUnavailable extends Error {}

export type Tier = "smart" | "fast";
export type CompleteInput = {
  feature: string;
  tier?: Tier;
  system: string | Anthropic.TextBlockParam[];
  messages: Anthropic.MessageParam[];
  tools?: Anthropic.Tool[];
  maxTokens?: number;
  effort?: "low" | "medium" | "high";
  cache?: boolean;
};

let client: Anthropic | null = null;
async function getClient(ctx: Pick<Ctx, "db" | "workspace">) {
  // a workspace may bring its own key via the Anthropic integration
  const own = await ctx.db.query.integrations.findFirst({ where: and(eq(schema.integrations.workspaceId, ctx.workspace.id), eq(schema.integrations.provider, "anthropic"), eq(schema.integrations.status, "connected")) });
  if (own?.tokenRef) {
    const { readSecret } = await import("@/lib/vault");
    const c = await readSecret(ctx.db, own.tokenRef);
    if (c?.apiKey) return new Anthropic({ apiKey: c.apiKey });
  }
  if (!process.env.ANTHROPIC_API_KEY) throw new AiUnavailable("AI is not configured. Set ANTHROPIC_API_KEY (or connect Anthropic in Integrations).");
  client ??= new Anthropic();
  return client;
}

export function aiConfigured() {
  return !!process.env.ANTHROPIC_API_KEY;
}

export async function complete(ctx: Pick<Ctx, "db" | "workspace">, input: CompleteInput): Promise<{ message: Anthropic.Message; text: string; cached: boolean }> {
  const credits = await aiCreditsRemaining(ctx);
  if (credits.remaining <= 0) throw new ApiError(402, "ai_credits_exhausted", "This workspace has used all AI credits for the month");
  const tier = input.tier ?? "smart";
  const model = MODELS[tier];
  const promptKey = sha256(JSON.stringify({ model, s: input.system, m: input.messages, t: input.tools?.map((t) => t.name) }));

  if (input.cache !== false && !input.tools) {
    const hit = await ctx.db.query.aiLogs.findFirst({ where: and(eq(schema.aiLogs.workspaceId, ctx.workspace.id), eq(schema.aiLogs.promptHash, promptKey), gte(schema.aiLogs.createdAt, new Date(Date.now() - 24 * 3600000))), orderBy: desc(schema.aiLogs.createdAt) });
    if (hit?.response) {
      await ctx.db.insert(schema.aiLogs).values({ workspaceId: ctx.workspace.id, feature: input.feature, model, promptHash: promptKey, prompt: lastUserText(input.messages).slice(0, 4000), response: hit.response, cached: true });
      return { message: { content: [{ type: "text", text: hit.response }] } as unknown as Anthropic.Message, text: hit.response, cached: true };
    }
  }

  const anthropic = await getClient(ctx);
  const params: Record<string, unknown> = {
    model,
    max_tokens: input.maxTokens ?? 4000,
    system: input.system,
    messages: input.messages,
    output_config: { effort: input.effort ?? (tier === "fast" ? "low" : "medium") },
    ...(input.tools ? { tools: input.tools, tool_choice: { type: "auto" } } : {}),
  };
  let message: Anthropic.Message;
  try {
    if (model.startsWith("claude-opus") || model.startsWith("claude-fable") || model.startsWith("claude-sonnet")) {
      // server-side refusal fallback: a policy decline is re-run on a fallback model in the same call
      message = (await anthropic.beta.messages.create({ ...(params as any), betas: ["server-side-fallback-2026-07-01"], fallbacks: "default" } as any)) as unknown as Anthropic.Message;
    } else {
      message = await anthropic.messages.create(params as unknown as Anthropic.MessageCreateParamsNonStreaming);
    }
  } catch (e) {
    if (e instanceof Anthropic.RateLimitError) throw new ApiError(429, "ai_rate_limited", "AI provider is rate limiting — try again shortly");
    if (e instanceof Anthropic.AuthenticationError) throw new AiUnavailable("AI provider rejected the API key");
    if (e instanceof Anthropic.APIError) throw new ApiError(502, "ai_provider_error", `AI provider error ${e.status ?? ""}`.trim());
    throw e;
  }
  const text = message.content.filter((b): b is Anthropic.TextBlock => b.type === "text").map((b) => b.text).join("\n").trim();
  const inTok = message.usage?.input_tokens ?? 0, outTok = message.usage?.output_tokens ?? 0;
  // 1 credit ≈ 1,000 tokens on the smart model; the fast model costs a fraction
  const credits_ = Math.max(1, Math.ceil(((inTok + outTok) / 1000) * (tier === "fast" ? 0.1 : 1)));
  await ctx.db.insert(schema.aiLogs).values({
    workspaceId: ctx.workspace.id, feature: input.feature, model: message.model ?? model, promptHash: promptKey, prompt: lastUserText(input.messages).slice(0, 4000),
    response: text.slice(0, 20000), toolCalls: message.content.filter((b) => b.type === "tool_use"), inputTokens: inTok, outputTokens: outTok, credits: credits_,
  });
  await recordUsage(ctx, "ai_credits", credits_);
  if (message.stop_reason === "refusal") throw new ApiError(422, "ai_refused", "The AI model declined this request");
  return { message, text, cached: false };
}

function lastUserText(messages: Anthropic.MessageParam[]) {
  const m = [...messages].reverse().find((x) => x.role === "user");
  if (!m) return "";
  return typeof m.content === "string" ? m.content : m.content.map((c) => (c.type === "text" ? c.text : c.type === "tool_result" ? JSON.stringify(c.content).slice(0, 500) : "")).join("\n");
}

/** Extract the first JSON object/array from a model response. */
export function parseJson<T>(text: string): T | null {
  const m = text.match(/```(?:json)?\s*([\s\S]*?)```/);
  const raw = m ? m[1]! : text;
  const start = raw.search(/[[{]/);
  if (start < 0) return null;
  for (let end = raw.length; end > start; end--) {
    try {
      return JSON.parse(raw.slice(start, end)) as T;
    } catch {
      /* shrink */
    }
  }
  return null;
}
