#!/usr/bin/env python3
"""
Heidelberg UB METS-based downloader for Pal.lat manuscripts.
Bypass for Vatican DigiVatLib when the main server blocks/503s.

Usage:
    python download_heidelberg_mets.py --shelf 1298
    python download_heidelberg_mets.py --shelf 1362b --pages all --resolution MAX
    python download_heidelberg_mets.py --shelf 1268 --pages 5,10,50-60
    python download_heidelberg_mets.py --shelf 1298 --pages all --pdf
    python download_heidelberg_mets.py --list-maps         # scan wiglaf for map entries

Shelfmark convention: pass the Pal.lat number (e.g. "1298" or "1362b").
"""

import argparse
import os
import re
import sys
import time
import urllib.parse

import requests

BASE = "https://digi.ub.uni-heidelberg.de"
METS_URL_TPL = BASE + "/diglitData/mets/bav_pal_lat_{shelf}.xml"
HTML_URL_TPL = BASE + "/diglit/bav_pal_lat_{shelf}"
OUT_BASE = os.path.expanduser("~/research collection/manuscripts")
UA = "Mozilla/5.0 Honeycutt Ai Labs-VMS-research"
DELAY = 2.0  # Heidelberg rate-limits otherwise

HEADERS = {"User-Agent": UA, "Accept": "*/*"}


def fetch_mets(shelf: str) -> str:
    url = METS_URL_TPL.format(shelf=shelf)
    print(f"  METS: {url}")
    r = requests.get(url, headers=HEADERS, timeout=60, allow_redirects=True)
    r.raise_for_status()
    return r.text


def fetch_title(shelf: str) -> str:
    """Grab the <title> from the catalog HTML — gives rich content description."""
    url = HTML_URL_TPL.format(shelf=shelf)
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        m = re.search(r"<title>(.*?)</title>", r.text, re.DOTALL)
        if m:
            return re.sub(r"\s+", " ", m.group(1)).strip()
    except Exception:
        pass
    return ""


def parse_image_urls(mets_xml: str, resolution: str = "MAX") -> list[tuple[str, str]]:
    """
    Return list of (folio_label, image_url) pairs for the specified fileGrp USE.
    Resolutions available: DEFAULT, MAX, THUMBS, INTROIMAGE.
    """
    m = re.search(
        rf'<mets:fileGrp[^>]+USE="{resolution}"(.*?)</mets:fileGrp>',
        mets_xml, re.DOTALL,
    )
    if not m:
        return []
    grp = m.group(1)
    urls = re.findall(r'xlink:href="([^"]+\.(?:jpg|tif|png))"', grp)
    out = []
    for u in urls:
        # Extract folio label from URL (e.g. Pal.lat.1298.f.019r.jpg -> 019r)
        mm = re.search(r"\.f\.([^/]+?)\.jpg$", u)
        label = mm.group(1) if mm else os.path.basename(u)
        out.append((label, u))
    return out


def filter_body(pairs: list[tuple[str, str]]) -> list[tuple[str, str]]:
    """Strip binding/flyleaf/calibration artifacts."""
    skip = ["Einband", "Vorderspiegel", "Hinterspiegel", "schnitt",
            "Farbkeil", "ruecken", "Rücken"]
    return [(l, u) for l, u in pairs
            if not any(s.lower() in u.lower() for s in skip)]


def parse_range_spec(spec: str, total: int) -> list[int]:
    """Parse 'all', '1-10', '1,5,10', '1-10,15,20-25' into 1-indexed list."""
    if spec is None or spec.lower() == "all":
        return list(range(1, total + 1))
    selected: set[int] = set()
    for part in spec.split(","):
        part = part.strip()
        if not part:
            continue
        m = re.match(r"^(\d+)-(\d+)$", part)
        if m:
            a, b = int(m.group(1)), int(m.group(2))
            if a > b:
                a, b = b, a
            for i in range(a, b + 1):
                if 1 <= i <= total:
                    selected.add(i)
        elif part.isdigit():
            i = int(part)
            if 1 <= i <= total:
                selected.add(i)
        else:
            raise ValueError(f"Bad page spec fragment: {part!r}")
    return sorted(selected)


def download_one(url: str, dest: str) -> bool:
    try:
        r = requests.get(url, headers=HEADERS, timeout=120, stream=True)
        r.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in r.iter_content(chunk_size=16384):
                f.write(chunk)
        return True
    except Exception as e:
        print(f"    FAIL: {e}")
        return False


