import { HttpError } from "../middleware/errorHandler";
import { prisma } from "./prisma";
import { decryptSecret, encryptSecret } from "./tokenCrypto";

// Platform-wide OpenAI settings, stored on the IntegrationSettings singleton and
// editable only by system admins (see integrations.routes.ts). The API key is
// encrypted at rest the same way the Microsoft client secret is.

export const DEFAULT_OPENAI_MODEL = "gpt-4.1-mini";
export const DEFAULT_TRANSCRIBE_MODEL = "whisper-1";

// Language the generated tasks are written in. A separate setting (not part of the
// editable prompt) so it can't get lost when someone edits the prompt text.
export const TASK_LANGUAGES = ["English", "Same as input", "Turkish"] as const;
export type TaskLanguage = (typeof TASK_LANGUAGES)[number];
export const DEFAULT_TASK_LANGUAGE: TaskLanguage = "English";

function languageRule(language: TaskLanguage): string {
  if (language === "Same as input") {
    return 'Output language: write every title, description and the "understanding" in the language the person used ("inputLanguage"). English input gets English tasks, Turkish input gets Turkish tasks.';
  }
  return `Output language: write every title, description and the "understanding" in ${language}, whatever language the person used. Translate from the input when needed, keeping names of people, companies, properties and products, codes, references and amounts exactly as they are.`;
}

// Only the instructions are admin-editable. The board context (lists, members,
// labels, columns, today's date) and the JSON output format are always appended
// by code, so an edited prompt can't break task extraction.
export const DEFAULT_TASK_PROMPT = `You turn what a person gives you (screenshots, photos of notes or whiteboards, voice notes, typed text) into tasks for a Kanban board. First work out what they actually want done, then write the tasks.

Language: first set "inputLanguage" to the language the person used in this input (the words of the voice note, the typed text or the text in the image). The language to write the tasks in is given by the "Output language" rule after these instructions. The examples below are in mixed languages only to illustrate; never copy their language.

How to read the input
- Voice notes and typed text are usually instructions spoken TO YOU. Carry out the instruction: the task is the work to be done, never the instruction itself. Examples:
  - "Create a task named abc" -> title "abc"
  - "abc adında bir görev oluştur" -> title "abc"
  - "Yarın ev sahibini aramak için bir task aç, Joy'a ata" -> a task to call the landlord ("Call the landlord" in English, "Ev sahibini ara" in Turkish), due date tomorrow, member Joy
  - "Remind me to send the invoices on Friday, it's urgent" -> title "Send the invoices", due date Friday, label Urgent if it exists
  - "Add two cards: book the venue and order the catering" -> two tasks, "Book the venue" and "Order the catering"
- Never start a title with command words such as "Create task", "Add a card", "Task named", "New task", "Remind me to", "Görev oluştur", "Task aç", "Kart ekle".
- Screenshots and photos: extract each actionable item (to-dos, requests, action points, bugs, follow-ups). Ignore decoration, headers, signatures and small talk. Items already marked as done (ticked, crossed out, "[x]") go to the board's done-type list if there is one; otherwise leave them out.

How to write tasks
- One task per distinct piece of work. Don't merge unrelated items or split one item into several.
- Title: short and specific (ideally under 80 characters), phrased as an action, in the output language.
- Description: only extra details that are really in the input (context, amounts, names, links, quotes), in the output language. Don't repeat the title, don't narrate ("The user wants...", "User requested..."), and leave it empty when there is nothing to add.
- Put assignees, dates, labels and column values into their own fields instead of the description, using only values that exist on this board (listed below). Match people by first name, surname or email. Leave a field empty when unsure.
- Only add a label when the input names it or clearly means it ("bug", "urgent", "acil"). Priority words ("high priority", "öncelik yüksek") go to a priority column if the board has one, not to a label.
- Resolve relative dates ("tomorrow", "yarın", "Friday", "cuma") against today's date and weekday. A bare weekday or "this Friday" / "bu cuma" is the next such day. "Next week", "haftaya" and "haftaya cuma" mean the following calendar week, e.g. on a Monday "haftaya cuma" is the Friday 11 days later, not this week's Friday.
- In "understanding", say in one short sentence, in the output language, what you understood the person wants.
- If the input contains nothing that looks like work to be done (a random photo, a meme, an empty page), set isTaskLike to false, explain why in "warning", and still return any tasks you can reasonably infer (possibly none).`;

