import type { ChatAttachment, ChatImageAttachment, ChatMessage, ChatTextAttachment } from "./types.js";

const DEFAULT_USER_LOCATION = "San Francisco, CA";

function currentDateString(now = new Date()) {
  return now.toISOString().slice(0, 10);
}

function resolveUserLocation(userLocation?: string) {
  return userLocation?.trim() || process.env.SYBIL_USER_LOCATION?.trim() || DEFAULT_USER_LOCATION;
}

export function buildSystemPromptAugmentation(userLocation?: string, now = new Date()) {
  return `Current date: ${currentDateString(now)}.\nUser location: ${resolveUserLocation(userLocation)}.`;
}

function escapeAttribute(value: string) {
  return value.replace(/"/g, "&quot;");
}

export function getImageAttachments(message: ChatMessage) {
  return (message.attachments ?? []).filter((attachment): attachment is ChatImageAttachment => attachment.kind === "image");
}

export function getTextAttachments(message: ChatMessage) {
  return (message.attachments ?? []).filter((attachment): attachment is ChatTextAttachment => attachment.kind === "text");
}

export function buildImageSummaryText(attachments: ChatImageAttachment[]) {
  if (!attachments.length) return null;
  const label = attachments.length === 1 ? "Attached image" : "Attached images";
  return `${label}: ${attachments.map((attachment) => attachment.filename).join(", ")}.`;
}

export function buildTextAttachmentPrompt(attachment: ChatTextAttachment) {
  const truncationNote = attachment.truncated ? ' truncated="true"' : "";
  return [
    `Attached text file: ${attachment.filename}${attachment.truncated ? " (content truncated)" : ""}`,
    `<attached_file filename="${escapeAttribute(attachment.filename)}" mime_type="${escapeAttribute(attachment.mimeType)}"${truncationNote}>`,
    attachment.text,
    "</attached_file>",
  ].join("\n");
}

export function parseImageDataUrl(attachment: ChatImageAttachment) {
  const match = attachment.dataUrl.match(/^data:(image\/(?:png|jpeg));base64,([a-z0-9+/=\s]+)$/i);
  if (!match) {
    throw new Error(`Invalid image attachment data URL for '${attachment.filename}'.`);
  }

  const mediaType = match[1].toLowerCase();
  if (mediaType !== attachment.mimeType) {
    throw new Error(`Image attachment MIME type mismatch for '${attachment.filename}'.`);
  }

  return {
    mediaType,
    data: match[2].replace(/\s+/g, ""),
  };
}

export function buildSystemPromptAugmentationMessage(userLocation?: string) {
  return {
    role: "system",
    content: buildSystemPromptAugmentation(userLocation),
  };
}

export function buildTopLevelSystemPrompt(messages: ChatMessage[], userLocation?: string, toolSystemPrompt?: string) {
  return [toolSystemPrompt, buildSystemPromptAugmentation(userLocation), messages.find((message) => message.role === "system")?.content]
    .filter(Boolean)
    .join("\n\n");
}

export function buildComparableAttachments(input: unknown): ChatAttachment[] {
  if (!Array.isArray(input)) return [];

  const attachments: ChatAttachment[] = [];
  for (const entry of input) {
    if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
    const record = entry as Record<string, unknown>;
    const kind = record.kind;
    const id = typeof record.id === "string" ? record.id : "";
    const filename = typeof record.filename === "string" ? record.filename : "";
    const mimeType = typeof record.mimeType === "string" ? record.mimeType : "";
    const sizeBytes = typeof record.sizeBytes === "number" ? record.sizeBytes : 0;

    if (kind === "image" && typeof record.dataUrl === "string") {
      attachments.push({
        kind,
        id,
        filename,
        mimeType: mimeType === "image/png" ? "image/png" : "image/jpeg",
        sizeBytes,
        dataUrl: record.dataUrl,
      });
      continue;
    }

    if (kind === "text" && typeof record.text === "string") {
      attachments.push({
        kind,
        id,
        filename,
        mimeType,
        sizeBytes,
        text: record.text,
        truncated: record.truncated === true,
      });
    }
  }

  return attachments;
}
