"""生成智保通知识库手动测试 PDF。"""

from __future__ import annotations

from pathlib import Path
from typing import Any

from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_JUSTIFY, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
    BaseDocTemplate,
    Frame,
    KeepTogether,
    PageBreak,
    PageTemplate,
    Paragraph,
    Spacer,
    Table,
    TableStyle,
)
from pypdf import PdfReader


ROOT = Path(__file__).resolve().parents[1]
OUTPUT_DIR = ROOT / "knowledge" / "test-pdfs"
BLUE = colors.HexColor("#146CE5")
NAVY = colors.HexColor("#10213A")
MUTED = colors.HexColor("#65778D")
LIGHT_BLUE = colors.HexColor("#EDF5FF")
LINE = colors.HexColor("#D7E3F0")
GREEN = colors.HexColor("#16836C")


def register_fonts() -> tuple[str, str]:
    regular_candidates = (
        Path("C:/Windows/Fonts/msyh.ttc"),
        Path("C:/Windows/Fonts/simsun.ttc"),
    )
    bold_candidates = (
        Path("C:/Windows/Fonts/msyhbd.ttc"),
        Path("C:/Windows/Fonts/simhei.ttf"),
    )
    regular = next((path for path in regular_candidates if path.exists()), None)
    bold = next((path for path in bold_candidates if path.exists()), regular)
    if regular is None or bold is None:
        raise FileNotFoundError("未找到可用的中文字体")
    pdfmetrics.registerFont(TTFont("ZBT-Regular", str(regular)))
    pdfmetrics.registerFont(TTFont("ZBT-Bold", str(bold)))
    return "ZBT-Regular", "ZBT-Bold"


REGULAR_FONT, BOLD_FONT = register_fonts()


class ZBTDocument(BaseDocTemplate):
    def __init__(self, filename: Path, *, title: str, document_code: str) -> None:
        super().__init__(
            str(filename),
            pagesize=A4,
            leftMargin=22 * mm,
            rightMargin=22 * mm,
            topMargin=25 * mm,
            bottomMargin=22 * mm,
            title=title,
            author="智保通",
            subject="智保通知识库本地测试资料",
        )
        self.document_title = title
        self.document_code = document_code
        frame = Frame(
            self.leftMargin,
            self.bottomMargin,
            self.width,
            self.height,
            id="content",
        )
        self.addPageTemplates(
            [
                PageTemplate(
                    id="zbt",
                    frames=[frame],
                    onPage=self._draw_page,
                )
            ]
        )

    def _draw_page(self, canvas: Any, doc: Any) -> None:
        width, height = A4
        canvas.saveState()
        canvas.setFillColor(BLUE)
        canvas.rect(0, height - 10 * mm, width, 10 * mm, fill=1, stroke=0)
        canvas.setFont(BOLD_FONT, 9)
        canvas.setFillColor(colors.white)
        canvas.drawString(22 * mm, height - 6.5 * mm, "智保通  ZHIBAOTONG")
        canvas.setFont(REGULAR_FONT, 7.5)
        canvas.drawRightString(
            width - 22 * mm,
            height - 6.5 * mm,
            self.document_code,
        )
        canvas.setStrokeColor(LINE)
        canvas.line(22 * mm, 15 * mm, width - 22 * mm, 15 * mm)
        canvas.setFillColor(MUTED)
        canvas.setFont(REGULAR_FONT, 7.5)
        canvas.drawString(22 * mm, 10 * mm, "仅用于智保通本地项目测试，不构成真实保险合同或承诺")
        canvas.drawRightString(width - 22 * mm, 10 * mm, f"第 {doc.page} 页")
        canvas.restoreState()