export type OpenAiConfig = {
  apiKey: string;
  model: string;
  transcribeModel: string;
  prompt: string;
  taskLanguage: TaskLanguage;
};

export async function getOpenAiSettings() {
  const settings = await prisma.integrationSettings.findUnique({ where: { id: "singleton" } });
  let apiKey: string | null = null;
  if (settings?.openaiApiKey) {
    try {
      apiKey = decryptSecret(settings.openaiApiKey);
    } catch {
      apiKey = null;
    }
  }
  return {
    apiKey,
    model: settings?.openaiModel || DEFAULT_OPENAI_MODEL,
    transcribeModel: settings?.openaiTranscribeModel || DEFAULT_TRANSCRIBE_MODEL,
    prompt: settings?.openaiTaskPrompt || DEFAULT_TASK_PROMPT,
    customPrompt: !!settings?.openaiTaskPrompt,
    taskLanguage: (TASK_LANGUAGES as readonly string[]).includes(settings?.openaiTaskLanguage ?? "")
      ? (settings!.openaiTaskLanguage as TaskLanguage)
      : DEFAULT_TASK_LANGUAGE,
  };
}

export async function requireOpenAiConfig(): Promise<OpenAiConfig> {
  const s = await getOpenAiSettings();
  if (!s.apiKey) {
    throw new HttpError(400, "AI import isn't set up yet. Ask a system admin to add an OpenAI API key under Integrations.");
  }
  return { apiKey: s.apiKey, model: s.model, transcribeModel: s.transcribeModel, prompt: s.prompt, taskLanguage: s.taskLanguage };
}

export async function saveOpenAiSettings(input: {
  apiKey?: string;
  model: string;
  transcribeModel: string;
  prompt: string | null;
  taskLanguage: TaskLanguage;
}) {
  const data = {
    openaiTaskLanguage: input.taskLanguage,
    ...(input.apiKey ? { openaiApiKey: encryptSecret(input.apiKey) } : {}),
    openaiModel: input.model,
    openaiTranscribeModel: input.transcribeModel,
    // Saving the default text verbatim is stored as "no override", so future
    // improvements to the default prompt still reach this install.
    openaiTaskPrompt: input.prompt && input.prompt.trim() !== DEFAULT_TASK_PROMPT.trim() ? input.prompt.trim() : null,
  };
  await prisma.integrationSettings.upsert({
    where: { id: "singleton" },
    update: data,
    create: { id: "singleton", ...data },
  });
}

async function openAiFetch(apiKey: string, path: string, init: RequestInit & { timeoutMs?: number }) {
  let res: Response;
  try {
    res = await fetch(`https://api.openai.com/v1${path}`, {
      ...init,
      headers: { Authorization: `Bearer ${apiKey}`, ...(init.headers ?? {}) },
      signal: AbortSignal.timeout(init.timeoutMs ?? 120_000),
    });
  } catch (err) {
    const timedOut = err instanceof Error && err.name === "TimeoutError";
    throw new HttpError(502, timedOut ? "OpenAI took too long to respond. Please try again." : "Couldn't reach OpenAI. Please try again.");
  }

  if (!res.ok) {
    let detail = "";
    try {
      const body = (await res.json()) as { error?: { message?: string } };
      detail = body.error?.message ?? "";
    } catch {
      // non-JSON error body
    }
    console.error(`OpenAI ${path} failed (${res.status}): ${detail}`);
    if (res.status === 401) throw new HttpError(502, "OpenAI rejected the API key. A system admin needs to update it under Integrations.");
    if (res.status === 429) throw new HttpError(429, "OpenAI rate limit or quota reached. Please try again later.");
    if (res.status === 404) throw new HttpError(502, `OpenAI model not available: ${detail || "check the model name under Integrations."}`);
    throw new HttpError(502, `OpenAI request failed${detail ? `: ${detail}` : "."}`);
  }
  return res;
}

/** Cheap connectivity/key check used by the Integrations page "Test" button. */
export async function testOpenAi(config: Pick<OpenAiConfig, "apiKey" | "model">) {
  await openAiFetch(config.apiKey, `/models/${encodeURIComponent(config.model)}`, { method: "GET", timeoutMs: 20_000 });
}

