#!/usr/bin/env python3
"""
IIIF Manuscript Downloader for Honeycutt Ai Labs VMS Project
Downloads manuscript page images from IIIF manifests.

Usage:
    python download_iiif.py                              # all configured MSS
    python download_iiif.py --only KEY                   # one manuscript
    python download_iiif.py --only KEY --pages 1-20      # specific folios
    python download_iiif.py --only KEY --pages 1,5,10    # specific indices
    python download_iiif.py --only KEY --pages 1-10,15,20-25
    python download_iiif.py --only KEY --pdf             # assemble PDF after
    python download_iiif.py --manifest URL --key CUSTOM  # ad-hoc manifest
    python download_iiif.py --list                       # list configured keys
"""

import argparse
import json
import os
import re
import sys
import time

import requests

# ---------- Configuration ----------

MANUSCRIPTS = {
    # --- Vatican + Gallica + Bologna (original set) ---
    "Vat_lat_2462": {
        "manifest": "https://digi.vatlib.it/iiif/MSS_Vat.lat.2462/manifest.json",
        "description": "Jacopo Dondi, Aggregator Medicinarum (1355)",
    },
    "Vat_lat_6973": {
        "manifest": "https://digi.vatlib.it/iiif/MSS_Vat.lat.6973/manifest.json",
        "description": "Vat.lat.6973",
    },
    "Vat_lat_6974": {
        "manifest": "https://digi.vatlib.it/iiif/MSS_Vat.lat.6974/manifest.json",
        "description": "Vat.lat.6974",
    },
    "Bologna_Aldrovandi_153": {
        "manifest": "https://historica.unibo.it/server/iiif/08ad03ec-dd53-46d8-8472-e8ac4a1719a1/manifest",
        "description": "Bologna Aldrovandi ms. 153",
    },
    # --- MDZ Munich (BSB) ---
    "MDZ_Bede_Clm_14725": {
        "manifest": "https://api.digitale-sammlungen.de/iiif/presentation/v2/bsb00065777/manifest",
        "description": "Bede, De temporum ratione + Computus ecclesiasticus + indiction tables 779-836 - BSB Clm 14725 (342 canvases)",
    },
    "MDZ_Hermannus_Clm_14836": {
        "manifest": "https://api.digitale-sammlungen.de/iiif/presentation/v2/bsb00060096/manifest",
        "description": "Hermannus Contractus, De mensura astrolabii - BSB Clm 14836 (334 canvases)",
    },
    # --- e-codices St. Gall ---
    "StGall_csg_902": {
        "manifest": "https://www.e-codices.unifr.ch/metadata/iiif/csg-0902/manifest.json",
        "description": "St. Gall Cod. Sang. 902 - Hrabanus De computo + Greek Computus (9th c.)",
    },
    "StGall_csg_250": {
        "manifest": "https://www.e-codices.unifr.ch/metadata/iiif/csg-0250/manifest.json",
        "description": "St. Gall Cod. Sang. 250 - astronomical-computistical tables + constellations (late 9th c.)",
    },
    "StGall_csg_338": {
        "manifest": "https://www.e-codices.unifr.ch/metadata/iiif/csg-0338/manifest.json",
        "description": "St. Gall Cod. Sang. 338 - liturgical + computational tables (11th c.)",
    },
    "StGall_csg_378": {
        "manifest": "https://www.e-codices.unifr.ch/metadata/iiif/csg-0378/manifest.json",
        "description": "St. Gall Cod. Sang. 378 - calendar + computus + tropary (11th c.)",
    },
    # --- British Library (accessed via bl.digirati.io CDN post-cyberattack) ---
    "BL_Egerton_747": {
        "manifest": "https://bl.digirati.io/iiif/ark:/81055/vdc_100058663072.0x000001",
        "description": "BL Egerton 747 - Tractatus de herbis + medical texts, S. Italy c.1280-1310 (309 canvases)",
    },
    "BL_Sloane_4016": {
        "manifest": "https://bl.digirati.io/iiif/ark:/81055/vdc_100165172997.0x000001",
        "description": "BL Sloane 4016 - Italian Herbal, N. Italian group, c.1440 full-page plant miniatures (235 canvases) - CLOSEST VMS-BOTANICAL-LAYOUT PARALLEL IN WINDOW",
    },
    "BL_Egerton_2020_Carrara_Herbal": {
        "manifest": "https://bl.digirati.io/iiif/ark:/81055/vdc_100165162636.0x000001",
        "description": "BL Egerton 2020 - Carrara Herbal (Erbario Carrarese), Padova c.1390-1404 Italian translation of Serapion Junior (600 canvases)",
    },
    "BL_Cotton_Galba_E_IV": {
        "manifest": "https://bl.digirati.io/iiif/ark:/81055/vdc_100063638967.0x000001",
        "description": "BL Cotton MS Galba E IV - 12th c. scientific misc., ff.187-244 = earliest Hippocrates De aere, aqua et regionibus (515 canvases, fire-damaged)",
    },
    "BL_Harley_2897_Breviary": {
        "manifest": "https://bl.digirati.io/iiif/ark:/81055/vdc_100161511640.0x000001",
        "description": "BL Harley 2897 - Summer Breviary of John the Fearless + Margaret of Bavaria, Paris c.1413-1419 (933 canvases) - DIRECT BREVIARIUM EXEMPLAR IN VMS WINDOW, WITTELSBACH PROVENANCE",
    },
    # --- Heidelberg UB mirror of Pal.lat (Vatican DigiVatLib 503 workaround, via wiglaf.org index) ---
    # Pattern: https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_NNNN/iiif/manifest.json
    "HD_Pal_lat_1115": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1115/iiif/manifest.json",
        "description": "Pal.lat.1115 (Heidelberg mirror) - Avicenna + Hippocrates + Cermisone + Arnald de Villanova + al - Medical Sammelhs - Pavia/Padua 1430-1431 IN VMS WINDOW",
    },
    "HD_Pal_lat_1211": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1211/iiif/manifest.json",
        "description": "Pal.lat.1211 (Heidelberg mirror) - Medizinische Sammelband: Galen+Rasis+Mundinus+H.Bate+Arnald, late 14th c. / c.1400",
    },
    "HD_Pal_lat_1262": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1262/iiif/manifest.json",
        "description": "Pal.lat.1262 (Heidelberg mirror) - Consilium ad fluxum materiarum, 1451-1500, Swabia (Augsburg?) - Wittelsbach zone",
    },
    "HD_Pal_lat_1268": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1268/iiif/manifest.json",
        "description": "Pal.lat.1268 HQ (Heidelberg mirror) - Tossignano + Galeatus Sancta Sophia + Arnald + Marsilius: Receptae super Nono Almansoris Rasis, 1434 Vienna - VMS WINDOW",
    },
    "HD_Pal_lat_1277": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1277/iiif/manifest.json",
        "description": "Pal.lat.1277 (Heidelberg mirror) - ps-Thessalus Illustrated Herbarium, 1551-1600, southern Germany",
    },
    "HD_Pal_lat_1298": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1298/iiif/manifest.json",
        "description": "Pal.lat.1298 (Heidelberg mirror) - Medical Miscellaney (incipit: Quia ut ait Galenus VII terapenture methodi), 1464 Padua",
    },
    "HD_Pal_lat_1373": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1373/iiif/manifest.json",
        "description": "Pal.lat.1373 (Heidelberg mirror) - already in Honeycutt Ai Labs corpus",
    },
    "HD_Pal_lat_1389": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1389/iiif/manifest.json",
        "description": "Pal.lat.1389 (Heidelberg mirror) - Mathematisch-astronomische Sammelhandschrift, Deutschland 2nd half 14th c.",
    },
    "HD_Pal_lat_1417": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1417/iiif/manifest.json",
        "description": "Pal.lat.1417 (Heidelberg mirror) - Nimroth De astronomia dialogus, Italia 12th c.",
    },
    "HD_Pal_lat_1812_Massa_Compoti": {
        "manifest": "https://digi.ub.uni-heidelberg.de/diglit/bav_pal_lat_1812/iiif/manifest.json",
        "description": "Pal.lat.1812 (Heidelberg mirror) - Alexander de Villa Dei Carmen de algorismo + Massa compoti, Kurpfalz(?) 14th c.",
    },
}

