import { mockDelay } from "./mockAi";

/** 從商品連結「抓回來」後要填進表單的草稿（尚未存檔） */
export type ProductUrlDraft = {
  label: string;
  product_context: string;
  pain_points: string[];
  match_tags: string[];
  placement_url: string;
  /** mock 說明：live 會是後端爬頁 */
  source_note: string;
};

function slugToWords(slug: string): string[] {
  return slug
    .split(/[-_+/]+/)
    .map((s) => decodeURIComponent(s).trim())
    .filter((s) => s.length > 1 && !/^\d+$/.test(s) && !/^(www|com|tw|html|php|p|product|products|item|shop)$/i.test(s));
}

function titleCaseWords(words: string[]): string {
  return words
    .map((w) => {
      if (/[\u4e00-\u9fff]/.test(w)) return w;
      return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
    })
    .join(" ");
}

/** 依 URL 路徑／主機推估產品語意（mock；真抓頁屬 Phase C 後端） */
export async function mockImportProductFromUrl(rawUrl: string): Promise<ProductUrlDraft> {
  await mockDelay(900);
  const trimmed = rawUrl.trim();
  if (!trimmed) throw new Error("請貼上商品或官網連結");

  let url: URL;
  try {
    url = new URL(trimmed.includes("://") ? trimmed : `https://${trimmed}`);
  } catch {
    throw new Error("連結格式不正確");
  }

  const host = url.hostname.replace(/^www\./, "");
  const pathParts = url.pathname.split("/").filter(Boolean);
  const lastSlug = pathParts[pathParts.length - 1] || host.split(".")[0] || "product";
  const words = slugToWords(lastSlug.replace(/\.(html?|php)$/i, ""));
  const fromQuery =
    url.searchParams.get("name") ||
    url.searchParams.get("title") ||
    url.searchParams.get("q") ||
    "";
  const labelBase =
    (fromQuery && fromQuery.trim()) ||
    (words.length ? titleCaseWords(words.slice(0, 6)) : "") ||
    host.split(".")[0] ||
    "未命名商品";

  const blob = `${labelBase} ${words.join(" ")} ${host}`.toLowerCase();

  // 粗分類：用路徑關鍵字推痛點／tags（mock 啟發式）
  let pain_points: string[] = [];
  let match_tags: string[] = [...words.slice(0, 5)];
  let angle = "依商品頁摘要整理的賣點與使用情境（請再人工改準）。";

  if (/敏感|無香|香精|抗敏|unscent|sensitive|hypo/i.test(blob)) {
    pain_points = ["香精／氣味太重受不了", "皮膚或頭皮容易刺癢", "找不到真的溫和選項"];
    match_tags = [...new Set([...match_tags, "無香", "敏感肌", "溫和", "香精"])];
    angle = "主打低刺激／無香體驗；適合先講使用感受，再輕帶規格與通路。";
  } else if (/咖啡|cafe|coffee|插座|座位|第三空間/i.test(blob)) {
    pain_points = ["平日下午沒地方久坐", "店裡沒插座或趕客", "人多坐不久"];
    match_tags = [...new Set([...match_tags, "咖啡廳", "插座", "筆電", "不限時"])];
    angle = "強調座位與工作友善，分享實際待店經驗優於硬推商品。";
  } else if (/寶寶|嬰|幼兒|baby|kids/i.test(blob)) {
    pain_points = ["怕洗劑太刺激", "怕洗不乾淨", "不知道怎麼選成分"];
    match_tags = [...new Set([...match_tags, "寶寶", "溫和", "嬰幼兒"])];
    angle = "親子情境：務實講洗淨與溫和的取捨，避免恐嚇式行銷。";
  } else if (/洗|沐|護|detergent|shampoo|soap|skincare|保養/i.test(blob)) {
    pain_points = ["不知道適不適合自己膚況", "行銷話術看不懂", "用完反而不適"];
    match_tags = [...new Set([...match_tags, "選品", "成分", "使用心得"])];
    angle = "先對齊使用情境與頻率，再對規格；語氣務實不硬廣。";
  } else {
    pain_points = [`在找「${labelBase}」相關解法或真實心得`, "被行銷文搞混、想聽實際用過的人講"];
    if (!match_tags.length) match_tags = [labelBase, "推薦", "心得"];
    angle = `從「${labelBase}」商品頁推測的使用情境；請依真實賣點改寫。`;
  }

  const product_context = [`【${labelBase}】`, angle].join("\n");

  return {
    label: labelBase.slice(0, 48),
    product_context,
    pain_points,
    match_tags: match_tags.map((t) => t.slice(0, 24)).filter(Boolean).slice(0, 12),
    placement_url: url.toString(),
    source_note: "已填入，可再改",
  };
}
