import { api } from "../api/haixun";
import {
  mentionSurface,
  mentionThreadRootId,
  type ThreadsMentionHit
} from "./mentionInbox";

export type MediaSnippet = {
  id: string;
  label: string;
  text?: string;
  username?: string;
  permalink?: string;
  timestamp?: string;
  media_type?: string;
};

export type MentionContext = {
  status: "loading" | "ok" | "error";
  root?: MediaSnippet;
  parent?: MediaSnippet;
  message?: string;
};

function parseMediaDetail(data: string): MediaSnippet | null {
  const trimmed = data.trim();
  if (!trimmed) return null;
  try {
    const row = JSON.parse(trimmed) as Record<string, unknown>;
    const id = String(row.id || "").trim();
    if (!id) return null;
    return {
      id,
      label: "",
      text: typeof row.text === "string" ? row.text : undefined,
      username: typeof row.username === "string" ? row.username : undefined,
      permalink: typeof row.permalink === "string" ? row.permalink : undefined,
      timestamp: typeof row.timestamp === "string" ? row.timestamp : undefined,
      media_type: typeof row.media_type === "string" ? row.media_type : undefined
    };
  } catch {
    return null;
  }
}

async function fetchMediaSnippet(accountId: string, mediaId: string, label: string): Promise<MediaSnippet | null> {
  const result = await api.threadsPlayground(accountId, {
    action: "media_detail",
    media_id: mediaId
  });
  if (!result.ok) return null;
  const snippet = parseMediaDetail(result.data);
  if (!snippet) return null;
  return { ...snippet, label };
}

export function buildMentionAiPayload(hit: ThreadsMentionHit, context?: MentionContext) {
  const surface = mentionSurface(hit);
  const mentionText = (hit.text || "").trim();
  const cachedThread = (hit.thread_post_text || "").trim();
  const cachedParent = (hit.parent_reply_text || "").trim();

  if (surface === "post") {
    return {
      thread_post_text: mentionText,
      parent_reply_text: "",
      reply_text: mentionText,
      post_text: mentionText
    };
  }

  if (cachedThread || cachedParent) {
    return {
      thread_post_text: cachedThread || mentionText,
      parent_reply_text: cachedParent,
      reply_text: mentionText,
      post_text: cachedThread || mentionText
    };
  }

  const threadText = (context?.root?.text || "").trim();
  const parentText = (context?.parent?.text || "").trim();

  return {
    thread_post_text: threadText || mentionText,
    parent_reply_text: parentText,
    reply_text: mentionText,
    post_text: threadText || mentionText
  };
}

export function cachedMentionContext(hit: ThreadsMentionHit): MentionContext | null {
  const surface = mentionSurface(hit);
  if (surface === "post") {
    return { status: "ok" };
  }

  const threadText = (hit.thread_post_text || "").trim();
  if (!threadText) {
    return null;
  }

  const rootId = mentionThreadRootId(hit);
  const context: MentionContext = {
    status: "ok",
    root: {
      id: rootId,
      label: surface === "quote" ? "被引用的原文" : "主串貼文",
      text: threadText
    }
  };

  const parentText = (hit.parent_reply_text || "").trim();
  const parentId = (hit.parent_id || "").trim();
  if (surface === "reply" && parentText && parentId) {
    context.parent = {
      id: parentId,
      label: "上層留言",
      text: parentText
    };
  }

  return context;
}

export async function loadMentionContext(accountId: string, hit: ThreadsMentionHit): Promise<MentionContext> {
  const surface = mentionSurface(hit);
  if (surface === "post") {
    return { status: "ok" };
  }

  const rootId = mentionThreadRootId(hit);
  if (!rootId) {
    return { status: "error", message: "找不到主串貼文 ID" };
  }

  try {
    const root = await fetchMediaSnippet(accountId, rootId, surface === "quote" ? "被引用的原文" : "主串貼文");
    if (!root) {
      return { status: "error", message: "無法載入主串原文（可能權限或貼文已刪除）" };
    }

    let parent: MediaSnippet | undefined;
    const parentId = (hit.parent_id || "").trim();
    if (surface === "reply" && parentId && parentId !== hit.id && parentId !== rootId) {
      const loaded = await fetchMediaSnippet(accountId, parentId, "上層留言");
      if (loaded) parent = loaded;
    }

    return { status: "ok", root, parent };
  } catch (err) {
    return {
      status: "error",
      message: err instanceof Error ? err.message : "載入原文失敗"
    };
  }
}