/**
 * Tử Vi Số · Section-by-section reading prompts
 *
 * For deep "đọc lá số chuyên sâu", we don't ask the model one open-ended
 * question — we drive 6 focused sections, each with its own system prompt
 * + palace-context payload. The result is a coherent, scannable reading
 * that mirrors how a real thầy luận lá số: Mệnh → Tài → Quan → Phối →
 * Tử/Phụ → Đại vận.
 *
 * Each section returns the message array ready to feed into
 * `provider.streamMessages()` — system + user.
 */
import type { Chart } from "@/lib/tuvi/engine";
import type { Horoscope } from "@/lib/tuvi/horoscope";
import type { ChatMessage } from "./provider";

export type SectionKey = "menh" | "tai-bach" | "quan-loc" | "phu-the" | "tu-tuc" | "dai-van";

export type Section = {
  key: SectionKey;
  title: string;
  description: string;
  /** Vietnamese palace name(s) we focus on for this section */
  palaceNames: string[];
};

export const SECTIONS: Section[] = [
  {
    key: "menh",
    title: "Cung Mệnh & Thân",
    description: "Tính cách cốt lõi, thiên hướng cuộc đời, ưu nhược điểm bẩm sinh.",
    palaceNames: ["Mệnh", "Thân"],
  },
  {
    key: "tai-bach",
    title: "Tài Bạch & Phúc Đức",
    description: "Tài chính, cách kiếm tiền, phúc khí gia đạo.",
    palaceNames: ["Tài Bạch", "Phúc Đức"],
  },
  {
    key: "quan-loc",
    title: "Quan Lộc & Thiên Di",
    description: "Sự nghiệp, công danh, di chuyển - xuất ngoại.",
    palaceNames: ["Quan Lộc", "Thiên Di"],
  },
  {
    key: "phu-the",
    title: "Phu Thê",
    description: "Hôn nhân, vợ/chồng, mối quan hệ tình cảm chính.",
    palaceNames: ["Phu Thê"],
  },
  {
    key: "tu-tuc",
    title: "Tử Tức & Phụ Mẫu",
    description: "Con cái, sinh sản, mối quan hệ với cha mẹ.",
    palaceNames: ["Tử Tức", "Phụ Mẫu"],
  },
  {
    key: "dai-van",
    title: "Đại Vận hiện tại",
    description: "Vận trình 10 năm đang đi, lưu niên năm hiện tại, lưu ý đáng chú ý.",
    palaceNames: ["Mệnh"], // re-uses Mệnh + adds horoscope context
  },
];

/**
 * Format a single palace into a compact textual block. Skips empty fields
 * to keep prompts short — every token costs.
 */
function formatPalace(chart: Chart, palaceName: string): string {
  const p = chart.palaces.find((x) => x.name === palaceName);
  if (!p) return `Cung ${palaceName}: (không tìm thấy)`;
  const stars: string[] = [];
  for (const s of p.majorStars) {
    let line = s.name;
    if (s.brightness) line += `(${s.brightness})`;
    if (s.mutagen) line += ` ★Hóa ${s.mutagen}`;
    stars.push(line);
  }
  for (const s of p.minorStars) {
    let line = s.name;
    if (s.mutagen) line += ` ★Hóa ${s.mutagen}`;
    stars.push(line);
  }
  for (const s of p.adjStars) {
    stars.push(s.name);
  }
  const flags: string[] = [];
  if (p.isBodyPalace) flags.push("[Thân]");
  if (p.isOriginalPalace) flags.push("[Bản cung]");
  return `Cung ${p.name} (${p.heavenlyStem} ${p.earthlyBranch}) ${flags.join(" ")}\n  Sao: ${
    stars.length ? stars.join(", ") : "(không sao)"
  }`;
}

/**
 * Common header that appears in every section system prompt — anchors the
 * model on identity, voice, and the global chart summary so each section
 * doesn't drift in tone.
 */