def assemble_pdf(out_dir: str, shelf: str, indices: list[int], pairs: list[tuple[str, str]]) -> str | None:
    try:
        from PIL import Image
    except ImportError:
        print("  ! PIL not installed; skip PDF assembly")
        return None
    paths = []
    for i in indices:
        label, _ = pairs[i - 1]
        p = os.path.join(out_dir, f"{label}.jpg")
        if os.path.exists(p) and os.path.getsize(p) > 0:
            paths.append(p)
    if not paths:
        return None
    pdf_path = os.path.join(out_dir, f"Pal_lat_{shelf}.pdf")
    print(f"  Assembling PDF: {pdf_path} ({len(paths)} pages)")
    first = Image.open(paths[0]).convert("RGB")
    rest = [Image.open(p).convert("RGB") for p in paths[1:]]
    first.save(pdf_path, save_all=True, append_images=rest, resolution=150.0)
    sz = os.path.getsize(pdf_path) / 1024 / 1024
    print(f"  PDF: {pdf_path} ({sz:.1f} MB)")
    return pdf_path


def list_maps_from_wiglaf():
    """Scan wiglaf.org Pal.lat page for map-like entries."""
    print("Fetching wiglaf.org Pal.lat index...")
    r = requests.get("https://www.wiglaf.org/vatican/fonds/Pal.lat.html",
                     headers=HEADERS, timeout=60)
    html = r.text
    rows = re.findall(
        r'<div class="mss_row grid-x">(.*?)</div><!-- close the row-->',
        html, re.DOTALL,
    )
    map_terms = ["weltkarte", "mappa", "mappae mundi", "mappamundi",
                 "world map", "map of", "carta ", "tabula peut",
                 "atlas", "portolan", "isolario", "geograph",
                 "cosmograph", "karte", "landkarte", "orbis terra",
                 "walsperger", "fra mauro", "ptolem"]
    print(f"\nMap-related Pal.lat entries from wiglaf.org:\n")
    found = []
    for row in rows:
        low = row.lower()
        hits = [t for t in map_terms if t in low]
        if not hits:
            continue
        # Shelfmark
        sm = re.search(r'Pal\.lat\.(\d+[a-z]?)', row)
        desc = re.search(r'<div class="notes">(.*?)</div>', row, re.DOTALL)
        inc = re.search(r'<div class="incipit">(.*?)</div>', row, re.DOTALL)
        if sm:
            shelf = sm.group(1)
            dtxt = re.sub(r"<[^>]+>", "", desc.group(1)).strip() if desc else ""
            itxt = re.sub(r"<[^>]+>", "", inc.group(1)).strip() if inc else ""
            dtxt = re.sub(r"\s+", " ", dtxt)[:180]
            itxt = re.sub(r"\s+", " ", itxt)[:100]
            found.append((shelf, hits, dtxt, itxt))
            print(f"  Pal.lat.{shelf}  [{','.join(hits)}]")
            if dtxt:
                print(f"    {dtxt}")
            if itxt:
                print(f"    incipit: {itxt}")
    print(f"\nTotal map-like entries: {len(found)}")
    return found


def main():
    ap = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    ap.add_argument("--shelf", help="Pal.lat shelfmark (e.g. 1298 or 1362b)")
    ap.add_argument("--pages", default="all", help="Page spec: all, 1-10, 1,5,10, 1-10,15,20-25")
    ap.add_argument("--resolution", default="MAX",
                    choices=["MAX", "DEFAULT", "THUMBS", "INTROIMAGE"])
    ap.add_argument("--pdf", action="store_true", help="Assemble PDF from downloaded images")
    ap.add_argument("--list-maps", action="store_true", help="List map-like Pal.lat from wiglaf")
    args = ap.parse_args()

    if args.list_maps:
        list_maps_from_wiglaf()
        return

    if not args.shelf:
        ap.print_help()
        sys.exit(1)

    shelf = args.shelf
    out_dir = os.path.join(OUT_BASE, f"HD_Pal_lat_{shelf}")
    os.makedirs(out_dir, exist_ok=True)
    print(f"\n{'='*60}\nPal.lat.{shelf}\n{'='*60}")

    title = fetch_title(shelf)
    if title:
        print(f"Title: {title}")

    mets = fetch_mets(shelf)
    with open(os.path.join(out_dir, "mets.xml"), "w") as f:
        f.write(mets)

    pairs = filter_body(parse_image_urls(mets, args.resolution))
    print(f"Body folios: {len(pairs)}")
    indices = parse_range_spec(args.pages, len(pairs))
    print(f"Will fetch: {len(indices)} at resolution={args.resolution}")

    ok = fail = 0
    for i in indices:
        label, url = pairs[i - 1]
        dest = os.path.join(out_dir, f"{label}.jpg")
        if os.path.exists(dest) and os.path.getsize(dest) > 0:
            print(f"  [{i}/{len(pairs)}] {label} — exists, skip")
            ok += 1
            continue
        print(f"  [{i}/{len(pairs)}] {label} ...", end=" ", flush=True)
        if download_one(url, dest):
            print(f"OK ({os.path.getsize(dest)/1024:.0f} KB)")
            ok += 1
        else:
            fail += 1
        time.sleep(DELAY)

    print(f"\nResult: {ok} succeeded, {fail} failed")
    if args.pdf and ok > 0:
        assemble_pdf(out_dir, shelf, indices, pairs)


if __name__ == "__main__":
    main()