styles = getSampleStyleSheet()
TITLE = ParagraphStyle(
    "ZBTTitle",
    parent=styles["Title"],
    fontName=BOLD_FONT,
    fontSize=25,
    leading=34,
    textColor=NAVY,
    alignment=TA_LEFT,
    spaceAfter=8 * mm,
)
SUBTITLE = ParagraphStyle(
    "ZBTSubtitle",
    parent=styles["Normal"],
    fontName=REGULAR_FONT,
    fontSize=10,
    leading=18,
    textColor=MUTED,
    spaceAfter=6 * mm,
)
H1 = ParagraphStyle(
    "ZBTH1",
    parent=styles["Heading1"],
    fontName=BOLD_FONT,
    fontSize=16,
    leading=22,
    textColor=NAVY,
    borderColor=BLUE,
    borderWidth=0,
    borderPadding=(0, 0, 0, 8),
    spaceBefore=3 * mm,
    spaceAfter=2 * mm,
)
H2 = ParagraphStyle(
    "ZBTH2",
    parent=styles["Heading2"],
    fontName=BOLD_FONT,
    fontSize=11,
    leading=17,
    textColor=BLUE,
    spaceBefore=3 * mm,
    spaceAfter=2 * mm,
)
BODY = ParagraphStyle(
    "ZBTBody",
    parent=styles["BodyText"],
    fontName=REGULAR_FONT,
    fontSize=9.5,
    leading=18,
    textColor=NAVY,
    alignment=TA_JUSTIFY,
    spaceAfter=2.5 * mm,
)
BULLET = ParagraphStyle(
    "ZBTBullet",
    parent=BODY,
    leftIndent=5 * mm,
    firstLineIndent=-3.5 * mm,
    bulletIndent=0,
    spaceAfter=1.5 * mm,
)
SMALL = ParagraphStyle(
    "ZBTSmall",
    parent=BODY,
    fontSize=8,
    leading=14,
    textColor=MUTED,
    alignment=TA_LEFT,
)
COVER_CODE = ParagraphStyle(
    "ZBTCoverCode",
    parent=BODY,
    fontName=BOLD_FONT,
    fontSize=9,
    textColor=BLUE,
    alignment=TA_CENTER,
)
TABLE_HEAD = ParagraphStyle(
    "ZBTTableHead",
    parent=BODY,
    fontName=BOLD_FONT,
    fontSize=8.5,
    leading=13,
    textColor=colors.white,
    alignment=TA_CENTER,
)
TABLE_CELL = ParagraphStyle(
    "ZBTTableCell",
    parent=BODY,
    fontSize=8.2,
    leading=13,
    alignment=TA_LEFT,
    spaceAfter=0,
)


def p(text: str, style: ParagraphStyle = BODY) -> Paragraph:
    return Paragraph(text, style)


def bullet(text: str) -> Paragraph:
    return Paragraph(f"•&nbsp;&nbsp;{text}", BULLET)


def data_table(rows: list[list[str]], widths: list[float]) -> Table:
    content = [
        [p(cell, TABLE_HEAD if index == 0 else TABLE_CELL) for cell in row]
        for index, row in enumerate(rows)
    ]
    table = Table(content, colWidths=widths, repeatRows=1, hAlign="LEFT")
    table.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (-1, 0), BLUE),
                ("TEXTCOLOR", (0, 0), (-1, 0), colors.white),
                ("BACKGROUND", (0, 1), (-1, -1), colors.white),
                ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#F7FAFE")]),
                ("GRID", (0, 0), (-1, -1), 0.5, LINE),
                ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                ("LEFTPADDING", (0, 0), (-1, -1), 7),
                ("RIGHTPADDING", (0, 0), (-1, -1), 7),
                ("TOPPADDING", (0, 0), (-1, -1), 7),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
            ]
        )
    )
    return table


