#!/usr/bin/env python3
"""Structural checks for the book-profile docx probe.

Do not reuse verify_docx.py here: that script asserts website prefixes
(图2-), bilingual captions, and a callout still wrapped in a table.
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

from verify_docx import (
    check,
    mask_inside_tables,
    paragraphs_with_style,
    plain_text,
    read_document_xml,
)


def verify_book(docx_path: Path) -> list[tuple[bool, str]]:
    xml = read_document_xml(docx_path)
    outside, _inside = mask_inside_tables(xml)
    text = plain_text(xml)
    results: list[tuple[bool, str]] = []

    tight = re.search(r"见图\d+-\d+", text)
    dotted = re.search(r"图\s*\d+\.\d+", text)
    results.append(
        check(
            "TC-BOOK-NUM hyphen number",
            tight is not None and dotted is None,
            "expected 见图N-M and no dotted 图N.M",
        )
    )

    landscape = len(re.findall(r'w:orient="landscape"', xml))
    results.append(check("TC-LAND one landscape section", landscape == 1, f"count={landscape}"))

    empty_sect = len(re.findall(r"<w:sectPr\s*/>|<w:sectPr>\s*</w:sectPr>", xml))
    results.append(
        check(
            "TC-LAND no empty sectPr",
            empty_sect == 0,
            f"count={empty_sect}",
        )
    )

    portrait_close = 'w:w="11906" w:h="16838"'
    landscape_close = (
        '<w:footerReference w:type="default" r:id="rId14"/>'
        '<w:type w:val="nextPage"/>'
        '<w:pgSz w:w="16838" w:h="11906" w:orient="landscape"/>'
    )
    results.append(
        check(
            "TC-LAND portrait then landscape",
            portrait_close in xml and landscape_close in xml,
            "A4 nextPage pair with default footer rId14",
        )
    )

    note_at = xml.find("注：")
    source_at = xml.find("资料来源")
    land_at = xml.find('w:orient="landscape"')
    portrait_at = xml.find(portrait_close)
    results.append(
        check(
            "TC-LAND note inside landscape section",
            0 <= portrait_at < note_at < source_at < land_at,
            "注 and 资料来源 sit between the portrait close and the landscape close",
        )
    )

    for style, label in (("TuTi", "图题"), ("BiaoTi", "表题")):
        paras = paragraphs_with_style(xml, style)
        outside_n = len(paragraphs_with_style(outside, style))
        results.append(
            check(
                f"TC-CAP {label} outside table",
                len(paras) >= 1 and outside_n == len(paras),
                f"styled={len(paras)} outside={outside_n}",
            )
        )

    results.append(check("TC-TBL year cell", "年份" in text and "2024" in text, ""))
    results.append(check("TC-NOTE no raw TeX circled", r"\U2460" not in text and r"\U2460" not in xml, ""))
    return results


def main() -> int:
    if len(sys.argv) < 2:
        print("Usage: verify_book.py <path/to/book.docx>", file=sys.stderr)
        return 2

    docx_path = Path(sys.argv[1]).resolve()
    if not docx_path.is_file():
        print(f"File not found: {docx_path}", file=sys.stderr)
        return 2

    print(f"Verifying book probe: {docx_path}")
    failed = 0
    for ok, msg in verify_book(docx_path):
        print(msg)
        if not ok:
            failed += 1

    if failed:
        print(f"\n{failed} book check(s) failed.")
        return 1

    print("\nAll book-profile structural checks passed.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
