import { mockDelay } from "./mockAi";
import { nowUnixNano } from "./time";
import type { ExternalThreadTarget } from "../domain/types";

/** 正規化 Threads permalink（比對方案用） */
export function normalizeThreadUrl(raw: string): string {
  const trimmed = (raw || "").trim();
  if (!trimmed) return "";
  try {
    const withProto = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
    const u = new URL(withProto);
    const host = u.hostname.replace(/^www\./i, "").toLowerCase();
    // threads.com / threads.net 等
    let path = u.pathname.replace(/\/+$/, "") || "";
    return `https://${host}${path}`;
  } catch {
    return trimmed.split("?")[0].split("#")[0].replace(/\/+$/, "");
  }
}

/**
 * 從連結拆 shortcode / 作者。
 * 支援：
 * - https://www.threads.net/@user/post/CODE
 * - https://www.threads.com/@user/post/CODE
 * - https://www.threads.net/t/CODE （較少見）
 */
export function parseThreadsPermalink(raw: string): {
  url: string;
  shortcode?: string;
  author_username?: string;
} | null {
  const input = (raw || "").trim();
  if (!input) return null;

  let href = input;
  if (!/^https?:\/\//i.test(href)) href = `https://${href}`;

  let u: URL;
  try {
    u = new URL(href);
  } catch {
    return null;
  }

  const host = u.hostname.replace(/^www\./i, "").toLowerCase();
  if (!host.includes("threads.")) {
    // 仍允許貼完整 URL 當目標，但提示非標準
    if (!/threads/i.test(input)) return null;
  }

  const path = u.pathname;
  const postMatch = path.match(/\/@([^/]+)\/post\/([^/?#]+)/i);
  if (postMatch) {
    const author = postMatch[1]!;
    const code = postMatch[2]!;
    const url = normalizeThreadUrl(`https://www.threads.net/@${author}/post/${code}`);
    return { url, shortcode: code, author_username: author };
  }

  const tMatch = path.match(/\/t\/([^/?#]+)/i);
  if (tMatch) {
    const code = tMatch[1]!;
    const url = normalizeThreadUrl(`https://www.threads.net/t/${code}`);
    return { url, shortcode: code };
  }

  // 任意 threads 連結：至少當目標 URL
  if (host.includes("threads.")) {
    return { url: normalizeThreadUrl(href) };
  }

  return null;
}

const MOCK_SNIPPETS = [
  "最近有人推這套流程嗎？我試了兩週還在卡關…",
  "真心問：週末還有哪間不擠、有插座的店？",
  "敏感肌用這款會刺痛嗎？求真實心得不要業配腔。",
  "第一次自己發串，回覆要怎麼接才不像機器人？",
  "有人用過這招嗎？留言區好像很吵。",
];

function mockPreviewForCode(code: string, author?: string): string {
  let h = 0;
  const s = `${code}|${author || ""}`;
  for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
  const base = MOCK_SNIPPETS[h % MOCK_SNIPPETS.length]!;
  return author ? `@${author}：${base}` : base;
}

/**
 * mock 解析 Threads 連結 → 可掛互回的目標。
 * live 應改後端 resolve media id + 正文。
 */
export async function mockResolveThreadLink(rawUrl: string): Promise<ExternalThreadTarget> {
  await mockDelay(450);
  const parsed = parseThreadsPermalink(rawUrl);
  if (!parsed) {
    throw new Error("請貼有效的 Threads 連結（例如 https://www.threads.net/@user/post/…）");
  }
  const shortcode = parsed.shortcode || "unknown";
  return {
    url: parsed.url,
    raw_url: rawUrl.trim(),
    shortcode,
    author_username: parsed.author_username,
    text_preview: mockPreviewForCode(shortcode, parsed.author_username),
    // mock 假 numeric id，方便之後對齊 API
    media_id: `mock_${shortcode.replace(/[^a-zA-Z0-9]/g, "").slice(0, 12) || "post"}`,
    resolved_at: nowUnixNano(),
  };
}

export function externalTargetKey(target: Pick<ExternalThreadTarget, "url"> | string): string {
  const url = typeof target === "string" ? target : target.url;
  return normalizeThreadUrl(url);
}
