export type CtaType = "none" | "link" | "dm" | "follow";

export const CTA_TYPE_OPTIONS: Array<{ value: CtaType; label: string }> = [
  { value: "none", label: "（無）不主動帶 CTA" },
  { value: "link", label: "連結（選填網址）" },
  { value: "dm", label: "私訊" },
  { value: "follow", label: "追蹤" },
];

function normalizeCtaType(value: unknown): CtaType {
  return value === "link" || value === "dm" || value === "follow" ? value : "none";
}

export interface ProductContextFields {
  brand: string;
  product: string;
  features: string;
  /** 希望怎麼帶到產品，例如先共情、像朋友分享 */
  placementTone?: string;
  /** 留言要怎麼收尾的行動呼籲 */
  ctaType?: CtaType;
  /** 當 ctaType = link 時，可選填的網址；有填才會帶進留言 */
  ctaUrl?: string;
}

export const EMPTY_PRODUCT_CONTEXT: ProductContextFields = {
  brand: "",
  product: "",
  features: "",
  placementTone: "",
  ctaType: "none",
  ctaUrl: "",
};

export function parseProductContext(raw: string | null | undefined): ProductContextFields {
  if (!raw?.trim()) return { ...EMPTY_PRODUCT_CONTEXT };

  try {
    const parsed = JSON.parse(raw) as Partial<ProductContextFields>;
    if (parsed && typeof parsed === "object") {
      return {
        brand: parsed.brand?.trim() ?? "",
        product: parsed.product?.trim() ?? "",
        features: parsed.features?.trim() ?? "",
        placementTone: parsed.placementTone?.trim() ?? "",
        ctaType: normalizeCtaType(parsed.ctaType),
        ctaUrl: parsed.ctaUrl?.trim() ?? "",
      };
    }
  } catch {
    // legacy plain text
  }

  return {
    ...EMPTY_PRODUCT_CONTEXT,
    features: raw.trim(),
  };
}

export function serializeProductContext(fields: ProductContextFields): string {
  const brand = fields.brand.trim();
  const product = fields.product.trim();
  const features = fields.features.trim();
  const placementTone = fields.placementTone?.trim() ?? "";
  const ctaType = normalizeCtaType(fields.ctaType);
  const ctaUrl = fields.ctaUrl?.trim() ?? "";

  if (!brand && !product && !features && !placementTone && ctaType === "none" && !ctaUrl) {
    return "";
  }

  return JSON.stringify({ brand, product, features, placementTone, ctaType, ctaUrl });
}

/** 取出 CTA 設定，供留言生成判斷要不要帶網址／引導 */
export function getProductCta(raw: string | null | undefined): { ctaType: CtaType; ctaUrl: string } {
  const fields = parseProductContext(raw);
  const ctaType = normalizeCtaType(fields.ctaType);
  return {
    ctaType,
    ctaUrl: ctaType === "link" ? fields.ctaUrl?.trim() ?? "" : "",
  };
}

export function hasProductContext(raw: string | null | undefined): boolean {
  const fields = parseProductContext(raw);
  return !!(fields.brand || fields.product || fields.features);
}

export function formatProductContextForPrompt(raw: string | null | undefined): string {
  const fields = parseProductContext(raw);
  const lines: string[] = [];

  if (fields.brand) lines.push(`品牌：${fields.brand}`);
  if (fields.product) lines.push(`產品：${fields.product}`);
  if (fields.features) lines.push(`特色／能幫上忙的地方：${fields.features}`);
  if (fields.placementTone) lines.push(`置入語氣偏好：${fields.placementTone}`);

  return lines.length > 0 ? lines.join("\n") : "（尚未填寫品牌與產品資訊）";
}

/** 給 UI 顯示的單行摘要 */
export function summarizeProductContext(raw: string | null | undefined): string | null {
  const fields = parseProductContext(raw);
  const parts = [fields.brand, fields.product, fields.features].filter(Boolean);
  return parts.length > 0 ? parts.join(" · ") : null;
}