const AUDIO_EXTENSIONS: Record<string, string> = {
  "audio/webm": "webm",
  "video/webm": "webm",
  "audio/ogg": "ogg",
  "audio/mp4": "m4a",
  "audio/x-m4a": "m4a",
  "audio/m4a": "m4a",
  "video/mp4": "mp4",
  "audio/mpeg": "mp3",
  "audio/mp3": "mp3",
  "audio/wav": "wav",
  "audio/x-wav": "wav",
  "audio/wave": "wav",
  "audio/flac": "flac",
};

export function isSupportedAudio(mimetype: string) {
  return !!AUDIO_EXTENSIONS[mimetype.split(";")[0].trim()];
}

/** `hint` is passed as Whisper's prompt: names and terms from the board, so people's
 * names ("Emre", "Ijas") are spelled the way the board spells them. */
export async function transcribeAudio(config: OpenAiConfig, audio: { buffer: Buffer; mimetype: string }, hint?: string) {
  const mime = audio.mimetype.split(";")[0].trim();
  const form = new FormData();
  form.append("model", config.transcribeModel);
  // The API infers the format from the filename extension, not the content type.
  form.append("file", new Blob([new Uint8Array(audio.buffer)], { type: mime }), `voice-note.${AUDIO_EXTENSIONS[mime] ?? "webm"}`);
  if (hint) form.append("prompt", hint.slice(0, 800));
  const res = await openAiFetch(config.apiKey, "/audio/transcriptions", { method: "POST", body: form });
  const body = (await res.json()) as { text?: string };
  return (body.text ?? "").trim();
}

export type AiTask = {
  title: string;
  description: string;
  list: string;
  status: string;
  startDate: string;
  dueDate: string;
  members: string[];
  labels: string[];
  fields: { name: string; value: string }[];
};

export type AiExtraction = { understanding: string; isTaskLike: boolean; warning: string; tasks: AiTask[] };

const EXTRACTION_SCHEMA = {
  type: "object",
  additionalProperties: false,
  // "inputLanguage" and "understanding" come first on purpose: having the model state
  // the language and the intent before writing tasks stops it answering English input
  // in Turkish (the prompt has Turkish examples) and literal "Create task named X" titles.
  required: ["inputLanguage", "understanding", "isTaskLike", "warning", "tasks"],
  properties: {
    inputLanguage: { type: "string", description: "Language the person used in THIS input (e.g. English, Turkish)." },
    understanding: { type: "string", description: "One sentence: what the person wants, in the output language." },
    isTaskLike: { type: "boolean", description: "False when the input does not look like work to be done." },
    warning: { type: "string", description: "Why the input doesn't look like tasks, or other caveats. Empty if none." },
    tasks: {
      type: "array",
      items: {
        type: "object",
        additionalProperties: false,
        required: ["title", "description", "list", "status", "startDate", "dueDate", "members", "labels", "fields"],
        properties: {
          title: { type: "string" },
          description: { type: "string", description: "Empty string if none." },
          list: { type: "string", description: "Exact name of an existing list, or empty for the default list." },
          status: { type: "string", description: "Exact label of an existing status, or empty." },
          startDate: { type: "string", description: "YYYY-MM-DD or empty." },
          dueDate: { type: "string", description: "YYYY-MM-DD or empty." },
          members: { type: "array", items: { type: "string" }, description: "Emails of existing board members." },
          labels: { type: "array", items: { type: "string" }, description: "Names of existing labels." },
          fields: {
            type: "array",
            description: "Values for existing custom columns; omit columns you have no value for.",
            items: {
              type: "object",
              additionalProperties: false,
              required: ["name", "value"],
              properties: { name: { type: "string" }, value: { type: "string" } },
            },
          },
        },
      },
    },
  },
} as const;

