#!/usr/bin/env python3
"""Parallel downloader for BSB Clm 30150 Kyeser Bellifortis canvases.

Idempotent: skips files already present. Retries on transient failures.
"""
import csv
import os
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed

BASE = '../../../resources/tools/provenance/index.html#s-3dcde5bc82b4fe5b'
DEST = os.path.join(BASE, 'folios')
LIST = os.path.join(BASE, 'download_list.tsv')
LOG = os.path.join(BASE, '_download.log')

WORKERS = 4
MAX_RETRIES = 4
BACKOFF_BASE = 3.0  # seconds

os.makedirs(DEST, exist_ok=True)

tasks = []
with open(LIST) as f:
    r = csv.reader(f, delimiter='\t')
    next(r)
    for row in r:
        idx, fname, url, w, h = row
        tasks.append((fname, url))


def fetch(task):
    fname, url = task
    dest = os.path.join(DEST, fname)
    if os.path.exists(dest) and os.path.getsize(dest) > 1000:
        return (fname, 'skip', os.path.getsize(dest))
    tmp = dest + '.tmp'
    last_err = None
    for attempt in range(MAX_RETRIES):
        try:
            req = urllib.request.Request(url, headers={'User-Agent': 'iiif-curator/1.0'})
            with urllib.request.urlopen(req, timeout=120) as r:
                data = r.read()
            with open(tmp, 'wb') as f:
                f.write(data)
            os.rename(tmp, dest)
            return (fname, 'ok', len(data))
        except Exception as e:
            last_err = e
            time.sleep(BACKOFF_BASE * (2 ** attempt))
    if os.path.exists(tmp):
        try:
            os.unlink(tmp)
        except OSError:
            pass
    return (fname, f'FAIL: {last_err}', 0)


start = time.time()
done = 0
total_bytes = 0
fails = []
with open(LOG, 'w') as logf, ThreadPoolExecutor(max_workers=WORKERS) as ex:
    futs = [ex.submit(fetch, t) for t in tasks]
    for fut in as_completed(futs):
        fname, status, sz = fut.result()
        done += 1
        if status in ('ok', 'skip'):
            total_bytes += sz
        else:
            fails.append((fname, status))
        if done % 25 == 0 or done == len(tasks):
            elapsed = time.time() - start
            msg = f"[{done}/{len(tasks)}] elapsed={elapsed:.1f}s mb={total_bytes/1e6:.1f} fails={len(fails)}"
            print(msg, flush=True)
            logf.write(msg + '\n')
            logf.flush()

elapsed = time.time() - start
summary = f"DONE: {done}/{len(tasks)} processed, {len(fails)} failed, {total_bytes/1e6:.1f} MB in {elapsed:.1f}s"
print(summary)
with open(LOG, 'a') as logf:
    logf.write(summary + '\n')
    if fails:
        logf.write("FAILURES:\n")
        for f, e in fails:
            logf.write(f"  {f}: {e}\n")
