import type { Brand, InspireAngle, Persona, TrendItem } from "../domain/types";
import { newId } from "./id";
import { mockDelay } from "./mockAi";
import { isPersonaReady, toneOf } from "./personaPrompt";

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

/**
 * 針對一則熱點產 3 個開場角度。
 * 人設／品牌選填：有且可用才餵進語氣／品牌視角。
 */
export async function mockGenerateInspireAngles(opts: {
  trend: TrendItem;
  persona?: Persona | null;
  brand?: Brand | null;
}): Promise<InspireAngle[]> {
  await mockDelay(650);
  const { trend } = opts;
  const label = trend.label.replace(/^#/, "");
  const sample = trend.samples[0] || trend.summary;
  const persona = opts.persona && isPersonaReady(opts.persona) ? opts.persona : null;
  const brand = opts.brand || null;
  const tone = persona ? toneOf(persona) : "";
  const brandBit = brand?.brief
    ? clip(brand.brief, 36)
    : brand?.display_name
      ? brand.display_name
      : "";

  const a1 = persona
    ? `（${tone}）看到大家都在聊 ${trend.label}——${clip(sample, 40)} 你實際怎麼處理？`
    : `${trend.label} 最近很吵：${clip(sample, 42)} 有人也是嗎？`;

  const a2 = brandBit
    ? `講 ${label} 時大家常忽略一點：${brandBit}。我自己的經驗是…`
    : `先別急著結論 ${label}。我比較想聽「真正踩過雷」的人怎麼說。`;

  const a3 =
    trend.keywords[0] != null
      ? `一句話：${trend.keywords[0]} 到底卡在哪？留言區求不業配的真實答案。`
      : `如果只能給 ${label} 一個實用建議，你會說什麼？`;

  return [
    { id: newId("ang"), hook: a1 },
    { id: newId("ang"), hook: a2 },
    { id: newId("ang"), hook: a3 },
  ];
}

/** 搜尋關鍵字當臨時熱點，走同一套角度流 */
export function trendFromQuery(query: string): TrendItem {
  const q = query.trim() || "熱門";
  const now = Date.now() * 1_000_000;
  return {
    id: newId("trend"),
    kind: "threads_tag",
    label: q.startsWith("#") ? q : `#${q.replace(/\s+/g, "")}`,
    summary: `與「${q}」相關的 Threads 討論`,
    heat: 70,
    keywords: [q],
    samples: [`最近一直刷到「${q}」，求經驗`],
    source_label: "搜尋",
    observed_at: now,
  };
}
