import html
import json
import re
from pathlib import Path

from pypdf import PdfReader

MODULE_ID = "tomo-de-magia-od2"
ROOT = Path(__file__).resolve().parents[1]
OUTPUT = ROOT / "data" / "rules.json"

SOURCES = [
    {
        "id": "divine-rules",
        "title": "Regras de Magia Divina",
        "pdfTitle": "Tomo de Magia Divina - OD2",
        "pdfPath": "/Volumes/rMacMiniM4/rsardinha/Downloads/Tomo de Magia Divina - OD2.pdf",
        "assetPath": f"modules/{MODULE_ID}/assets/pdfs/tomo-de-magia-divina-od2.pdf",
        "startPage": 7,
        "endPage": 23,
    },
    {
        "id": "arcane-rules",
        "title": "Regras de Magia Arcana",
        "pdfTitle": "Tomo da Magia Arcana - OD2",
        "pdfPath": "/Volumes/rMacMiniM4/organizar/Downloads/Tomo da Magia Arcana - OD2.pdf",
        "assetPath": f"modules/{MODULE_ID}/assets/pdfs/tomo-da-magia-arcana-od2.pdf",
        "startPage": 7,
        "endPage": 25,
    },
]


def clean_text(text):
    text = text.replace("\u00a0", " ")
    text = re.sub(r"-\s*\n\s*", "", text)
    text = re.sub(r"[ \t]+", " ", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def page_to_html(page_number, text):
    text = clean_text(text)
    if not text:
        return f"<h2>Pagina {page_number}</h2><p><em>Sem texto extraivel nesta pagina.</em></p>"

    paragraphs = [p.strip() for p in re.split(r"\n\s*\n", text) if p.strip()]
    if len(paragraphs) == 1:
        paragraphs = [p.strip() for p in re.split(r"(?<=[.!?])\s+(?=[A-ZÁÉÍÓÚÂÊÔÃÕÇ])", paragraphs[0]) if p.strip()]

    body = "\n".join(f"<p>{html.escape(paragraph)}</p>" for paragraph in paragraphs)
    return f"<h2>Pagina {page_number}</h2>\n{body}"


def extract_source(source):
    reader = PdfReader(source["pdfPath"])
    pages = []
    for page_number in range(source["startPage"], source["endPage"] + 1):
        index = page_number - 1
        text = reader.pages[index].extract_text() or ""
        pages.append(
            {
                "pageNumber": page_number,
                "content": page_to_html(page_number, text),
            }
        )

    return {
        "id": source["id"],
        "title": source["title"],
        "pdfTitle": source["pdfTitle"],
        "assetPath": source["assetPath"],
        "startPage": source["startPage"],
        "endPage": source["endPage"],
        "pages": pages,
    }


def build():
    data = {
        "moduleId": MODULE_ID,
        "rules": [extract_source(source) for source in SOURCES],
    }
    OUTPUT.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"Wrote {OUTPUT}")
    for rule in data["rules"]:
        print(f"{rule['title']}: {rule['startPage']}-{rule['endPage']} ({len(rule['pages'])} pages)")


if __name__ == "__main__":
    build()