BASE_DIR = os.path.expanduser("~/research collection/manuscripts")
IMAGE_WIDTH = "1024,"  # IIIF size: 1024px wide, height proportional
DELAY_SECONDS = 0.5
MAX_RETRIES = 2

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
                  "(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "Accept": "image/jpeg,image/*,*/*",
}

JSON_HEADERS = {
    "User-Agent": HEADERS["User-Agent"],
    "Accept": "application/json,application/ld+json,*/*",
}


# ---------- Page-range parsing ----------


def parse_pages(spec: str, total: int) -> list[int]:
    """
    Parse a pages spec into a sorted list of 1-indexed canvas indices.
      "all"          -> [1..total]
      "1-10"         -> [1..10]
      "1,5,10"       -> [1, 5, 10]
      "1-10,15,20-25"-> [1..10, 15, 20..25]
    """
    if spec is None or spec == "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)


# ---------- IIIF helpers ----------


def fetch_manifest(url: str) -> dict:
    print(f"  Fetching manifest: {url}")
    resp = requests.get(url, headers=JSON_HEADERS, timeout=60)
    resp.raise_for_status()
    return resp.json()


def extract_image_urls(manifest: dict) -> list[tuple[str, str]]:
    """
    Return a list of (label, image_base_url) per canvas.
    Supports IIIF Presentation 2.x and 3.x.
    """
    results: list[tuple[str, str]] = []

    # IIIF Presentation 2.x
    sequences = manifest.get("sequences")
    if sequences:
        canvases = sequences[0].get("canvases", [])
        for canvas in canvases:
            label = canvas.get("label", "")
            if isinstance(label, list):
                label = label[0].get("@value", "") if label else ""
            images = canvas.get("images", [])
            if not images:
                continue
            resource = images[0].get("resource", {})
            service = resource.get("service", {})
            if isinstance(service, list):
                service = service[0] if service else {}
            base_url = service.get("@id", "") or resource.get("@id", "").rsplit("/full/", 1)[0]
            if base_url:
                results.append((str(label), base_url))
        return results

    # IIIF Presentation 3.x
    items = manifest.get("items", [])
    for canvas in items:
        label_obj = canvas.get("label", {})
        if isinstance(label_obj, dict):
            label = ""
            for vals in label_obj.values():
                label = vals[0] if vals else ""
                break
        else:
            label = str(label_obj)

        anno_pages = canvas.get("items", [])
        if not anno_pages:
            continue
        annotations = anno_pages[0].get("items", [])
        if not annotations:
            continue
        body = annotations[0].get("body", {})
        service = body.get("service", [])
        if isinstance(service, list):
            service = service[0] if service else {}
        base_url = service.get("@id") or service.get("id", "")
        if base_url:
            results.append((label, base_url))

    return results


