#!/usr/bin/env python3
"""
BSB Cod.icon. 242 (Fontana, Bellicorum instrumentorum liber) full-resolution IIIF fetcher.
Reads manifest, fetches all canvases at /full/max/ using bounded concurrency.
"""
import json
import os
import re
import sys
import time
import unicodedata
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.request import urlopen, Request
from urllib.error import HTTPError, URLError

MANIFEST_PATH = "f084643ca6e12256257a4ce5.json"
OUT_DIR = "../../../resources/tools/provenance/index.html#s-44c8a77ad62a71b3"
CONCURRENCY = 3
RETRIES = 3
RETRY_DELAY = 4

os.makedirs(OUT_DIR, exist_ok=True)

def slugify(label: str) -> str:
    # Strip control chars, normalize, replace spaces, drop trailing parenthetical numbers
    s = unicodedata.normalize("NFKD", label)
    s = s.encode("ascii", "ignore").decode("ascii")
    s = re.sub(r"\s+", "_", s.strip())
    s = re.sub(r"[^A-Za-z0-9_.\-]", "", s)
    return s[:80]

def fetch_one(idx: int, canvas: dict, total: int) -> tuple[int, str, str]:
    label = canvas.get("label", f"canvas_{idx+1:03d}")
    svc = canvas["images"][0]["resource"]["service"]["@id"]
    url = f"{svc}/full/max/0/default.jpg"
    seq = idx + 1
    fname = f"{seq:03d}_{slugify(label)}.jpg"
    fpath = os.path.join(OUT_DIR, fname)
    if os.path.exists(fpath) and os.path.getsize(fpath) > 100_000:
        return (seq, fname, "SKIP")
    last_err = None
    for attempt in range(1, RETRIES + 1):
        try:
            req = Request(url, headers={"User-Agent": "iiif-manifest-curator/1.0 (academic)"})
            with urlopen(req, timeout=120) as r:
                data = r.read()
            if len(data) < 50_000:
                raise ValueError(f"short response {len(data)} bytes")
            tmp = fpath + ".part"
            with open(tmp, "wb") as f:
                f.write(data)
            os.rename(tmp, fpath)
            return (seq, fname, f"OK {len(data)//1024}KB")
        except (HTTPError, URLError, ValueError, OSError) as e:
            last_err = e
            if attempt < RETRIES:
                time.sleep(RETRY_DELAY * attempt)
    return (seq, fname, f"FAIL {last_err}")

def main():
    with open(MANIFEST_PATH) as f:
        m = json.load(f)
    canvases = m["sequences"][0]["canvases"]
    total = len(canvases)
    print(f"[manifest] {total} canvases, target dir: {OUT_DIR}", flush=True)
    results = []
    t0 = time.time()
    with ThreadPoolExecutor(max_workers=CONCURRENCY) as ex:
        futs = {ex.submit(fetch_one, i, c, total): i for i, c in enumerate(canvases)}
        done_count = 0
        for fut in as_completed(futs):
            r = fut.result()
            results.append(r)
            done_count += 1
            if done_count % 10 == 0 or "FAIL" in r[2]:
                elapsed = time.time() - t0
                print(f"[{done_count}/{total}] {r[0]:03d} {r[2]:<14} {r[1]}  ({elapsed:.0f}s)", flush=True)
    elapsed = time.time() - t0
    ok = sum(1 for r in results if r[2].startswith("OK"))
    skip = sum(1 for r in results if r[2] == "SKIP")
    fail = sum(1 for r in results if r[2].startswith("FAIL"))
    print(f"\n[summary] OK={ok}  SKIP={skip}  FAIL={fail}  total={total}  time={elapsed:.1f}s", flush=True)
    if fail:
        print("\n[failures]")
        for r in sorted(results):
            if r[2].startswith("FAIL"):
                print(f"  {r[0]:03d}  {r[1]}  {r[2]}")
        sys.exit(1)

if __name__ == "__main__":
    main()