export async function extractTasks(
  config: OpenAiConfig,
  input: {
    boardContext: string;
    note?: string;
    transcript?: string;
    images: { mimetype: string; buffer: Buffer }[];
  }
): Promise<AiExtraction> {
  const userContent: unknown[] = [];
  const textParts = [
    input.note ? `Typed by the person (addressed to you, the assistant):\n${input.note}` : "",
    input.transcript ? `Voice note transcript (spoken to you, the assistant):\n${input.transcript}` : "",
    input.images.length > 0 ? `${input.images.length} image(s) attached.` : "",
  ].filter(Boolean);
  userContent.push({ type: "text", text: textParts.join("\n\n") || "Extract the tasks." });
  for (const img of input.images) {
    userContent.push({
      type: "image_url",
      image_url: { url: `data:${img.mimetype};base64,${img.buffer.toString("base64")}`, detail: "high" },
    });
  }

  const res = await openAiFetch(config.apiKey, "/chat/completions", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: config.model,
      messages: [
        { role: "system", content: `${config.prompt}\n\n${languageRule(config.taskLanguage)}\n\n${input.boardContext}` },
        { role: "user", content: userContent },
      ],
      response_format: { type: "json_schema", json_schema: { name: "board_tasks", strict: true, schema: EXTRACTION_SCHEMA } },
    }),
  });

  const body = (await res.json()) as { choices?: { message?: { content?: string; refusal?: string } }[] };
  const message = body.choices?.[0]?.message;
  if (message?.refusal) throw new HttpError(422, `The AI declined to process this input: ${message.refusal}`);
  try {
    const parsed = JSON.parse(message?.content ?? "") as AiExtraction;
    return {
      understanding: parsed.understanding ?? "",
      isTaskLike: !!parsed.isTaskLike,
      warning: parsed.warning ?? "",
      tasks: Array.isArray(parsed.tasks) ? parsed.tasks : [],
    };
  } catch {
    throw new HttpError(502, "The AI returned an unreadable response. Please try again.");
  }
}

// ---------- AI assistant (chat panel) ----------

// Admin-editable part of the assistant's instructions (tone, language, house rules).
// The security rules and tool usage rules in lib/assistant/agent.ts are always added
// by code and can't be changed from the settings page.
export const DEFAULT_ASSISTANT_PROMPT = `You are Assisto AI, the assistant built into My Assisto, the team's task and board app.

- Reply in the language the user writes in. Keep answers short and practical; use bullet points for lists.
- When the user asks about tasks, look them up with the tools instead of guessing, and show the relevant cards with display_cards.
- For summaries, use summarize_tasks so the user sees charts, then add two or three sentences with the key points (what is overdue, what is due soon, where the load is).
- When creating tasks from a file or an image, extract every actionable item, pick the most suitable board (ask if it is unclear), and propose them in one go.
- If a request is ambiguous (which board, which card), ask one short clarifying question.`;

export async function getAssistantSettings() {
  const settings = await prisma.integrationSettings.findUnique({ where: { id: "singleton" } });
  return {
    enabled: settings?.assistantEnabled ?? true,
    // Empty = use the same model as the import feature.
    model: settings?.assistantModel || "",
    prompt: settings?.assistantPrompt || DEFAULT_ASSISTANT_PROMPT,
    customPrompt: !!settings?.assistantPrompt,
  };
}

export async function saveAssistantSettings(input: { enabled: boolean; model: string; prompt: string | null }) {
  const data = {
    assistantEnabled: input.enabled,
    assistantModel: input.model.trim() || null,
    assistantPrompt: input.prompt && input.prompt.trim() !== DEFAULT_ASSISTANT_PROMPT.trim() ? input.prompt.trim() : null,
  };
  await prisma.integrationSettings.upsert({ where: { id: "singleton" }, update: data, create: { id: "singleton", ...data } });
}

export type ChatMessage =
  | { role: "system" | "user"; content: string | unknown[] }
  | { role: "assistant"; content: string | null; tool_calls?: ToolCall[] }
  | { role: "tool"; tool_call_id: string; content: string };

export type ToolCall = { id: string; type: "function"; function: { name: string; arguments: string } };

export type ChatTool = {
  type: "function";
  function: { name: string; description: string; parameters: Record<string, unknown> };
};

/** One chat-completions round trip with optional tools; returns the assistant message. */
export async function openAiChat(
  config: Pick<OpenAiConfig, "apiKey" | "model">,
  input: { messages: ChatMessage[]; tools?: ChatTool[]; toolChoice?: "auto" | "none" }
): Promise<{ content: string | null; tool_calls?: ToolCall[]; refusal?: string | null }> {
  const res = await openAiFetch(config.apiKey, "/chat/completions", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      model: config.model,
      messages: input.messages,
      ...(input.tools?.length ? { tools: input.tools, tool_choice: input.toolChoice ?? "auto", parallel_tool_calls: true } : {}),
    }),
  });
  const body = (await res.json()) as { choices?: { message?: { content: string | null; tool_calls?: ToolCall[]; refusal?: string | null } }[] };
  const message = body.choices?.[0]?.message;
  if (!message) throw new HttpError(502, "The AI returned an empty response. Please try again.");
  return message;
}