def download_image(base_url: str, dest_path: str) -> bool:
    url = f"{base_url}/full/{IMAGE_WIDTH}/0/default.jpg"
    for attempt in range(1 + MAX_RETRIES):
        try:
            resp = requests.get(url, headers=HEADERS, timeout=120, stream=True)
            resp.raise_for_status()
            with open(dest_path, "wb") as f:
                for chunk in resp.iter_content(chunk_size=8192):
                    f.write(chunk)
            return True
        except Exception as e:
            if attempt < MAX_RETRIES:
                print(f"    Retry after error: {e}")
                time.sleep(2)
            else:
                print(f"    FAILED: {e}")
                return False
    return False


# ---------- PDF assembly ----------


def assemble_pdf(out_dir: str, key: str, indices: list[int]) -> str | None:
    """
    Assemble the specified page images into {key}[_pages-N-M].pdf.
    Uses PIL (Pillow) — must be installed.
    """
    try:
        from PIL import Image
    except ImportError:
        print("  ! PIL not available; cannot build PDF. Install with: pip install pillow")
        return None

    image_paths = []
    for idx in indices:
        p = os.path.join(out_dir, f"page_{idx:03d}.jpg")
        if os.path.exists(p) and os.path.getsize(p) > 0:
            image_paths.append(p)

    if not image_paths:
        print("  ! No images found to assemble")
        return None

    if len(indices) == 0:
        return None

    # Filename reflects range if partial
    if len(image_paths) < 500:  # don't clutter name for whole-MS
        first, last = indices[0], indices[-1]
        if len(indices) == (last - first + 1) and indices == list(range(first, last + 1)):
            suffix = f"_p{first:03d}-{last:03d}"
        else:
            suffix = f"_p{first:03d}-{last:03d}_partial"
    else:
        suffix = ""

    pdf_path = os.path.join(out_dir, f"{key}{suffix}.pdf")
    print(f"  Assembling {len(image_paths)} pages into {os.path.basename(pdf_path)} ...")

    first_img = Image.open(image_paths[0]).convert("RGB")
    rest = [Image.open(p).convert("RGB") for p in image_paths[1:]]
    first_img.save(pdf_path, save_all=True, append_images=rest, resolution=150.0)
    print(f"  PDF: {pdf_path} ({os.path.getsize(pdf_path) / 1024 / 1024:.1f} MB)")
    return pdf_path