function commonHeader(chart: Chart): string {
  return `Bạn là một chuyên gia tử vi đẩu số có 30 năm kinh nghiệm, đang đọc lá số chuyên sâu cho khách người Việt.

Bối cảnh chung của lá số (đừng lặp lại trong câu trả lời):
- Họ tên: ${chart.fullName || "(không cung cấp)"}
- Giới tính: ${chart.gender}
- Ngày sinh dương: ${chart.solarDate} · Âm lịch: ${chart.lunarDate}
- Tứ trụ: ${chart.chineseDate}
- Cục mệnh: ${chart.fiveElements} · Mệnh chủ: ${chart.soulStar} · Thân chủ: ${chart.bodyStar}
- Con giáp: ${chart.zodiac}

Quy tắc viết:
1. Văn phong điềm đạm, có dẫn chứng cụ thể từ sao trong cung.
2. KHÔNG kể lại tổng quan lá số — đi thẳng vào chủ đề mục này.
3. Cấu trúc 3 đoạn:
   ① Phân tích sao chính + ý nghĩa (3-4 câu)
   ② Điểm mạnh hoặc lưu ý (2-3 câu)
   ③ Lời khuyên hành động cụ thể (1-2 câu)
4. Tránh sáo ngữ. Không dùng "tốt nhất là", "cẩn thận là tốt".
5. Không vượt quá 250 từ.
6. KHÔNG đưa lời khuyên y tế / pháp luật / tài chính cụ thể.`;
}

/**
 * Build the messages for a single section. `horoscope` is optional and
 * only used by the "dai-van" section.
 */
export function buildSectionMessages(args: {
  section: SectionKey;
  chart: Chart;
  horoscope?: Horoscope;
}): ChatMessage[] {
  const meta = SECTIONS.find((s) => s.key === args.section);
  if (!meta) throw new Error(`Unknown section: ${args.section}`);

  const palaceBlocks = meta.palaceNames.map((n) => formatPalace(args.chart, n)).join("\n\n");

  let userBody = `Hãy luận **${meta.title}** dựa trên các cung sau:\n\n${palaceBlocks}`;

  if (args.section === "dai-van" && args.horoscope) {
    const h = args.horoscope;
    const decadalCell = h.decadalTimeline.find((d) => d.isCurrent);
    userBody += `\n\nVận trình hiện tại (tuổi mụ ${h.age}):
- Đại vận: ${h.decadal.heavenlyStem} ${h.decadal.earthlyBranch} · cung ${decadalCell?.palaceName ?? "?"} · phạm vi tuổi ${decadalCell?.ageFrom}–${decadalCell?.ageTo}
- Lưu niên: ${h.yearly.heavenlyStem} ${h.yearly.earthlyBranch}
- Tiểu hạn: ${h.ageHan.heavenlyStem} ${h.ageHan.earthlyBranch}
- Tứ hóa đại vận: Lộc-${h.decadal.mutagen[0]} · Quyền-${h.decadal.mutagen[1]} · Khoa-${h.decadal.mutagen[2]} · Kỵ-${h.decadal.mutagen[3]}
- Hạn truyền thống năm: ${
      [
        h.hanVn.tamTai.active ? `Tam Tai (${h.hanVn.tamTai.label})` : null,
        h.hanVn.kimLau.active ? h.hanVn.kimLau.label : null,
        !h.hanVn.hoangOc.good ? `Hoàng Ốc (${h.hanVn.hoangOc.label})` : null,
        ...h.hanVn.fixed.filter((f) => f.active).map((f) => f.name),
      ]
        .filter(Boolean)
        .join(", ") || "không phạm hạn nào nặng"
    }

Hãy luận tập trung: 10 năm đại vận này có chủ đề gì, năm nay (lưu niên) tốt/xấu ra sao, có gì cần lưu ý đặc biệt.`;
  }

  return [
    { role: "system", content: commonHeader(args.chart) },
    { role: "user", content: userBody },
  ];
}
