"""Generate PDF: Trademark registry record (mimics HK IPD format)."""

from pathlib import Path
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor

from .cjk_font import register_cjk_font, _has_cjk


def generate(
    output_path: Path,
    ipd: dict,
    tm_number: str,
    tm_text: str,
    status: str,
    nice_class: str,
    class_description: str,
    applicant: str,
    applicant_address: str,
    agent: str,
    agent_address: str,
    filing_date: str,
    publication_date: str,
):
    """Generate a TM registry record PDF (mimicking 306457384.pdf)."""
    cjk = register_cjk_font()
    c = canvas.Canvas(str(output_path), pagesize=A4)
    w, h = A4

    def draw_text(x, y_pos, text, size=10, bold=False, centered=False):
        if _has_cjk(text) and cjk != "Helvetica":
            c.setFont(cjk, size)
        else:
            c.setFont("Helvetica-Bold" if bold else "Helvetica", size)
        if centered:
            c.drawCentredString(x, y_pos, text)
        else:
            c.drawString(x, y_pos, text)

    # ── Page 1: Basic Information ──────────────────────────────────

    # Header
    draw_text(w / 2, h - 45, ipd["chinese_name"], 11, bold=True, centered=True)
    draw_text(w / 2, h - 60, ipd["name"], 10, centered=True)
    draw_text(
        w / 2,
        h - 75,
        "The Government of the Hong Kong Special Administrative Region",
        9,
        centered=True,
    )

    # Divider
    c.setStrokeColor(HexColor("#333333"))
    c.line(50, h - 88, w - 50, h - 88)

    # Titles
    draw_text(w / 2, h - 108, "商標記錄", 12, bold=True, centered=True)
    draw_text(w / 2, h - 124, "Trade Mark Records", 12, bold=True, centered=True)

    # Section: Basic Information
    y = h - 150
    draw_text(50, y, "基本資料 Basic information", 10, bold=True)
    y -= 5
    c.line(50, y, w - 50, y)
    y -= 20

    value_x = 280

    fields_page1 = [
        ("[210/111]", "商標編號:\nTrade Mark No.:", tm_number),
        ("", "狀況:\nStatus:", status),
        ("", "商標文字:\nTrade Mark Text:", tm_text),
        ("[550]", "商標種類:\nMark Type:", "Ordinary"),
        ("[511]", "類別編號:\nClass No.:", nice_class),
        ("[511]", "貨品 / 服務說明:\nSpecification:", class_description),
    ]

    for code, label, value in fields_page1:
        if code:
            c.setFont("Helvetica", 8)
            c.drawString(50, y, code)

        # Draw bilingual label
        label_lines = label.split("\n")
        for i, ll in enumerate(label_lines):
            draw_text(105, y - (i * 14), ll, 9, bold=True)

        # Draw value
        draw_text(value_x, y, value, 10)
        if len(value) > 55:
            # Wrap
            draw_text(value_x, y, value[:55], 10)
            y -= 16
            draw_text(value_x, y, value[55:110], 10)

        y -= max(len(label_lines) * 14, 18) + 8

    # Dates section
    y -= 10
    draw_text(50, y, "日期 (日日-月月-年年年年)", 10, bold=True)
    c.setFont("Helvetica-Bold", 10)
    c.drawString(50, y - 14, "Dates (DD-MM-YYYY)")
    y -= 19
    c.line(50, y, w - 50, y)
    y -= 20

    date_fields = [
        ("[220]", "提交日期:\nDate of Filing:", filing_date),
        ("[442]", "公布獲接納註冊申請日期:\nDate of Publication:", publication_date),
    ]

    for code, label, value in date_fields:
        c.setFont("Helvetica", 8)
        c.drawString(50, y, code)
        label_lines = label.split("\n")
        for i, ll in enumerate(label_lines):
            draw_text(105, y - (i * 14), ll, 9, bold=True)
        draw_text(value_x, y, value, 10)
        y -= max(len(label_lines) * 14, 18) + 8

    # ── Page 2: Applicant/Owner ────────────────────────────────────
    c.showPage()
    y = h - 60

    draw_text(50, y, "申請人／擁有人", 10, bold=True)
    c.setFont("Helvetica-Bold", 10)
    c.drawString(50, y - 14, "Applicant/Owner")
    y -= 19
    c.line(50, y, w - 50, y)
    y -= 20

    owner_fields = [
        ("[730]", "姓名／名稱:\nName:", applicant),
        ("[730]", "地址:\nAddress:", applicant_address),
        ("[842]", "類別:\nType:", "Incorporated"),
        ("[842]", "公司成立為法團的所在地:\nPlace of Incorporation:", "HONG KONG"),
        (
            "[750]",
            "供送達文件的地址:\nAddress for Service:",
            f"{agent}\n{agent_address}",
        ),
        ("[740]", "代理人詳情:\nAgent's Details:", f"{agent}\n{agent_address}"),
    ]

    for code, label, value in owner_fields:
        c.setFont("Helvetica", 8)
        c.drawString(50, y, code)

        label_lines = label.split("\n")
        for i, ll in enumerate(label_lines):
            draw_text(105, y - (i * 14), ll, 9, bold=True)

        value_lines = value.split("\n")
        for i, vl in enumerate(value_lines):
            if len(vl) > 50:
                draw_text(value_x, y - (i * 14), vl[:50], 10)
                draw_text(value_x, y - ((i + 1) * 14), vl[50:100], 10)
            else:
                draw_text(value_x, y - (i * 14), vl, 10)

        y -= max(len(label_lines), len(value_lines)) * 14 + 12

    c.save()