def cover(
    title: str,
    subtitle: str,
    document_code: str,
    document_type: str,
    version: str,
) -> list[Any]:
    badge = Table(
        [[p(document_type, COVER_CODE), p(version, COVER_CODE), p("本地测试资料", COVER_CODE)]],
        colWidths=[48 * mm, 48 * mm, 48 * mm],
    )
    badge.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (-1, -1), LIGHT_BLUE),
                ("BOX", (0, 0), (-1, -1), 0.7, colors.HexColor("#B9D3F4")),
                ("INNERGRID", (0, 0), (-1, -1), 0.5, colors.HexColor("#C9DCF4")),
                ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                ("TOPPADDING", (0, 0), (-1, -1), 9),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 9),
            ]
        )
    )
    notice = Table(
        [[p("资料说明", H2), p("文档内容为智保通本地项目的虚构测试数据，用于验证 PDF 解析、文本切分、向量检索、重排与来源引用。", SMALL)]],
        colWidths=[32 * mm, 112 * mm],
    )
    notice.setStyle(
        TableStyle(
            [
                ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#F5F9FE")),
                ("BOX", (0, 0), (-1, -1), 0.7, LINE),
                ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
                ("LEFTPADDING", (0, 0), (-1, -1), 10),
                ("RIGHTPADDING", (0, 0), (-1, -1), 10),
                ("TOPPADDING", (0, 0), (-1, -1), 10),
                ("BOTTOMPADDING", (0, 0), (-1, -1), 10),
            ]
        )
    )
    return [
        Spacer(1, 20 * mm),
        p("ZBT KNOWLEDGE BASE", COVER_CODE),
        Spacer(1, 7 * mm),
        p(title, TITLE),
        p(subtitle, SUBTITLE),
        badge,
        Spacer(1, 16 * mm),
        notice,
        Spacer(1, 8 * mm),
        p(f"文档编号：{document_code}", SMALL),
        p("生效日期：2026年7月1日　　整理日期：2026年7月28日", SMALL),
        PageBreak(),
    ]


def build_document(
    filename: str,
    title: str,
    document_code: str,
    story: list[Any],
) -> None:
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    document = ZBTDocument(
        OUTPUT_DIR / filename,
        title=title,
        document_code=document_code,
    )
    document.build(story)


def build_senior_terms() -> None:
    title = "银龄守护医疗险条款摘要"
    code = "ZBT-KB-TERMS-001"
    story = cover(
        title,
        "面向50至75周岁人群的住院医疗保障测试条款",
        code,
        "保险条款",
        "V1.0",
    )
    story += [
        p("一、产品基本信息", H1),
        data_table(
            [
                ["项目", "约定内容"],
                ["投保年龄", "首次投保年龄为50至75周岁，以投保时的周岁年龄为准。"],
                ["保障期间", "一年，自电子保单载明的保障起期零时开始。"],
                ["等待期", "疾病住院等待期为30天；意外伤害导致的住院不设等待期。"],
                ["适用医院", "中国大陆境内二级及以上公立医院普通部。"],
                ["年度保额", "银龄标准计划年度医疗费用保额为100万元。"],
            ],
            [35 * mm, 109 * mm],
        ),
        p("二、保险责任", H1),
        p("在保险期间内，被保险人因疾病或意外伤害，经符合约定的医院诊断必须住院治疗，对其实际发生且合理必要的医疗费用，按本摘要约定计算保险金。"),
        bullet("住院医疗费用包括床位费、药品费、治疗费、检查检验费、手术费和护理费。"),
        bullet("年度免赔额为10,000元，同一保险期间内累计计算。"),
        bullet("经基本医疗保险结算后，超过免赔额的合规费用按80%比例赔付。"),
        bullet("未使用基本医疗保险结算的，超过免赔额部分按60%比例赔付。"),
        p("三、责任免除", H1),
        p("下列情形产生的费用不在本测试条款保障范围内：投保前已明确诊断的既往症、美容整形、健康体检、康复疗养、违法犯罪行为导致的伤害，以及在非约定医疗机构发生的费用。"),
        p("四、示例计算", H1),
        p("被保险人使用基本医疗保险结算后，个人承担的合规住院费用为30,000元。扣除10,000元年度免赔额后，可赔付金额为20,000 × 80% = 16,000元。"),
    ]
    build_document("01-银龄守护医疗险条款摘要.pdf", title, code, story)


