/** 我的貼文 → 寫一則／仿寫：跨頁帶參考文 + 結構分析（避免長文塞 URL） */

const KEY = "harbor.compose.bridge";
const DRAFT_KEY = "harbor.compose.draftBody";

export type ComposeMimicBridge = {
  sourceText: string;
  /** 結構化分析全文（formula_detail 優先） */
  structureNotes?: string;
  formulaSummary?: string;
  insight?: string;
  /** 來源貼文 id（可選，方便除錯） */
  fromPostId?: string;
  savedAt: number;
};

export function saveComposeMimicBridge(payload: Omit<ComposeMimicBridge, "savedAt">): void {
  const data: ComposeMimicBridge = { ...payload, savedAt: Date.now() };
  try {
    sessionStorage.setItem(KEY, JSON.stringify(data));
  } catch {
    // quota / private mode — ignore
  }
}

export function takeComposeMimicBridge(): ComposeMimicBridge | null {
  try {
    const raw = sessionStorage.getItem(KEY);
    if (!raw) return null;
    sessionStorage.removeItem(KEY);
    const parsed = JSON.parse(raw) as ComposeMimicBridge;
    if (!parsed || typeof parsed.sourceText !== "string") return null;
    // 超過 1 小時當過期
    if (parsed.savedAt && Date.now() - parsed.savedAt > 60 * 60 * 1000) return null;
    return parsed;
  } catch {
    return null;
  }
}

/** 任務頁／通知 → 寫一則：帶入仿寫完成的正文 */
export function saveComposeDraftBody(text: string): void {
  try {
    sessionStorage.setItem(DRAFT_KEY, JSON.stringify({ text, savedAt: Date.now() }));
  } catch {
    /* ignore */
  }
}

export function takeComposeDraftBody(): string | null {
  try {
    const raw = sessionStorage.getItem(DRAFT_KEY);
    if (!raw) return null;
    sessionStorage.removeItem(DRAFT_KEY);
    const parsed = JSON.parse(raw) as { text?: string; savedAt?: number };
    if (!parsed?.text) return null;
    if (parsed.savedAt && Date.now() - parsed.savedAt > 60 * 60 * 1000) return null;
    return String(parsed.text);
  } catch {
    return null;
  }
}

export function parseComposeMimicResultPayload(payload?: string): string {
  if (!payload) return "";
  try {
    const o = JSON.parse(payload) as { result_text?: string };
    return String(o.result_text ?? "").trim();
  } catch {
    return "";
  }
}

/** 把 insight / formula 合成給 LLM 的 structure notes */
export function buildStructureNotes(opts: {
  insight?: string;
  formulaSummary?: string;
  formulaDetail?: string;
}): string {
  const parts: string[] = [];
  if (opts.formulaDetail?.trim()) {
    parts.push(opts.formulaDetail.trim());
  } else {
    if (opts.insight?.trim()) parts.push(`【洞察】${opts.insight.trim()}`);
    if (opts.formulaSummary?.trim()) parts.push(`【鉤子／覆盤】${opts.formulaSummary.trim()}`);
  }
  return parts.join("\n").trim();
}
