import type { Persona } from "../domain/types";
import { buildPersonaPromptBlock, isPersonaReady, toneOf } from "./personaPrompt";

/** Tiny delay so mock AI buttons feel async */
export function mockDelay(ms = 450): Promise<void> {
  return new Promise((resolve) => window.setTimeout(resolve, ms));
}

export function voiceLabel(persona?: Persona | null): string {
  return persona?.name || "預設語氣";
}

function clip(s: string, n: number): string {
  const t = s.trim();
  return t.length > n ? `${t.slice(0, n)}…` : t;
}

function fingerprintBits(persona?: Persona | null) {
  const d = persona?.style?.draft;
  return {
    tone: toneOf(persona),
    hooks: d?.hooks || "先丟痛點再問",
    fingerprint: d?.languageFingerprint || "口語短句",
    rhythm: d?.rhythm || "2～3 短段",
    examples: d?.examples || "",
    avoid: d?.avoid || persona?.guard?.avoid?.join("、") || "硬廣",
    cta: d?.ctaStyle || "輕輕問一句",
    audience: d?.audience || "會求經驗的人",
  };
}

/** 產出時附帶使用的人設 block（除錯／預覽用） */
export function explainPersonaUsage(persona?: Persona | null, mode: "post" | "reply" | "outreach" | "inspire" = "post") {
  return {
    ready: isPersonaReady(persona),
    name: persona?.name || "（未選）",
    block: buildPersonaPromptBlock(persona, mode),
  };
}

export function mockGenerateTopic(seed: string, persona?: Persona | null): string {
  const b = fingerprintBits(persona);
  const base = seed.trim() || "日常小發現";
  return [
    `（視角：${persona?.name || "預設"} · ${b.tone}）`,
    `${b.hooks}：最近卡在「${base}」。`,
    `想聽 ${b.audience} 的真實經驗——不是規格文。`,
    `用字偏向：${b.fingerprint}`,
  ].join("\n");
}

export function mockGenerateRoot(topic: string, persona?: Persona | null): string {
  const b = fingerprintBits(persona);
  const t = topic.trim() || "一個大家會想回的小題目";
  const body = [
    clip(t, 120),
    "",
    `我自己目前卡在「有沒有實際用過、會不會踩雷」。`,
    b.examples ? `（像我會說的：${clip(b.examples, 48)}）` : "",
    b.cta,
  ]
    .filter(Boolean)
    .join("\n");
  return `（${b.tone} · 避開：${clip(b.avoid, 24)}）\n${body}`;
}

export function mockGenerateReply(opts: {
  context: string;
  speakerName: string;
  /** 有才套用語氣；沒有就中性口吻 */
  persona?: Persona | null;
  /** 有才輕帶品牌視角；沒有就不提 */
  brandName?: string;
  brandBrief?: string;
  isLead?: boolean;
}): string {
  const { context, speakerName, persona, brandName, brandBrief, isLead } = opts;
  const hasPersona = Boolean(persona);
  const b = fingerprintBits(persona);
  const clipCtx = clip(context, 48) || "前面那則";
  const head = hasPersona ? `（${speakerName} · ${b.tone}）` : `（${speakerName}）`;
  const brandLine =
    brandName && brandBrief
      ? `補充一點 ${brandName} 相關經驗：${clip(brandBrief, 48)}`
      : brandName
        ? `補充一點和 ${brandName} 有關的實際用法。`
        : "";

  if (isLead) {
    return [
      head,
      `懂你說的「${clipCtx}」。`,
      brandLine || "想再問一句：你實際怎麼選的？",
      hasPersona ? `（避開 ${clip(b.avoid, 24)}）` : "",
    ]
      .filter(Boolean)
      .join("\n");
  }
  return [
    head,
    brandLine || `我這邊經驗是：${clipCtx} 真的有差。`,
    brandLine ? `對「${clipCtx}」這點，務實做法通常是先對情境再對規格。` : "如果在意使用情境，我可以再補細節。",
    hasPersona ? `用字：${b.fingerprint}` : "",
  ]
    .filter(Boolean)
    .join("\n");
}

export function mockGenerateOwnPostReply(opts: {
  postText: string;
  replyText?: string;
  persona?: Persona | null;
}): string {
  const b = fingerprintBits(opts.persona);
  const target = clip(opts.replyText || opts.postText, 40);
  return [
    `（作者本人 · ${b.tone}）`,
    `懂你說的「${target}」。`,
    `我自己是先抓痛點再對規格，通常看使用情境而不是只看規格表。`,
    `你比較在意哪一點？`,
    opts.persona?.guard?.banAiTone ? "（已關 AI 腔／客服腔）" : "",
  ]
    .filter(Boolean)
    .join("\n");
}

export function mockGenerateScoutDraft(opts: {
  postText: string;
  brandName: string;
  brandBrief?: string;
  targetAudience?: string;
  productLabel?: string;
  productContext?: string;
  painHint?: string;
  placementUrl?: string;
  persona?: Persona | null;
  /** theme = 接話；product = 可輕帶解法；activity = 短回養帳號 */
  mode?: "product" | "theme" | "activity";
}): string {
  const b = fingerprintBits(opts.persona);
  const clipPost = clip(opts.postText, 36);
  const mode = opts.mode || (opts.productLabel ? "product" : "theme");

  if (mode === "activity") {
    return [
      `同感「${clipPost}」這段 🙌`,
      `我也常這樣，後來比較會先停一下再決定。`,
      `你現在比較偏哪一種狀態？`,
    ].join("\n");
  }

  if (mode === "theme") {
    return [
      `看到你聊「${clipPost}」——`,
      `我之前也卡過類似的點，後來比較有感的是先釐清自己在意什麼。`,
      `你現在最卡的是哪一段？可以再多講一點（真想聽，不是套公式）。`,
      opts.persona?.guard?.banAiTone ? "" : "",
    ]
      .filter(Boolean)
      .join("\n");
  }

  const lines = [
    `看到你提到「${clipPost}」很有感。`,
  ];
  if (opts.painHint) {
    lines.push(`這類「${clip(opts.painHint, 28)}」的情況，身邊也常聽到。`);
  }
  if (opts.productContext) {
    lines.push(clip(opts.productContext, 120));
  } else if (opts.productLabel) {
    lines.push(`我自己後來會先從「${opts.productLabel}」這類情境想解法，不一定一步到位。`);
  } else {
    lines.push(`整理經驗時也常遇到類似情況——可以分享一個比較務實的切入點（非業配）。`);
  }
  if (opts.placementUrl) {
    lines.push(opts.placementUrl);
  }
  lines.push(`你比較在意哪一點？`);
  if (b.tone) {
    // light fingerprint without fake meta banner
  }
  return lines.join("\n");
}

export function mockGenerateInspiration(
  topic: string,
  persona?: Persona | null,
): {
  title: string;
  hook: string;
  angle: string;
} {
  const b = fingerprintBits(persona);
  const t = topic.trim() || "生活小題";
  return {
    title: `${t} · ${persona?.name || "日常視角"}`,
    hook: `${b.hooks}（主題：${t}；對 ${b.audience}）`,
    angle:
      persona?.style?.dimensions?.d4Topics?.summary ||
      persona?.brief ||
      "先痛點、再經驗、最後輕帶觀點，避免一句廣告。",
  };
}