def build_claim_service() -> None:
    title = "蓉惠医疗险服务申请指南"
    code = "ZBT-KB-SERVICE-002"
    story = cover(
        title,
        "医疗费用报销协助的申请入口、材料清单与处理时效",
        code,
        "服务规则",
        "V1.2",
    )
    story += [
        p("一、服务申请入口", H1),
        p("用户应登录智保通 H5，在“我的保障”中找到状态为“保障中”的保单，点击“发起保单服务”。“保单服务”页面仅用于查看申请记录、处理状态和运营人员反馈，不提供新的申请入口。"),
        p("二、申请时限", H1),
        p("建议用户在出院之日起10个自然日内提交服务申请。超过10日仍可提交，但可能因材料补充或信息核验延长处理时间。"),
        p("三、基础材料清单", H1),
        data_table(
            [
                ["材料", "要求", "常见问题"],
                ["医疗费用票据", "原件照片完整、金额和票据号码清晰", "图片裁切、反光或金额模糊"],
                ["住院费用清单", "包含费用项目、数量、单价和合计金额", "只上传首页，缺少明细页"],
                ["出院记录", "包含入院诊断、治疗经过和出院诊断", "患者姓名与保单不一致"],
                ["诊断证明", "由就诊医院出具并加盖有效印章", "缺少医院印章或诊断日期"],
                ["身份与账户信息", "按后续通知补充，不在首次票据识别阶段上传", "银行卡户名与被保险人不一致"],
            ],
            [32 * mm, 63 * mm, 49 * mm],
        ),
        p("四、智能识别与人工确认", H1),
        p("系统通过阿里云百炼调用 Qwen 多模态模型，识别医疗票据中的票据号码、医疗机构、就诊日期和费用金额。识别结果仅作为候选字段，用户必须对照原始票据逐项核对并确认。AI 识别结果不代表保险公司作出赔付承诺。"),
        p("五、处理状态说明", H1),
        data_table(
            [
                ["状态", "含义", "用户下一步"],
                ["待处理", "申请已提交，等待运营人员初步核验", "保持联系方式畅通"],
                ["已受理", "材料满足初步受理条件", "等待后续服务联系"],
                ["未受理", "申请不符合当前服务范围", "查看处理意见或咨询人工服务"],
            ],
            [31 * mm, 64 * mm, 49 * mm],
        ),
        p("六、处理时效", H1),
        bullet("运营人员应在申请提交后1个工作日内完成初步审核。"),
        bullet("状态为“已受理”的申请，工作人员通常在2个工作日内首次联系用户。"),
    ]
    build_document("02-蓉惠医疗险服务申请指南.pdf", title, code, story)


def build_family_accident() -> None:
    title = "家庭意外保障险产品说明"
    code = "ZBT-KB-PRODUCT-003"
    story = cover(
        title,
        "适合家庭成员统一配置的意外伤害保障测试资料",
        code,
        "产品说明",
        "V2.0",
    )
    story += [
        p("一、产品定位", H1),
        p("家庭意外保障险用于覆盖家庭成员在日常生活、通勤和休闲活动中遭受的意外伤害风险。家庭计划最多可纳入5名家庭成员，成员关系限本人、父母、配偶和子女。"),
        p("二、保障计划", H1),
        data_table(
            [
                ["保障项目", "个人计划", "家庭计划"],
                ["意外身故及伤残", "每人20万元", "每人20万元"],
                ["意外医疗", "每人2万元", "每人2万元"],
                ["意外住院津贴", "100元/天，年度最多30天", "100元/天，年度最多30天"],
                ["年度保费", "99元/年", "159元/年"],
                ["可保障人数", "1人", "最多5人"],
            ],
            [50 * mm, 47 * mm, 47 * mm],
        ),
        p("三、意外医疗费用规则", H1),
        bullet("每次事故免赔额为100元。"),
        bullet("属于当地基本医疗保险范围内的合理费用，扣除免赔额后按90%比例赔付。"),
        bullet("同一被保险人年度意外医疗累计赔付不超过20,000元。"),
        p("四、投保人与被保险人", H1),
        p("投保人应为具有完全民事行为能力的自然人。家庭计划中的被保险人可以是投保人本人、父母、配偶或子女。新增家庭成员时，应准确填写姓名、身份证号码及与投保人的关系。"),
        p("五、不保事项", H1),
        p("疾病导致的医疗费用、故意自伤、酒后驾驶、无有效驾驶证驾驶、高风险竞技运动以及战争或核辐射导致的损失不属于本产品的意外保障范围。"),
        p("六、典型场景", H1),
        p("被保险人因骑行摔伤产生合规意外医疗费用2,000元。扣除100元免赔额后，按90%计算，可赔付1,710元。"),
    ]
    build_document("03-家庭意外保障险产品说明.pdf", title, code, story)