# ---------- Main ----------


def download_manuscript(key: str, info: dict, pages_spec: str | None,
                        build_pdf: bool) -> tuple[int, int]:
    out_dir = os.path.join(BASE_DIR, key)
    os.makedirs(out_dir, exist_ok=True)

    manifest = fetch_manifest(info["manifest"])

    manifest_path = os.path.join(out_dir, "manifest.json")
    with open(manifest_path, "w") as f:
        json.dump(manifest, f, indent=2)
    print(f"  Saved manifest to {manifest_path}")

    all_pages = extract_image_urls(manifest)
    total = len(all_pages)
    print(f"  Found {total} canvases")

    indices = parse_pages(pages_spec or "all", total)
    print(f"  Will fetch {len(indices)} pages (spec: {pages_spec or 'all'})")

    success = 0
    fail = 0

    for idx in indices:
        label, base_url = all_pages[idx - 1]
        filename = f"page_{idx:03d}.jpg"
        filepath = os.path.join(out_dir, filename)

        if os.path.exists(filepath) and os.path.getsize(filepath) > 0:
            print(f"  [{idx}/{total}] {filename} ('{label}') -- exists, skip")
            success += 1
            continue

        print(f"  [{idx}/{total}] {filename} ('{label}') ...", end=" ", flush=True)
        if download_image(base_url, filepath):
            size_kb = os.path.getsize(filepath) / 1024
            print(f"OK ({size_kb:.0f} KB)")
            success += 1
        else:
            fail += 1
            if os.path.exists(filepath):
                os.remove(filepath)

        time.sleep(DELAY_SECONDS)

    if build_pdf and success > 0:
        assemble_pdf(out_dir, key, indices)

    return success, fail


def main():
    parser = argparse.ArgumentParser(description="Download IIIF manuscript images",
                                     formatter_class=argparse.RawDescriptionHelpFormatter,
                                     epilog=__doc__)
    parser.add_argument("--only", type=str, help="Download only this key")
    parser.add_argument("--pages", type=str, default=None,
                        help="Pages spec: 'all', '1-20', '1,5,10', '1-10,15,20-25'")
    parser.add_argument("--pdf", action="store_true", help="Assemble PDF from downloaded images")
    parser.add_argument("--manifest", type=str, help="Ad-hoc IIIF manifest URL")
    parser.add_argument("--key", type=str, help="Key name for ad-hoc manifest (required with --manifest)")
    parser.add_argument("--description", type=str, default="", help="Description for ad-hoc manifest")
    parser.add_argument("--list", action="store_true", help="List configured manuscripts and exit")
    args = parser.parse_args()

    if args.list:
        print("Configured manuscripts:")
        for k, v in MANUSCRIPTS.items():
            print(f"  {k}\n    {v['description']}")
        return

    if args.manifest:
        if not args.key:
            print("ERROR: --manifest requires --key")
            sys.exit(1)
        targets = {args.key: {"manifest": args.manifest, "description": args.description}}
    elif args.only:
        if args.only not in MANUSCRIPTS:
            print(f"Unknown key '{args.only}'. Options:")
            for k in MANUSCRIPTS:
                print(f"  {k}")
            sys.exit(1)
        targets = {args.only: MANUSCRIPTS[args.only]}
    else:
        targets = MANUSCRIPTS

    for key, info in targets.items():
        print(f"\n{'='*60}")
        print(f"Downloading: {key} — {info.get('description', '')}")
        print(f"{'='*60}")
        ok, bad = download_manuscript(key, info, args.pages, args.pdf)
        print(f"\n  Result: {ok} succeeded, {bad} failed\n")


if __name__ == "__main__":
    main()
