import { env } from '../config/env';

/**
 * A small OpenAI client for structured answers.
 *
 * Every call asks for JSON that matches a schema (strict structured output),
 * so the CRM never parses prose. Returns the parsed object and the token
 * counts the spend cap is built on. OPENAI_BASE_URL lets the smoke suite
 * stand in for OpenAI; nothing here runs without OPENAI_API_KEY.
 */

export const isAiConfigured = () => !!env.OPENAI_API_KEY;

export class AiCallError extends Error {
  constructor(
    message: string,
    public status: number,
    public usage?: { input: number; output: number },
  ) {
    super(message);
  }
}

export type ContentPart = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } };

export interface JsonCall {
  /** Names the schema; also tells a stand-in server which answer to give. */
  name: string;
  system: string;
  user: string | ContentPart[];
  schema: Record<string, unknown>;
  maxTokens?: number;
  /** 'reports' uses OPENAI_MODEL_REPORTS (and its prices) when set. */
  tier?: AiTier;
}

export interface JsonResult<T> {
  data: T;
  model: string;
  usage: { input: number; output: number };
}

export type AiTier = 'routine' | 'reports';

export const modelFor = (tier: AiTier = 'routine') => (tier === 'reports' && env.OPENAI_MODEL_REPORTS) || env.OPENAI_MODEL;

export const costUsd = (u: { input: number; output: number }, tier: AiTier = 'routine') => {
  const reports = tier === 'reports';
  const inP = reports && env.OPENAI_REPORTS_PRICE_INPUT_PER_M !== undefined ? env.OPENAI_REPORTS_PRICE_INPUT_PER_M : env.OPENAI_PRICE_INPUT_PER_M;
  const outP = reports && env.OPENAI_REPORTS_PRICE_OUTPUT_PER_M !== undefined ? env.OPENAI_REPORTS_PRICE_OUTPUT_PER_M : env.OPENAI_PRICE_OUTPUT_PER_M;
  return (u.input * inP + u.output * outP) / 1_000_000;
};

type ChatBody = {
  model?: string;
  usage?: { prompt_tokens?: number; completion_tokens?: number };
  choices?: { message?: { content?: string | null; refusal?: string | null; tool_calls?: { id: string; type: string; function: { name: string; arguments: string } }[] }; finish_reason?: string }[];
  error?: { message?: string };
};

/** POST one Chat Completions request; provider errors become friendly AiCallErrors. */
async function post(label: string, payload: Record<string, unknown>) {
  if (!env.OPENAI_API_KEY) throw new AiCallError('AI is not set up on this server.', 503);
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), env.OPENAI_TIMEOUT_MS);
  let res: Response;
  try {
    res = await fetch(`${env.OPENAI_BASE_URL.replace(/\/$/, '')}/chat/completions`, {
      method: 'POST',
      signal: ctrl.signal,
      headers: { Authorization: `Bearer ${env.OPENAI_API_KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
  } catch (e) {
    throw new AiCallError(e instanceof Error && e.name === 'AbortError' ? 'The AI took too long to answer. Try again.' : 'Could not reach the AI service.', 504);
  } finally {
    clearTimeout(timer);
  }
  const body = (await res.json().catch(() => ({}))) as ChatBody;
  const usage = { input: body.usage?.prompt_tokens ?? 0, output: body.usage?.completion_tokens ?? 0 };
  if (!res.ok) {
    // Keep the provider's wording out of the user's face; log it instead.
    // eslint-disable-next-line no-console
    console.error(`[ai] ${label} failed ${res.status}: ${body.error?.message ?? 'no message'}`);
    throw new AiCallError(res.status === 429 ? 'The AI service is busy. Try again in a minute.' : 'The AI service could not answer just now.', res.status === 429 ? 429 : 502, usage);
  }
  const choice = body.choices?.[0];
  if (choice?.message?.refusal) throw new AiCallError('The AI declined to answer that.', 422, usage);
  if (choice?.finish_reason === 'length') throw new AiCallError('The answer was too long. Try with less text.', 422, usage);
  return { body, choice, usage };
}

export async function chatJson<T>(call: JsonCall): Promise<JsonResult<T>> {
  const { body, choice, usage } = await post(call.name, {
    model: modelFor(call.tier),
    messages: [
      { role: 'system', content: call.system },
      { role: 'user', content: call.user },
    ],
    response_format: { type: 'json_schema', json_schema: { name: call.name, strict: true, schema: call.schema } },
    max_completion_tokens: call.maxTokens ?? 1500,
    reasoning_effort: 'low',
  });
  try {
    return { data: JSON.parse(choice?.message?.content ?? '') as T, model: body.model ?? modelFor(call.tier), usage };
  } catch {
    throw new AiCallError('The AI answer could not be read. Try again.', 502, usage);
  }
}

// ── Tool calling (the CRM assistant) ───────────────────────────────────────

export type ChatMessage =
  | { role: 'system' | 'user'; content: string }
  | { role: 'assistant'; content: string | null; tool_calls?: { id: string; type: 'function'; function: { name: string; arguments: string } }[] }
  | { role: 'tool'; tool_call_id: string; content: string };

export interface ToolSpec {
  name: string;
  description: string;
  /** JSON schema, strict: every property listed in `required`, no extras. */
  parameters: Record<string, unknown>;
}

export interface ToolTurn {
  content: string | null;
  toolCalls: { id: string; name: string; arguments: string }[];
  model: string;
  usage: { input: number; output: number };
}

/** One round of a tool-using conversation: the model answers or asks for tools. */
export async function chatTools(p: { messages: ChatMessage[]; tools: ToolSpec[]; maxTokens?: number }): Promise<ToolTurn> {
  const { body, choice, usage } = await post('crm_assistant', {
    model: modelFor('routine'),
    messages: p.messages,
    tools: p.tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters, strict: true } })),
    parallel_tool_calls: true,
    max_completion_tokens: p.maxTokens ?? 3000,
    // GPT-5.4 on Chat Completions takes function tools only without reasoning.
    reasoning_effort: 'none',
  });
  return {
    content: choice?.message?.content ?? null,
    toolCalls: (choice?.message?.tool_calls ?? []).filter((c) => c.type === 'function').map((c) => ({ id: c.id, name: c.function.name, arguments: c.function.arguments })),
    model: body.model ?? modelFor('routine'),
    usage,
  };
}