def build_faq() -> None:
    title = "智保通投保与保单服务常见问题"
    code = "ZBT-KB-FAQ-004"
    story = cover(
        title,
        "覆盖投保、支付、电子保单、服务申请和数据安全的常见问题",
        code,
        "常见问题",
        "V1.0",
    )
    faq_items = [
        ("投保时可以修改联系电话吗？", "可以。投保页面默认带入登录手机号，用户可以修改为实际接收投保及服务通知的手机号。修改联系电话不会改变登录账号，订单仍归属于当前登录用户。"),
        ("支付完成后多久生成电子保单？", "本地模拟支付回调成功后，系统立即完成承保并生成电子保单。用户可以在“我的保障”中查看电子保单号、保障期限和保单状态。"),
        ("为什么有订单却没有保单？", "待支付、支付失败或已取消的订单不会生成有效保单。只有支付成功并完成承保的订单才会关联电子保单。"),
        ("从哪里发起保单服务？", "请在“我的保障”中选择状态为“保障中”的具体保单，点击“发起保单服务”。“保单服务”板块只展示申请记录和处理进度。"),
        ("AI 识别出的票据信息可以修改吗？", "可以。票据号码、医疗机构、就诊日期、费用金额和联系电话均应由用户核对，确认无误后再提交。"),
        ("申请未受理后应该怎么办？", "用户可以在服务记录中查看运营人员填写的处理意见；如需进一步了解原因，可联系人工服务。"),
        ("投保前取消是否收费？", "在订单尚未支付前可以放弃支付，不产生保费扣款。支付后的退保及退款属于后续保全业务，应以对应产品规则和系统处理结果为准。"),
        ("个人信息如何保护？", "身份证号码和手机号在后台展示时进行掩码处理，权限和数据范围由后端统一控制。敏感字段不应写入日志或智能体自由文本。"),
    ]
    story += [p("常见问题索引", H1)]
    for index, (question, answer) in enumerate(faq_items, start=1):
        story.append(
            KeepTogether(
                [
                    p(f"{index:02d}　{question}", H2),
                    p(answer),
                    Spacer(1, 1.5 * mm),
                ]
            )
        )
    build_document("04-智保通投保与保单服务常见问题.pdf", title, code, story)


def main() -> None:
    build_senior_terms()
    build_claim_service()
    build_family_accident()
    build_faq()
    expected_text = {
        "01-银龄守护医疗险条款摘要.pdf": ("等待期为30天", "免赔额为10,000元", "按80%比例赔付"),
        "02-蓉惠医疗险服务申请指南.pdf": (
            "出院之日起10个自然日",
            "阿里云百炼 · Qwen 多模态模型",
            "1个工作日内完成初步审核",
        ),
        "03-家庭意外保障险产品说明.pdf": (
            "5名家庭成员",
            "每次事故免赔额为100元",
            "按90%比例赔付",
        ),
        "04-智保通投保与保单服务常见问题.pdf": (
            "从哪里发起保单服务",
            "不会改变登录账号",
            "敏感字段不应写入日志",
        ),
    }
    for filename, phrases in expected_text.items():
        path = OUTPUT_DIR / filename
        reader = PdfReader(path)
        extracted = "\n".join(page.extract_text() or "" for page in reader.pages)
        normalized = "".join(extracted.split())
        missing = [
            phrase
            for phrase in phrases
            if "".join(phrase.split()) not in normalized
        ]
        if missing:
            raise RuntimeError(f"{filename} 文本提取校验失败：{missing}")
        print(
            f"{path.name}\t{len(reader.pages)} pages\t"
            f"{len(extracted)} chars\t{path.stat().st_size} bytes"
        )


if __name__ == "__main__":
    main()
