cirosantilli/bin/wayback-machine-download

bin/wayback-machine-download
#!/usr/bin/env python3
"""Download archived websites by listing CDX captures or crawling a replayed homepage.

Wayback Machine is slow and flaky, and this script aims to be highly resilient. One main
design goal is that if you stop and rerun the script it picks up from where you left off
quickly and without missing anything.
"""
import argparse
import calendar
from collections import defaultdict, deque
from copy import copy
import concurrent.futures
from contextlib import ExitStack, contextmanager
from contextvars import ContextVar
import csv
import datetime as dt
import email.utils
import errno
import filecmp
import fcntl
import hashlib
import heapq
from html import unescape
from html.parser import HTMLParser
import json
import math
import mimetypes
import os
import select
import signal
import shutil
import socket
import sqlite3
import subprocess
import sys
import tempfile
from pathlib import Path
import re
import threading
import time
from types import SimpleNamespace
from urllib.parse import parse_qsl, urljoin, urlsplit, urlunsplit, urlencode, unquote, unquote_plus, quote
from weakref import WeakValueDictionary

import requests

BASE = Path.cwd()
STATE = BASE / 'site-review'
MIRROR = BASE / 'site-mirrors'
DUMP = None
RATE_DIR = None
HTTP_COOLDOWN_SECONDS = 300
NETWORK_RECHECK_SECONDS = 15
SEED_CACHE = None
ANCHOR = dt.datetime.now(dt.timezone.utc).strftime('%Y%m%d%H%M%S')
LOCK = threading.RLock()
STOP = threading.Event()
OUTPUT_LOCK = threading.Lock()
EXTERNAL_REFERRER = ContextVar('external_referrer', default=None)
ASSET_EXT = re.compile(r'\.(?:css|js|mjs|jpe?g|png|gif|webp|svg|ico|bmp|woff2?|ttf|eot|otf|jar|class|swf)(?:$|[?;])', re.I)
PAGE_EXT = re.compile(r'\.(?:html?|php\d?|asp[x]?|jsp|shtml)(?:$|[?;])', re.I)


def report(message):
    with OUTPUT_LOCK:
        print(message, flush=True)


def report_download(url, port=None, outcome=None, elapsed=None):
    fields = []
    if outcome is not None:
        fields.append(str(outcome) if elapsed is None else f'{outcome} {elapsed:.1f}s')
    if port is not None:
        fields.append(f"tor: {str(port).removeprefix('managed-')}")
    if referrer := EXTERNAL_REFERRER.get():
        fields.append(f'external: {referrer}')
    suffix = f" ({', '.join(fields)})" if fields else ''
    report(f'DOWNLOAD {url}{suffix}')


def save(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name(path.name + f'.{threading.get_ident()}.new')
    temp.write_text(json.dumps(value, indent=2, ensure_ascii=True) + '\n')
    temp.replace(path)


def read_failure_statuses(metadata, path, migrate, reviewed):
    """Extract unresolved URL entries while preserving any saved capture metadata."""
    reviewed.clear()
    if 'failed_urls' not in metadata and 'missing_urls' not in metadata:
        statuses = {}
        for url, entry in list(metadata.items()):
            if not url.startswith(('https://', 'http://')) or not isinstance(entry, dict) or 'status' not in entry:
                continue
            status = entry.pop('status')
            # Reviewed outcomes retain their specific reason in the manifest.
            # Only the prefix determines whether another transfer is needed.
            group = status.split('-', 1)[0] if isinstance(status, str) else ''
            if group not in ('missing', 'failed', 'recovered') and status != 'petabox':
                raise ValueError(f'Invalid status for {url} in {path}')
            if status != group or group == 'recovered' or 'statusNotes' in entry:
                reviewed[url] = {'status': status}
                if 'statusNotes' in entry:
                    reviewed[url]['statusNotes'] = entry.pop('statusNotes')
            if group != 'recovered':
                statuses[url] = 'retry' if group == 'failed' else group
            if not entry:
                del metadata[url]
        return statuses
    failed = metadata.pop('failed_urls', [])
    if 'missing_urls' not in metadata and isinstance(failed, dict):
        if all(status in ('missing', 'retry') for status in failed.values()):
            return failed
        raise ValueError(f'Invalid failed_urls in {path}')
    if not isinstance(failed, list) or not all(isinstance(url, str) for url in failed):
        raise ValueError(f'Invalid failed_urls in {path}')
    if 'missing_urls' not in metadata:
        return migrate(failed)
    missing = metadata.pop('missing_urls')
    if not isinstance(missing, list) or not all(isinstance(url, str) for url in missing):
        raise ValueError(f'Invalid missing_urls in {path}')
    if not set(failed).isdisjoint(missing):
        raise ValueError(f'Overlapping failed_urls and missing_urls in {path}')
    return {**dict.fromkeys(failed, 'retry'), **dict.fromkeys(missing, 'missing')}


def with_failure_entries(metadata, statuses, reviewed):
    entries = dict(metadata)
    for url, status in statuses.items():
        entries[url] = {**entries.get(url, {}), 'status': 'failed' if status == 'retry' else status}
    for url, details in reviewed.items():
        entries[url] = {**entries.get(url, {}), **details}
    return dict(sorted(entries.items()))


class FailedDownloads:
    """Unresolved Wayback URLs shared by all runs writing to this mirror."""

    def __init__(self, root, checkpoint_dir=None):
        self.path = root / 'meta.json'
        self.checkpoint_dir = checkpoint_dir
        self.lock_path = root / '.wayback-machine-download' / 'meta.lock'
        self.lock_path.parent.mkdir(parents=True, exist_ok=True)
        self.version = None
        self.reviewed = {}
        self.update()

    def migrate(self, urls):
        statuses = dict.fromkeys(urls, 'retry')
        if statuses and self.checkpoint_dir:
            for path in self.checkpoint_dir.glob('domains/*.json'):
                state = json.loads(path.read_text())
                for item in state.get('items', {}).values():
                    if item.get('reason') not in ('Not archived: HTTP 404', 'Not archived: HTTP 410'):
                        continue
                    stamp = item.get('capture') or state.get('anchor')
                    requested = capture_url(stamp, item['url'])
                    if requested in statuses:
                        statuses[requested] = 'missing'
        return statuses

    def update(self, url=None, status=None):
        # A different date range or work directory can have its own controller.
        with self.lock_path.open('a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            try:
                stat = self.path.stat()
                version = (stat.st_ino, stat.st_mtime_ns)
            except FileNotFoundError:
                version = None
            changed = False
            if version is None or version != self.version:
                self.meta = json.loads(self.path.read_text()) if version is not None else {}
                changed = version is None or 'failed_urls' in self.meta or 'missing_urls' in self.meta
                self.statuses = read_failure_statuses(self.meta, self.path, self.migrate, self.reviewed)
                self.version = version
            urls = self.statuses
            if url is not None:
                entry = self.meta.get(url, {})
                if status == 'empty':
                    if self.reviewed.pop(url, None) is not None:
                        changed = True
                    if entry.get('empty') is not True:
                        self.meta[url] = {**entry, 'empty': True}
                        changed = True
                    status = None  # A verified empty index resolves any earlier failure.
                elif entry.get('empty') is True:
                    if status is not None:
                        return  # A concurrent failed request cannot invalidate a successful lookup.
                    del entry['empty']
                    if not entry:
                        del self.meta[url]
                    changed = True
            if url is not None and urls.get(url) != status:
                self.reviewed.pop(url, None)
                if status is None:
                    del urls[url]
                else:
                    urls[url] = status
                changed = True
            if changed:
                self.version = None
                save(self.path, with_failure_entries(self.meta, urls, self.reviewed))
                stat = self.path.stat()
                self.version = (stat.st_ino, stat.st_mtime_ns)

    def status(self, url):
        self.update()  # Reload changes made by other controllers.
        if self.meta.get(url, {}).get('empty') is True:
            return 'empty'
        return self.statuses.get(url)


def archive_error(data):
    """Classify Wayback placeholder pages, including ones replayed with HTTP 200."""
    title = re.search(rb'<title\b[^>]*>(.*?)</title>', data[:16384], re.I | re.S)
    if title and title[1].strip().lower() == b'welcome to the us petabox':
        return 'petabox'
    head = (title[1] if title else b'') + data[:1200]
    if re.search(rb'Wayback Machine.*has not archived|This URL has been excluded from the Wayback Machine|<title>Wayback Machine</title>', head, re.I | re.S):
        return 'failed'
    return None


def key(value):
    return hashlib.sha256(value.encode()).hexdigest()


def unwrap(url):
    if url.startswith('//'):
        url = 'https:' + url
    parsed = urlsplit(url)
    if parsed.hostname == 'web.archive.org':
        match = re.match(r'/web/(\d{1,14})[a-z_]*/(https?://.*)', parsed.path + ('?' + parsed.query if parsed.query else ''))
        if match:
            return match[2]
    return url


def normalize(url, base):
    url = unwrap(url.strip())
    parsed = urlsplit(urljoin(base, url))
    if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password:
        return None
    if parsed.hostname.lower() == 'web.archive.org':
        return None
    try:
        host = parsed.hostname.encode('idna').decode().lower()
        port = parsed.port
    except (ValueError, UnicodeError):
        return None
    if ':' in host:  # Keep this domain-name crawler out of ambiguous IPv6 path layouts.
        return None
    netloc = host + (':' + str(port) if port and port != (80 if parsed.scheme == 'http' else 443) else '')
    path = quote(parsed.path or '/', safe="/%:@!$&'()*+,;=-._~")
    query = quote(parsed.query, safe="/%?:@!$&'()*+,;=-._~[]")
    return urlunsplit((parsed.scheme.lower(), netloc, path, query, ''))


def family(host, domain):
    host, domain = host.lower().removeprefix('www.'), domain.lower().removeprefix('www.')
    return host == domain or host.endswith('.' + domain)


def replay_parts(url, headers=None):
    parsed = urlsplit(url)
    match = re.match(r'/web/(\d{14})[a-z_]*/(https?://.*)', parsed.path + ('?' + parsed.query if parsed.query else ''))
    if not match:
        return None
    stamp, original = match.groups()
    headers = {k.lower(): v for k, v in (headers or {}).items()}
    if headers.get('memento-datetime'):
        try:
            stamp = email.utils.parsedate_to_datetime(headers['memento-datetime']).astimezone(dt.timezone.utc).strftime('%Y%m%d%H%M%S')
        except (TypeError, ValueError):
            pass
    original = normalize(original, original)
    return (stamp, original) if original else None


def css_refs(text):
    # CSS escapes are common in quoted filenames and @import statements.
    def clean(s):
        s = re.sub(r'\\([0-9a-fA-F]{1,6})\s?', lambda m: chr(int(m[1], 16)) if int(m[1],16) <= 0x10ffff else '', s)
        return re.sub(r'\\([^\n])', r'\1', s)
    for match in re.finditer(r'url\(\s*(?:"([^"]*)"|\x27([^\x27]*)\x27|([^)]*?))\s*\)', text, re.I):
        yield clean(next(v for v in match.groups() if v is not None))
    for match in re.finditer(r'@import\s+["\x27]([^"\x27]+)["\x27]', text, re.I):
        yield clean(match[1])


class References(HTMLParser):
    def __init__(self, text):
        super().__init__(convert_charrefs=True)
        self.refs = []
        self.page_refs = 0
        self.asset_refs = 0
        self.base = None
        self.style = False
        self.script = False
        self.applet_base = ''
        self.overflow = False
        self.feed(text)

    def add(self, value, role='asset', codebase=''):
        count=self.page_refs if role=='page' else self.asset_refs
        if value and count < (500 if role=='page' else 5000):
            self.refs.append((value, role, codebase))
            if role=='page':self.page_refs+=1
            else:self.asset_refs+=1
        elif value:
            self.overflow = True

    def handle_starttag(self, tag, attrs):
        a = {name: value or "" for name,value in attrs}
        if tag == 'base' and a.get('href') and self.base is None:
            self.base = a['href']
        if tag == 'style': self.style = True
        if tag == 'script': self.script = True
        if tag == 'applet':
            self.applet_base = a.get('codebase', '')
            for value in a.get('archive', '').split(','):
                self.add(value.strip(), 'asset', self.applet_base)
            if not a.get('archive') and a.get('code'):
                self.add(a['code'], 'asset', self.applet_base)
        if tag == 'param' and a.get('name', '').lower() in ('movie', 'src', 'archive', 'filename'):
            for value in a.get('value', '').split(','):
                self.add(value.strip(), 'asset', self.applet_base)
        if tag in ('iframe', 'frame'):
            self.add(a.get('src'), 'frame')
        elif tag in ('img', 'script', 'input', 'embed', 'audio', 'video', 'source', 'track'):
            self.add(a.get('src'))
        if tag == 'object': self.add(a.get('data'))
        if tag in ('img','source'):
            for attr in ('data-src','data-original','data-lazy-src'):self.add(a.get(attr))
        if tag == 'video': self.add(a.get('poster'))
        if tag == 'link' and any(r in a.get('rel', '').lower().split() for r in ('stylesheet', 'icon', 'shortcut', 'preload', 'modulepreload')):
            self.add(a.get('href'))
        if tag=='link' and 'alternate' in a.get('rel','').lower() and a.get('type','').lower() in ('application/rss+xml','application/atom+xml'):
            self.add(a.get('href'))
        if tag in ('a', 'area'): self.add(a.get('href'), 'page')
        for attr in ('background', 'lowsrc', 'dynsrc'):
            self.add(a.get(attr))
        # Avoid splitting data: URL payloads into imaginary relative resources.
        srcset = a.get('srcset', '')
        if srcset and 'data:' not in srcset:
            for item in srcset.split(','):
                parts = item.strip().split()
                if parts: self.add(parts[0])
        for value in css_refs(a.get('style', '')): self.add(value)

    def handle_endtag(self, tag):
        if tag == 'style': self.style = False
        if tag == 'script': self.script = False
        if tag == 'applet': self.applet_base = ''

    def handle_data(self, data):
        if self.style:
            for value in css_refs(data): self.add(value)
        if self.script:
            for value in script_refs(data): self.add(value, 'script-asset')


def script_refs(text):
    # Literal filenames only. Never evaluate arbitrary JavaScript or guess its state.
    for match in re.finditer(r'''["']([^"'\n<>]{1,1024}\.(?:css|js|jpe?g|png|gif|webp|svg|ico|jar|swf)(?:\?[^"'\n<>]*)?)["']''', text, re.I):
        yield match[1]


def in_date_range(capture, start, end):
    return (start is None or start <= capture) and (end is None or capture <= end)


def cdx_dates(start, end):
    return {name: value for name, value in (('from', start), ('to', end)) if value is not None}


class Cache:
    def __init__(self):
        self.failed_downloads = None
        self.network = NetworkAvailability()
        self.urls = {}
        self.dump_hosts = set()
        self.lock = threading.RLock()
        self.fetch_locks = {}

    def add(self, url, capture, path, metadata=None, source='scan cache', source_path=None):
        url = normalize(url, url)
        if url and re.fullmatch(r'\d{14}', capture):
            record = dict(url=url, capture=capture, path=str(path.resolve()), source_path=source_path or str(path.resolve()), metadata=metadata, source=source)
            with self.lock:
                self.urls.setdefault(url, []).append(record)

    def load_scan(self):
        bases = [BASE] + sorted((BASE/'tor-top').glob('worker-*'))
        for base in bases:
            for meta in (base/'domains').glob('*/*.body.meta.json'):
                try:
                    m = json.loads(meta.read_text())
                    body = meta.with_name(meta.name.removesuffix('.meta.json'))
                    parts = replay_parts(m.get('url', m.get('requested_url', '')), m.get('headers'))
                    if m.get('status') == 200 and body.exists() and parts:
                        self.add(parts[1], parts[0], body, str(meta), 'scan cache')
                except (ValueError, OSError):
                    continue
        for file in (STATE/'domains').glob('*.json'):
            try:
                for item in json.loads(file.read_text()).get('items', {}).values():
                    if item.get('status') == 'saved':
                        record = item['record']
                        self.add(record['url'], record['capture'], Path(record['path']), record.get('metadata'), 'review mirror', record.get('source_path'))
            except (ValueError, OSError, KeyError):
                continue

    def load_dump(self, host):
        with self.lock:
            if host in self.dump_hosts: return
            self.dump_hosts.add(host)
            if DUMP is None: return
            root = DUMP/host
            if not root.is_dir(): return
            for capture in root.iterdir():
                if not re.fullmatch(r'\d{14}', capture.name) or not capture.is_dir(): continue
                for file in capture.rglob('*'):
                    if file.is_file() and not file.is_symlink():
                        rel = file.relative_to(capture).as_posix()
                        if '?' in rel and rel.endswith('/index.html'):
                            rel = rel[:-len('/index.html')]
                        paths = [rel]
                        if rel.endswith('index.html'): paths.append(rel[:-len('index.html')])
                        for path in paths:
                            for scheme in ('http', 'https'):
                                self.add(scheme+'://'+host+'/'+path, capture.name, file, source='existing dump')

    def get(self, url, anchor, max_days=7, start=None, end=None):
        self.load_dump(urlsplit(url).netloc)
        target = dt.datetime.strptime(anchor, '%Y%m%d%H%M%S')
        with self.lock:
            options = [r for r in self.urls.get(url, []) if
                       in_date_range(r['capture'], start, end)]
        options.sort(key=lambda r: (abs((dt.datetime.strptime(r['capture'], '%Y%m%d%H%M%S')-target).total_seconds()),r['source']=='review mirror'))
        for r in options:
            if abs((dt.datetime.strptime(r['capture'], '%Y%m%d%H%M%S')-target).total_seconds()) > max_days*86400:
                continue
            if Path(r['path']).is_file():
                with Path(r['path']).open('rb') as source:
                    if archive_error(source.read(16384)):continue
                return dict(r)
        return None


def mirror_path(record, mirror=None):
    mirror = MIRROR if mirror is None else mirror
    u = urlsplit(record['url'])
    parts = [p for p in u.path.split('/') if p]
    if any(unquote(p) in ('.', '..') or '\x00' in unquote(p) for p in parts):
        raise ValueError('Unsafe archive path')
    if not parts or u.path.endswith('/'): parts.append('index.html')
    parts = [p if len(p.encode()) <= 200 else 'long-path-'+key(p) for p in parts]
    if u.query:
        suffix = '?' + quote(u.query, safe='=&%+:,;@')
        parts[-1] += suffix if len((parts[-1]+suffix).encode()) <= 240 else '?query-'+key(u.query)
    destination = mirror / u.netloc / record['capture']
    destination = destination.joinpath(*parts)
    if not destination.resolve().is_relative_to(mirror.resolve()): raise ValueError('Mirror path escapes root')
    return destination


def seed_for(row):
    url = row.get('url') or 'http://' + row['domain'] + '/'
    anchor = row.get('capture') or ANCHOR
    if SEED_CACHE is not None:
        host = urlsplit(url).netloc
        choices = [url]
        if urlsplit(url).path in ('', '/'):
            alternate = host.removeprefix('www.') if host.startswith('www.') else 'www.' + host
            choices.extend([url.replace('://' + host, '://' + alternate, 1)])
        candidates = []
        for choice in choices:
            for scheme in ('http', 'https'):
                choice = scheme + ':' + choice.split(':', 1)[1]
                SEED_CACHE.load_dump(urlsplit(choice).netloc)
                with SEED_CACHE.lock:
                    rows = list(SEED_CACHE.urls.get(choice, []))
                for record in rows:
                    if in_date_range(record['capture'], row.get('start'), row.get('end')):
                        candidates.append(record)
        target = dt.datetime.strptime(anchor, '%Y%m%d%H%M%S')
        candidates.sort(key=lambda r: abs((dt.datetime.strptime(r['capture'], '%Y%m%d%H%M%S') - target).total_seconds()))
        for record in candidates:
            path = Path(record['path'])
            if path.is_file():
                with path.open('rb') as source:
                    if archive_error(source.read(16384)): continue
                return record['url'], record['capture'], str(path)
    return url, anchor, None


class Unavailable(Exception):
    status = 'missing'


class CaptureMissing(FileNotFoundError):
    """Wayback confirmed that it has no response for this replay URL."""
    status = 'missing'


class PetaboxCapture(CaptureMissing, Unavailable):
    status = 'petabox'

    def __init__(self):
        super().__init__('Wayback replayed the US Petabox landing page')


def check_local_petabox(path):
    # Earlier runs could publish the landing page as an ordinary HTTP 200 capture.
    with path.open('rb') as stream:
        if archive_error(stream.read(16384)) == 'petabox':
            raise PetaboxCapture()


class DeferredFetch(requests.RequestException):
    def __init__(self, *args, retry_in_pass=True, timeout_seconds=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.retry_in_pass = retry_in_pass
        self.timeout_seconds = timeout_seconds


class NetworkOutage(Exception):
    def __init__(self, reason, recovered):
        super().__init__(reason)
        self.recovered = recovered


def has_network_route():
    # UDP connect selects a local route without sending a packet or resolving a name.
    for family, address in ((socket.AF_INET, '192.0.2.1'), (socket.AF_INET6, '2001:db8::1')):
        try:
            with socket.socket(family, socket.SOCK_DGRAM) as sock:
                sock.connect((address, 443))
            return True
        except OSError as error:
            if error.errno not in (errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN,
                                   errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL):
                return True  # An inconclusive route check must not stall the queue.
    return False


def local_network_outage(error, via_tor):
    if via_tor:
        # A single unhealthy exit or a stopped local proxy is not a laptop outage.
        if not isinstance(error, DeferredFetch) or not str(error).startswith(('curl ', 'Tor curl subprocess timeout')):
            return None
    elif not isinstance(error, (requests.ConnectionError, requests.Timeout, requests.exceptions.ChunkedEncodingError)):
        return None
    if not has_network_route():
        return NetworkOutage('no network route', has_network_route)
    if via_tor:
        return None  # Leave DNS on the Tor circuit.
    # requests wraps urllib3's resolver error inside a MaxRetryError.
    causes = [error]
    seen = set()
    hostname = 'web.archive.org'
    while causes:
        cause = causes.pop()
        if not isinstance(cause, BaseException) or id(cause) in seen:
            continue
        seen.add(id(cause))
        hostname = getattr(cause, '_host', None) or hostname
        if isinstance(cause, socket.gaierror) and cause.errno == socket.EAI_AGAIN:
            def dns_recovered():
                try:
                    socket.getaddrinfo(hostname, 443, type=socket.SOCK_STREAM)
                    return True
                except socket.gaierror as error:
                    # A definitive DNS reply ends the local outage. The request
                    # can then report a permanent lookup error normally.
                    return error.errno != socket.EAI_AGAIN
            return NetworkOutage(f'temporary DNS failure for {hostname}', dns_recovered)
        causes.extend((cause.__context__, cause.__cause__, getattr(cause, 'reason', None), *cause.args))
    return None


class NetworkAvailability:
    def __init__(self):
        self.condition = threading.Condition()
        self.paused = False

    def wait(self):
        with self.condition:
            while self.paused and not STOP.is_set():
                self.condition.wait(0.5)

    def recover(self, outage):
        with self.condition:
            if self.paused:
                return  # The request loop waits for the worker already checking connectivity.
            self.paused = True
        try:
            report(f'Network paused: {outage}. Checking every {NETWORK_RECHECK_SECONDS}s.')
            while not STOP.wait(NETWORK_RECHECK_SECONDS):
                if outage.recovered():
                    report('Network available again; resuming interrupted requests.')
                    break
        finally:
            with self.condition:
                self.paused = False
                self.condition.notify_all()


class RateGate:
    """Shared start spacing; independent cooldowns for Tor SOCKS ports."""
    # Workers sharing a folder check this under the same rate.lock.
    _reported_direct_cooldowns = {}

    def __init__(self, folder, interval, stop=None):
        self.folder = Path(folder)
        self.interval = interval
        self.stop = stop

    def transaction(self, update):
        with (self.folder / 'rate.lock').open('a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            path = self.folder / 'rate.json'
            state = json.loads(path.read_text()) if path.exists() else {}
            result = update(state)
            temp = path.with_suffix('.new')
            temp.write_text(json.dumps(state, indent=2) + '\n')
            temp.replace(path)
            return result

    def wait(self, port=None):
        while True:
            if self.stop is not None and self.stop():
                raise InterruptedError('Stop requested while waiting for archive rate limit')
            def reserve(state):
                now = time.time()
                interval = self.interval
                if str(port).startswith('managed-') and now < state.get('managed_slow_until', 0):
                    interval = max(interval, state['managed_interval'])
                cooldown = (state.get('cooldowns', {}).get(str(port), 0) if port is not None
                            else state.get('cooldown_until', 0))
                if port is None and now < cooldown and self._reported_direct_cooldowns.get(self.folder) != cooldown:
                    until = dt.datetime.fromtimestamp(cooldown, dt.timezone.utc)
                    report(f'HTTP cooldown: {math.ceil(cooldown - now)}s remaining (until {until:%Y-%m-%d %H:%M:%S} UTC)')
                    self._reported_direct_cooldowns[self.folder] = cooldown
                deadline = max(state.get('last_start', 0) + interval,
                               cooldown,
                               state.get('cooldowns', {}).get('managed', 0) if str(port).startswith('managed-') else 0,
                               state.get('ports', {}).get(str(port), 0) + (15 if port is not None else 0))
                if now < deadline:
                    return deadline - now
                state['last_start'] = now
                if port is not None:
                    state.setdefault('ports', {})[str(port)] = now
                return 0
            delay = self.transaction(reserve)
            if not delay:
                return time.time()
            time.sleep(min(delay, 2))

    def backoff(self, seconds, port=None):
        def update(state):
            if port is None:
                state['cooldown_until'] = max(state.get('cooldown_until', 0), time.time() + seconds)
            else:
                cooldowns = state.setdefault('cooldowns', {})
                cooldowns[str(port)] = max(cooldowns.get(str(port), 0), time.time() + seconds)
        self.transaction(update)

    def throttle_managed_worker(self, port, seconds):
        def update(state):
            now = time.time()
            cooldowns = state.setdefault('cooldowns', {})
            cooldowns[port] = max(cooldowns.get(port, 0), now + seconds)
            interval = self.interval
            if now < state.get('managed_slow_until', 0):
                interval = max(interval, state['managed_interval'])
            state['managed_interval'] = min(interval * 2, max(60, self.interval * 2))
            state['managed_slow_until'] = max(state.get('managed_slow_until', 0), now + seconds)
            return state['managed_interval']
        return self.transaction(update)


def tor_control_paths(config_dir, port):
    return config_dir / f'control-{port}.sock', config_dir / f'control-{port}.cookie'


def tor_control_ready(config_dir, port):
    endpoint, cookie = tor_control_paths(config_dir, port)
    try:
        return endpoint.is_socket() and cookie.is_file() and cookie.stat().st_size == 32
    except OSError:
        return False


def tor_new_identity(config_dir, port):
    """Request NEWNYM locally; never print authentication material."""
    endpoint, cookie_path = tor_control_paths(config_dir, port)
    cookie = cookie_path.read_bytes()
    if len(cookie) != 32:
        raise ValueError('Invalid Tor control cookie length')
    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as control:
        control.settimeout(5)
        control.connect(str(endpoint))
        with control.makefile('rwb') as stream:
            for command in (b'AUTHENTICATE ' + cookie.hex().encode(), b'SIGNAL NEWNYM'):
                stream.write(command + b'\r\n'); stream.flush()
                for _ in range(50):
                    line = stream.readline(8192)
                    if not line.startswith(b'250'):
                        raise ValueError('Tor control authentication or NEWNYM was rejected')
                    if line[3:4] == b' ': break
                else:
                    raise ValueError('Unexpected Tor control response')


def setup_tor_control(config_dir, ports, *, managed_only=False):
    """Set up missing control sockets for the selected running Tor instances."""
    if managed_only and (not config_dir.is_dir() or all(tor_control_ready(config_dir, p) for p in ports)):
        return
    directory = config_dir.stat()
    if directory.st_uid != os.getuid() or directory.st_mode & 0o077:
        raise ValueError(f'Tor requires a user-owned private control directory: {config_dir}. '
                         'For your own tor-army directory, set its mode to 700 before reloading.')
    # Downloaders with different output directories can share the same Tor army.
    fd = os.open(config_dir, os.O_RDONLY | os.O_DIRECTORY)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX)
        missing = [p for p in ports if not tor_control_ready(config_dir, p)]
        if missing:
            configure_tor_instances(config_dir, missing, managed_only)
    finally:
        os.close(fd)


def configure_tor_instances(config_dir, ports, managed_only):
    configurations = {}
    for path in config_dir.glob('torrc_*'):
        if not re.fullmatch(r'torrc_\d+', path.name): continue
        content = path.read_text()
        for match in re.finditer(r'^\s*SocksPort\s+(?:127\.0\.0\.1:)?(\d+)\b', content, re.M):
            configurations[int(match[1])] = (path.resolve(), content)
    processes = {}
    for proc in Path('/proc').iterdir():
        if not proc.name.isdigit(): continue
        try:
            if proc.stat().st_uid != os.getuid(): continue
            argv = (proc / 'cmdline').read_bytes().split(b'\0')
            if not argv or Path(os.fsdecode(argv[0])).name != 'tor': continue
            index = argv.index(b'-f')
            processes[Path(os.fsdecode(argv[index+1])).resolve()] = int(proc.name)
        except (OSError, ValueError, IndexError): continue
    changes = []
    begin, end = '# BEGIN archive downloader control', '# END archive downloader control'
    for port in ports:
        if port not in configurations:
            if managed_only: continue
            raise ValueError(f'No tor-army config found for SOCKS port {port}')
        path, content = configurations[port]
        if path not in processes:
            if managed_only: continue
            raise ValueError(f'No running user-owned Tor instance for {path}')
        plain = re.sub(re.escape(begin) + r'.*?' + re.escape(end) + r'\n?', '', content, flags=re.S)
        if re.search(r'^\s*(?:ControlPort|ControlSocket|CookieAuthFile|HashedControlPassword)\s+', plain, re.M | re.I):
            if managed_only: continue
            raise ValueError(f'Existing custom control authentication in {path}; not overwritten')
        plain = re.sub(r'^\s*CookieAuthentication\s+[^\n]*\n?', '', plain, flags=re.M)
        endpoint, cookie = tor_control_paths(config_dir, port)
        if len(os.fsencode(endpoint)) >= 104: raise ValueError('Tor control socket path is too long')
        quote_path = lambda p: '"' + str(p).replace('\\', '\\\\').replace('"', '\\"') + '"'
        revised = plain.rstrip() + '\n' + begin + '\n' + '\n'.join([
            'ControlSocket ' + quote_path(endpoint),
            'CookieAuthentication 1',
            'CookieAuthFile ' + quote_path(cookie),
        ]) + '\n' + end + '\n'
        changes.append((path, content, revised, processes[path], port))
    # Check each reload before changing the next instance.
    for path, content, revised, pid, port in changes:
        if content == revised and tor_control_ready(config_dir, port):
            report(f'TOR CONTROL: SOCKS {port} controls already ready (PID {pid})')
            continue
        backup = path.with_name(path.name + '.before-archive-control')
        if not backup.exists():
            with backup.open('x') as out: out.write(content)
            backup.chmod(path.stat().st_mode & 0o777)
        temp = path.with_name(path.name + '.archive-control-new')
        temp.write_text(revised); temp.chmod(path.stat().st_mode & 0o777); temp.replace(path)
        os.kill(pid, signal.SIGHUP)
        deadline = time.monotonic() + 10
        while not tor_control_ready(config_dir, port):
            if time.monotonic() >= deadline:
                log = config_dir / (path.name.removeprefix('torrc_') + '.log')
                raise ValueError(f'Tor control for SOCKS {port} did not become ready after reloading '
                                 f'PID {pid}. Check {log}. Config backup: {backup}')
            time.sleep(.05)
        report(f'TOR CONTROL: SOCKS {port} socket and cookie ready (PID {pid}); backup {backup}')


def kill_managed_tor(output):
    """Signal only this user's tagged Tor children for the selected output."""
    configs = set()
    for root in Path(tempfile.gettempdir()).glob(f'wayback-tor-{os.getuid()}-*'):
        try:
            if root.is_symlink() or root.stat().st_uid != os.getuid() or (root/'output').read_text() != str(output):
                continue
            (root/'stop').touch()
            configs.add(os.fsencode(root/'torrc'))
        except FileNotFoundError:  # A pool finished while we were inspecting it.
            continue
    signaled = 0
    if configs:
        # Open the pidfd first, then check command-line identity. A recycled
        # numeric PID cannot receive either signal intended for the old child.
        pending = set()
        poller = select.poll()
        with ExitStack() as handles:
            for proc in Path('/proc').iterdir():
                if not proc.name.isdigit():
                    continue
                try:
                    if proc.stat().st_uid != os.getuid():
                        continue
                    fd = os.pidfd_open(int(proc.name))
                    try:
                        argv = (proc/'cmdline').read_bytes().split(b'\0')
                        if b'--defaults-torrc' not in argv:
                            continue
                        i = argv.index(b'--defaults-torrc')
                        if (i == 0 or os.path.basename(argv[i-1]) != b'tor' or i+3 >= len(argv)
                                or argv[i+1] not in configs or argv[i+2:i+4] != [b'-f', argv[i+1]]
                                or b'--__OwningControllerProcess' not in argv):
                            continue
                        signal.pidfd_send_signal(fd, signal.SIGTERM)
                        pending.add(fd)
                        handles.callback(os.close, fd)
                        poller.register(fd, select.POLLIN)
                        signaled += 1
                    finally:
                        if fd not in pending:
                            os.close(fd)
                except (FileNotFoundError, ProcessLookupError, PermissionError):
                    continue
            deadline = time.monotonic() + 5
            while pending and time.monotonic() < deadline:
                for fd, _ in poller.poll(max(1, int((deadline-time.monotonic())*1000))):
                    pending.remove(fd)
                    poller.unregister(fd)
            for fd in pending:
                try:
                    signal.pidfd_send_signal(fd, signal.SIGKILL)
                except ProcessLookupError:
                    pass
    report(f'Signaled {signaled} managed Tor process(es) for {output}')


@contextmanager
def managed_tor(count):
    """Launch the pool, wait for every bootstrap, and reap every owned child."""
    with tempfile.TemporaryDirectory(prefix=f'wayback-tor-{os.getuid()}-') as folder, ExitStack() as logs:
        root = Path(folder)
        config = root / 'torrc'
        config.touch()
        (root/'output').write_text(str(MIRROR))
        endpoints, children, streams = [], [], []
        try:
            report(f'Starting {count} Tor instance(s)')
            for number in range(1, count + 1):
                if STOP.is_set() or (root/'stop').exists() or (STATE/'STOP').exists():
                    raise InterruptedError('Tor startup interrupted')
                endpoint = root / f'socks-{number}'
                control, cookie = tor_control_paths(root, f'managed-{number}')
                # Keep the original single-instance guard state for instance 1.
                data = STATE / ('tor-data' if number == 1 else f'tor-data-{number}')
                data.mkdir(mode=0o700, exist_ok=True)
                command = ['tor', '--defaults-torrc', str(config), '-f', str(config),
                           '--RunAsDaemon', '0', '--ClientOnly', '1', '--DataDirectory', str(data),
                           '--SocksPort', f'unix:{endpoint}', '--Log', 'notice stdout',
                           '--ControlSocket', str(control), '--CookieAuthentication', '1',
                           '--CookieAuthFile', str(cookie),
                           '--__OwningControllerProcess', str(os.getpid())]
                log = root / f'tor-{number}.log'
                with log.open('wb') as out:
                    child = subprocess.Popen(command, stdout=out, stderr=subprocess.STDOUT, start_new_session=True)
                    children.append(child)
                streams.append(logs.enter_context(log.open(errors='replace')))
                endpoints.append(endpoint)
            deadline = time.monotonic() + 180
            next_report = time.monotonic() + 15
            ready = set()
            bootstrap = {}
            last_warning = {}
            while len(ready) < count:
                for number, (child, stream) in enumerate(zip(children, streams), 1):
                    if STOP.is_set() or (root/'stop').exists() or (STATE/'STOP').exists():
                        raise InterruptedError('Tor startup interrupted')
                    for line in stream:
                        if 'Bootstrapped ' in line:
                            bootstrap[number] = line.split('Bootstrapped ', 1)[1].split('%', 1)[0] + '%'
                        if '[warn]' in line or '[err]' in line:
                            last_warning[number] = line.strip()
                        if 'Bootstrapped 100%' in line:
                            ready.add(number)
                    if child.poll() is not None:
                        reason = last_warning.get(number, 'no Tor warning logged')
                        raise RuntimeError(f'Tor {number} exited during startup ({child.returncode}): {reason}')
                if len(ready) < count:
                    now = time.monotonic()
                    if now >= next_report or now >= deadline:
                        waiting = sorted(set(range(1, count + 1)) - ready)
                        detail = ', '.join(f'{n} at {bootstrap.get(n, "0%")}' for n in waiting[:5])
                        if len(waiting) > 5:
                            detail += f' and {len(waiting) - 5} more'
                        status = f'{len(ready)}/{count} Tor instances ready; waiting for {detail}'
                        if now >= deadline:
                            raise RuntimeError('Tor bootstrap timed out: ' + status)
                        report(status)
                        next_report = now + 15
                    STOP.wait(0.25)
            report(f'{count}/{count} Tor instances ready')
            yield endpoints
        finally:
            for child in children:
                if child.poll() is None:
                    child.terminate()
            deadline = time.monotonic() + 5
            for child in children:
                try:
                    child.wait(timeout=max(0, deadline - time.monotonic()))
                except subprocess.TimeoutExpired:
                    child.kill()
                    child.wait()


class TorSession:
    def __init__(self, module, port, gate, http_cooldown_seconds=HTTP_COOLDOWN_SECONDS):
        self.module = module
        self.port = port
        self.gate = gate
        self.http_cooldown_seconds = http_cooldown_seconds
        endpoint = getattr(module, 'SOCKS_SOCKET', None)
        self.control_dir = Path(endpoint).parent if endpoint else getattr(module, 'TOR_CONFIG_DIR', Path.home() / 'etc/tor')
        self.proxy = ('socks5h://localhost' + quote(str(endpoint)) if endpoint
                      else f'socks5h://127.0.0.1:{port}')
        self.headers = {'User-Agent': 'HistoricalWebsiteResearch/1.0 (paced archival review)'}
        self.proxy_failure_reason = (f'Cannot connect to the local Tor SOCKS listener on port {port}. '
                                     'Check that Tor instance, then rerun this downloader; cached progress is retained.')

    def get(self, url, timeout=None, allow_redirects=False):
        self.module.LAST_RESPONSE_BYTES = 0
        self.transfer_started = None
        if not url.startswith('https://web.archive.org/') or allow_redirects:
            raise ValueError('Only explicit archive.org HTTPS requests are allowed')
        started = self.gate.wait(self.port)
        with tempfile.TemporaryDirectory(prefix='curl-', dir=self.module.BASE) as folder:
            body = Path(folder) / 'body'
            head = Path(folder) / 'headers'
            def preserve_partial(error, code=None):
                self.module.LAST_RESPONSE_BYTES = body.stat().st_size if body.exists() else 0
                if body.exists() or head.exists():
                    saved = self.module.BASE / 'transport-failures' / Path(folder).name
                    saved.mkdir(parents=True, exist_ok=True)
                    for path in (body, head):
                        if path.exists():
                            shutil.copyfile(path, saved / path.name)
                    self.module.save(saved / 'metadata.json', dict(url=url, tor_port=self.port,
                        network_started_epoch=started, curl_exit_code=code, error=error,
                        note='Incomplete/failed transfer, retained as evidence; not classified as a complete capture.'))
            command = [
                'curl', '--silent', '--show-error', '--compressed', '--globoff',
                '--proto', '=https', '--proxy', self.proxy,
                '--noproxy', '', '--connect-timeout', '20', '--max-time', '60',
                '--user-agent', self.headers['User-Agent'],
                '--dump-header', str(head), '--output', str(body),
                '--write-out', '%{http_code} %{time_appconnect}', url,
            ]
            if getattr(self.module, 'MAX_RESPONSE_BYTES', None):
                command[1:1] = ['--max-filesize', str(self.module.MAX_RESPONSE_BYTES)]
            report_download(url, self.port)
            self.transfer_started = time.monotonic()
            try:
                result = subprocess.run(command, capture_output=True, text=True, timeout=70)
            except subprocess.TimeoutExpired as error:
                preserve_partial(str(error))
                raise self.module.DeferredFetch('Tor curl subprocess timeout: ' + str(error),
                                                timeout_seconds=error.timeout) from error
            http_code, _, tls_time = result.stdout.strip().partition(' ')
            if result.returncode:
                error = result.stderr.strip()
                elapsed = time.monotonic() - self.transfer_started
                preserve_partial(error, result.returncode)
                # A zero TLS handshake time distinguishes a connection timeout
                # from a slow response on an already established HTTPS circuit.
                if result.returncode == 28 and http_code == '000' and re.fullmatch(r'0(?:\.0+)?', tls_time):
                    self.gate.backoff(15, self.port)
                    try:
                        tor_new_identity(self.control_dir, self.port)
                    except (OSError, ValueError) as control_error:
                        report(f'TOR {self.port}: connection timeout; NEWNYM failed ({control_error})')
                    else:
                        report(f'TOR {self.port}: connection timeout; NEWNYM accepted')
                if result.returncode == 63 and hasattr(self.module, 'ResponseLimitExceeded'):
                    raise self.module.ResponseLimitExceeded('Individual response size limit: ' + error)
                if result.returncode in (5, 7):
                    raise self.module.requests.exceptions.ProxyError(
                        f'ProxyError: Tor endpoint {self.port}: {error}')
                # 97 includes SOCKS replies from a reachable Tor listener:
                # general circuit failure / destination unreachable / refused.
                # It does not establish that the local proxy is dead.
                raise self.module.DeferredFetch(
                    f'curl {result.returncode} via Tor port {self.port}: {error}',
                    timeout_seconds=elapsed if result.returncode == 28 else None)
            status = int(http_code)
            headers = {}
            for line in head.read_text(errors='replace').splitlines():
                if line.startswith('HTTP/'):
                    headers = {}
                elif ':' in line:
                    key, value = line.split(':', 1)
                    headers[key.strip()] = value.strip()
            if status in (429, 503):
                retry = next((v for k, v in headers.items() if k.lower() == 'retry-after'), '')
                try:
                    seconds = float(retry)
                except ValueError:
                    try:
                        seconds = email.utils.parsedate_to_datetime(retry).timestamp() - time.time()
                    except (ValueError, TypeError, AttributeError):
                        seconds = None
                managed = bool(getattr(self.module, 'SOCKS_SOCKET', None))
                delay = max(self.http_cooldown_seconds, seconds or 0)
                if status == 429 and managed and seconds is None:
                    interval = self.gate.throttle_managed_worker(self.port, delay)
                    report(f'TOR {self.port}: HTTP 429; worker pause {delay:g}s, pool spacing {interval:g}s.')
                elif status == 429 and not managed:
                    config_dir = getattr(self.module, 'TOR_CONFIG_DIR', Path.home() / 'etc/tor')
                    try:
                        tor_new_identity(config_dir, self.port)
                    except (OSError, ValueError) as error:
                        report(f'TOR {self.port}: HTTP 429; NEWNYM failed ({type(error).__name__}: {error}); pausing only this worker.')
                    else:
                        delay = max(15, seconds or 0)
                        report(f'TOR {self.port}: HTTP 429; NEWNYM accepted; worker pause {delay:g}s. Exit IP change is not guaranteed.')
                    self.gate.backoff(delay, self.port)
                else:
                    if managed and status == 429:
                        delay = max(self.gate.interval, seconds)
                    scope = 'pool' if managed else 'worker'
                    report(f'TOR {self.port}: HTTP {status}; {scope} cooldown {delay:g}s.')
                    self.gate.backoff(delay, 'managed' if managed else self.port)
            destination = getattr(self.module, 'RESPONSE_PATH', None)
            if destination is None:
                content = body.read_bytes()
            else:
                body.replace(destination)
                content = None
            return SimpleNamespace(status_code=status, url=url, headers=headers,
                                   content=content, request_started_epoch=started,
                                   tor_port=self.port)



def parse_ports(text):
    ports = []
    for part in text.split(','):
        if '-' in part:
            start, end = map(int, part.split('-', 1))
            ports.extend(range(start, end + 1))
        else:
            ports.append(int(part))
    if not ports or len(set(ports)) != len(ports) or any(p < 1 or p > 65535 for p in ports):
        raise argparse.ArgumentTypeError('Use distinct ports, for example 9051-9054')
    return ports



def domain_stage(row):
    selection = str(STATE) + row.get('date_scope', '')
    return MIRROR/'.wayback-machine-download'/'staging'/key(selection)[:12]/row['domain']


def publish_stage(source, destination):
    """Rename new host trees atomically; merge shared hosts without overwriting captures."""
    if destination.is_symlink() or source.is_symlink():
        raise ValueError('Symlink in mirror publication')
    if source.is_dir():
        if not destination.exists():
            try:
                source.rename(destination)
                return
            except OSError as error:
                if error.errno not in (errno.EEXIST, errno.ENOTEMPTY):
                    raise
        for entry in source.iterdir():
            publish_stage(entry, destination/entry.name)
        source.rmdir()
    else:
        try:
            os.link(source, destination)
        except FileExistsError:
            if not filecmp.cmp(source, destination, shallow=False):
                raise ValueError(f'Conflicting capture: {destination.relative_to(MIRROR)}')
        source.unlink()


# External capture parsing and storage.
WAYBACK = 'https://web.archive.org'
STAMP = re.compile(r'\d{14}')
REPLAY = re.compile(r'/web/(\d{14})[a-z_]*/(https?://.*)', re.I)
BASE_HREF = re.compile(r'''<base\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))''', re.I)
CSS_URL = re.compile(r'''url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)|@import\s+["']([^"']+)["']''', re.I)
CSS_TOKEN = re.compile(r'/\*.*?\*/|' + CSS_URL.pattern, re.I | re.S)
SCRIPT_URL = re.compile(r'''["']((?:https?:)?//[^"'\s<>]+?\.(?:css|m?js|png|gif|jpe?g|svg|webp|ico|swf|jar)(?:\?[^"'\s<>]*)?)["']''', re.I)
DOCUMENT_WRITE = re.compile(
    r"""\bdocument\s*\.\s*write(?:ln)?\s*\(\s*(?P<literal>'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")\s*\)""",
    re.S,
)
JS_ESCAPE = re.compile(r"\\(u\{[0-9A-Fa-f]{1,6}\}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{2}|\r\n|.)", re.S)
HTML_START = re.compile(rb'^\s*(?:<\?xml[^>]*>\s*)?(?:<!doctype\s+html|<html|<head|<body|<frameset)\b', re.I)
SIDECAR = '.external.json'
MANIFEST = 'meta.json'
LEGACY_INDEXES = ('external-captures.json', 'map.json')
NAME_LIMIT = 255
QUERY_SEPARATOR = '%3F'
WINDOWS_DEVICE = re.compile(r'(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9]|LPT[1-9])(?:\.|$)', re.I)
HTML_SUFFIXES = {'.html', '.htm', '.xhtml', '.shtml', '.php', '.asp', '.aspx', '.jsp', '.svg'}
CAPTURE_TYPES = {
    '.css': 'text/css', '.gif': 'image/gif', '.htm': 'text/html', '.html': 'text/html',
    '.jpeg': 'image/jpeg', '.jpg': 'image/jpeg', '.js': 'application/javascript',
    '.mjs': 'application/javascript', '.png': 'image/png', '.svg': 'image/svg+xml',
    '.webp': 'image/webp',
}
QUEUE_STATE = 'tmp.external-resources.sqlite3'


def instant(stamp):
    return dt.datetime.strptime(stamp, '%Y%m%d%H%M%S').replace(tzinfo=dt.timezone.utc)


def asset_replay_parts(url):
    parsed = urlsplit(url)
    if parsed.hostname != 'web.archive.org':
        return None
    path = parsed.path + ('?' + parsed.query if parsed.query else '')
    match = REPLAY.fullmatch(path)
    return match.groups() if match else None


def normalize_asset_url(value, base=''):
    value = value.strip()
    if not value or value.startswith('#'):
        return None
    try:
        joined = urljoin(base, value)
        archived = asset_replay_parts(joined)
        parsed = urlsplit(archived[1] if archived else joined)
        host = parsed.hostname
        if parsed.scheme not in ('http', 'https') or not host or parsed.username or parsed.password:
            return None
        host = host.rstrip('.').encode('idna').decode().lower()
        if not re.fullmatch(r'[a-z0-9][a-z0-9.-]*', host) or host == 'web.archive.org':
            return None
        port = parsed.port
    except (ValueError, UnicodeError):
        return None
    netloc = host + (f':{port}' if port and port != {'http': 80, 'https': 443}[parsed.scheme] else '')
    path = quote(parsed.path or '/', safe="/%:@!$&'()*+,;=-._~")
    query = quote(parsed.query, safe="/%?:@!$&'()*+,;=-._~[]")
    return urlunsplit((parsed.scheme, netloc, path, query, ''))


def same_host(a, b):
    return a.removeprefix('www.') == b.removeprefix('www.')


def same_resource(a, b):
    a, b = urlsplit(a), urlsplit(b)
    return (same_host(a.netloc, b.netloc) and a.path == b.path and a.query == b.query)


def capture_url(stamp, url):
    return f'{WAYBACK}/web/{stamp}id_/{url}'


def css_urls(text, base, visit):
    for match in CSS_TOKEN.finditer(text):
        for group, value in enumerate(match.groups(), 1):
            if value is not None:
                value = re.sub(r'\\([0-9a-fA-F]{1,6})\s?|\\(.)',
                               lambda m: chr(int(m[1], 16)) if m[1] and 0 < int(m[1], 16) <= 0x10ffff
                               else m[2] or '\ufffd', value)
                imported = group == 4 or text[max(0, match.start()-32):match.start()].rstrip().lower().endswith('@import')
                visit(value, base, 'css' if imported else 'asset')
                break


def script_urls(text, base, visit):
    for match in SCRIPT_URL.finditer(text):
        url = match[1]
        suffix = Path(url.partition('?')[0]).suffix.lower()
        visit(url, base, {'.css': 'css', '.js': 'script', '.mjs': 'script'}.get(suffix, 'asset'))
    controls = {'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '0': '\0'}

    def unescape_js(match):
        escaped = match[1]
        if escaped.startswith(('u', 'x')) and len(escaped) > 1:
            value = int(escaped[1:].strip('{}'), 16)
            return chr(value) if value <= 0x10ffff else match[0]
        return '' if escaped in ('\r', '\n', '\r\n') else controls.get(escaped, escaped)

    for match in DOCUMENT_WRITE.finditer(text):
        markup = JS_ESCAPE.sub(unescape_js, match['literal'][1:-1])
        if '<' in markup:
            Markup(markup, base, visit)


class Markup(HTMLParser):
    """Visit embedded resource URLs without executing scripts or following links."""

    def __init__(self, text, base, visit):
        super().__init__()
        self.visit = visit
        match = BASE_HREF.search(text)
        if match:
            href = next(value for value in match.groups() if value is not None)
            base = normalize_asset_url(unescape(href), base) or base
        self.base = self.codebase = base
        self.raw_tag = None
        self.feed(text)
        self.close()

    def handle_starttag(self, tag, attrs):
        a = {k: v or '' for k, v in attrs}
        if tag in ('style', 'script'):
            self.raw_tag = tag
        if tag in ('object', 'applet'):
            self.codebase = urljoin(self.base, a['codebase'].rstrip('/') + '/') if a.get('codebase') else self.base
            for url in a.get('archive', '').split(','):
                self.visit(url, self.codebase, 'asset')
            if tag == 'object' or not a.get('archive'):
                self.visit(a.get('data' if tag == 'object' else 'code', ''), self.codebase, 'asset')
        if tag == 'param' and a.get('name', '').lower() in ('movie', 'src', 'url', 'archive', 'cabbase', 'filename'):
            self.visit(a.get('value', ''), self.codebase, 'asset')
        kinds = {'script':'script', 'iframe':'html', 'frame':'html', 'img':'image', 'input':'image',
                 'embed':'asset', 'audio':'asset', 'video':'asset', 'source':'asset', 'track':'asset'}
        if tag in kinds and 'src' in a:
            self.visit(a['src'], self.base, kinds[tag])
        for name in ('background', 'poster', 'lowsrc', 'dynsrc', 'data-src', 'data-original', 'data-lazy-src'):
            if name in a:
                self.visit(a[name], self.base, 'image')
        if tag in ('image', 'use'):
            self.visit(a.get('href') or a.get('xlink:href', ''), self.base, 'image')
        if tag == 'link' and 'href' in a:
            rel = set(a.get('rel', '').lower().split())
            if 'stylesheet' in rel:
                self.visit(a['href'], self.base, 'css')
            elif rel & {'icon', 'preload', 'modulepreload'}:
                self.visit(a['href'], self.base, {'style':'css', 'script':'script', 'image':'image'}.get(a.get('as'), 'asset'))
            elif 'alternate' in rel and a.get('type') in ('application/rss+xml', 'application/atom+xml'):
                self.visit(a['href'], self.base, 'xml')
        if tag in ('img', 'source', 'link'):
            srcset = a.get('srcset') or a.get('imagesrcset', '')
            pos = 0
            while pos < len(srcset):
                match = re.match(r'[\s,]*([^\s]+)', srcset[pos:])
                if not match:
                    break
                token = match[1]
                self.visit(token.rstrip(','), self.base, 'image')
                pos += match.end()
                if not token.endswith(','):
                    comma = srcset.find(',', pos)
                    pos = len(srcset) if comma < 0 else comma + 1
        if tag == 'iframe' and a.get('srcdoc'):
            Markup(a['srcdoc'], self.base, self.visit)
        if 'style' in a:
            css_urls(a['style'], self.base, self.visit)

    def handle_endtag(self, tag):
        if tag == self.raw_tag:
            self.raw_tag = None
        if tag in ('object', 'applet'):
            self.codebase = self.base

    def handle_data(self, data):
        if self.raw_tag == 'style':
            css_urls(data, self.base, self.visit)
        elif self.raw_tag == 'script':
            script_urls(data, self.base, self.visit)


def decode_text(data, mime=''):
    charset = re.search(r'charset\s*=\s*["\']?([\w-]+)', mime, re.I)
    if not charset:
        charset = re.search(rb'charset\s*=\s*["\']?([\w-]+)', data[:4096], re.I)
    encoding = charset[1] if charset else None
    if isinstance(encoding, bytes):
        encoding = encoding.decode('ascii')
    for name in ('utf-8-sig' if data.startswith(b'\xef\xbb\xbf') else encoding, 'utf-8', 'windows-1252'):
        if name:
            try:
                return data.decode(name)
            except (UnicodeError, LookupError):
                pass
    return data.decode('windows-1252', errors='replace')


def inferred_url(relative):
    host, _, *components = Path(relative).parts
    name, separator, query = components[-1].partition(QUERY_SEPARATOR)
    components[-1] = name
    path = '/'.join('' if part == '%00' else part for part in components)
    return normalize_asset_url(f'http://{host}/{path}' + ('?' + query if separator else ''))


def inferred_type(relative):
    name = Path(relative).name.partition(QUERY_SEPARATOR)[0]
    return CAPTURE_TYPES.get(Path(name).suffix.lower())


def compact_capture(relative, row):
    original = row['original_url']
    stored = {'path': relative, 'used-by': row.get('used-by', [])}
    if original != row.get('request_url', original):
        stored['original_url'] = original
    if row['content_type'] != inferred_type(relative):
        stored['content_type'] = row['content_type']
    if 'items' in row:  # Curated feeds have reconstruction bindings and pinned bytes.
        stored.update({key: row[key] for key in ('items', 'site', 'sha256')})
        if row.get('wayback_url', capture_url(row['capture'], original)) != capture_url(row['capture'], original):
            stored['wayback_url'] = row['wayback_url']
    return stored


class ExternalArchive:
    """Index loose response bodies by their requested and final full URLs."""

    def __init__(self, root, db=None):
        self.root = root.resolve()
        self.db = db
        self.records = defaultdict(list)
        self.files = {}
        self.manifest_path = self.root / MANIFEST
        self.uses_dirty = False
        self.last_manifest_write = 0.0
        self.failure_statuses = {}
        self.reviewed = {}
        self.manifest = self.load_manifest()
        self.locations = {}
        self.legacy = {}
        for relative, row in self.manifest.items():
            path = self.root / relative
            self.add(path, row)
            self.locations[capture_key(row)] = path
        for sidecar in sorted(self.root.glob(f'*/*/*{SIDECAR}')):
            if sidecar.relative_to(self.root).as_posix() in self.manifest:
                continue
            try:
                row = json.loads(sidecar.read_text())
                path = sidecar.with_name(row['file'])
                newer_path = self.locations.get(capture_key(row))
                if newer_path not in self.files:
                    self.add(path, row)
                self.legacy[sidecar] = path, row
            except (OSError, ValueError, TypeError, KeyError):
                # An interrupted write or a removed body does not prevent other
                # captures from loading. The downloader can recover the entry.
                continue

    def migrate_failures(self, urls):
        statuses = dict.fromkeys(urls, 'retry')
        if self.db is not None:
            for stamp, url, all_missing, any_saved, any_failure in self.db.execute(
                    "SELECT anchor,url,MIN(status='missing'),MAX(status='saved'),"
                    "MAX(status IN ('missing','retry')) FROM jobs GROUP BY anchor,url"):
                requested = capture_url(stamp, url)
                if any_saved:
                    statuses.pop(requested, None)
                elif any_failure:
                    statuses[requested] = 'missing' if all_missing else 'retry'
        return statuses

    def load_manifest(self):
        if self.manifest_path.exists():
            saved = json.loads(self.manifest_path.read_text())
            state = {}
            if self.db:
                state = {path: dict(site=site, requested_capture=anchor, bytes=size, sha256=digest)
                         for path, site, anchor, size, digest in self.db.execute('SELECT * FROM capture_state')}
            self.uses_dirty = 'missing_urls' in saved or 'failed_urls' in saved
            if not self.uses_dirty and any(not key.startswith(('http://', 'https://')) for key in saved):
                saved['failed_urls'] = []  # Early path indexes stored outcomes only in SQLite.
            self.failure_statuses = read_failure_statuses(saved, self.manifest_path, self.migrate_failures, self.reviewed)
            rows = {}
            for key, entry in saved.items():
                replay = asset_replay_parts(key)
                if not replay:
                    self.uses_dirty = True  # Older captures were indexed by local path.
                for metadata in entry.get('captures', [entry]):
                    relative = metadata['path'] if replay else key
                    capture = Path(relative).parts[1]
                    row = {**state.get(relative, {}), **metadata}
                    if replay:
                        if capture != replay[0]:
                            raise ValueError(f'Capture timestamp mismatch: {key} and {relative}')
                        row['request_url'] = replay[1]
                    original = row.get('original_url') or (replay[1] if replay else inferred_url(relative))
                    row.update(original_url=original, capture=capture)
                    row.setdefault('content_type', inferred_type(relative))
                    row.setdefault('wayback_url', capture_url(capture, original))
                    rows[relative] = row
            return dict(sorted(rows.items()))
        for name in LEGACY_INDEXES:
            try:
                old = json.loads((self.root / name).read_text())
            except FileNotFoundError:
                continue
            if all(isinstance(row, dict) for row in old.values()):
                return old
            if self.manifest_path.exists():
                return self.load_manifest()
            raise ValueError(f'Missing capture index for {name}')
        return {}

    def add(self, path, row):
        if path.resolve() != path or not path.is_relative_to(self.root):
            raise ValueError(f'External capture outside its directory: {path}')
        relative = path.relative_to(self.root)
        capture = row['capture']
        original = normalize_asset_url(row['original_url'])
        if (len(relative.parts) < 3 or not original or not STAMP.fullmatch(capture)
                or relative.parts[:2] != (urlsplit(original).hostname, capture)):
            raise ValueError(f'Invalid external capture path: {path}')
        if not path.is_file():
            return
        instant(capture)
        if 'bytes' in row and path.stat().st_size != row['bytes']:
            return
        mime = row['content_type']
        if not mime or not re.fullmatch(r'[\x20-\x7e]+', mime):
            return
        record = dict(row, original_url=original, path=path)
        self.files[path] = record
        for url in {normalize_asset_url(row['original_url']), normalize_asset_url(row.get('request_url', row['original_url']))} - {None}:
            rows = self.records[url]
            rows[:] = [other for other in rows if other['path'] != path]
            rows.append(record)

    def register(self, path, row):
        relative = path.relative_to(self.root).as_posix()
        previous = self.manifest.get(relative, {})
        row['used-by'] = list(previous.get('used-by', []))
        self.manifest[relative] = row
        if row.get('referring_page'):
            self.record_use(relative, row['site'], row['requested_capture'], row['referring_page'])
        self.locations[capture_key(row)] = path
        if self.db:
            self.record_download(relative, row)

    def record_download(self, relative, row):
        self.db.execute('INSERT OR REPLACE INTO capture_state VALUES (?,?,?,?,?)',
                        (relative, row['site'], row['requested_capture'], row['bytes'], row['sha256']))

    def record_use(self, path, site, stamp, referrer):
        if path not in self.manifest or not referrer:
            return False
        uses = self.manifest[path].setdefault('used-by', [])
        use = dict(site=site, capture=stamp, url=referrer)
        if use in uses:
            return False
        self.uses_dirty = True
        uses.append(use)
        uses.sort(key=lambda entry: (entry['site'], entry['capture'], entry['url']))
        return True

    def update_job_uses(self, relative, site, url, stamp):
        for referrer, in self.db.execute(
                'SELECT referrer FROM asset_referrers WHERE site=? AND url=? AND anchor=?', (site, url, stamp)):
            self.record_use(relative, site, stamp, referrer)
        if self.uses_dirty and time.monotonic() - self.last_manifest_write >= 5:
            self.write_manifest()

    def sync_uses(self):
        # SQLite also preserves referrers discovered after a job was saved.
        changed = any('used-by' not in row for row in self.manifest.values())
        for path, site, stamp, url in self.db.execute(
                "SELECT j.detail,j.site,j.anchor,r.referrer FROM jobs j JOIN asset_referrers r "
                "USING(site,url,anchor) WHERE j.status='saved'"):
            changed |= self.record_use(path, site, stamp, url)
        if changed or self.uses_dirty:
            for row in self.manifest.values():
                row.setdefault('used-by', [])
            self.write_manifest()

    def write_manifest(self):
        if self.db:
            self.db.commit()
        captures = defaultdict(list)
        for path, row in self.manifest.items():
            url = capture_url(row['capture'], row.get('request_url', row['original_url']))
            captures[url].append(compact_capture(path, row))
        # Redirects can give the same request more than one saved destination.
        stored = {url: rows[0] if len(rows) == 1 else {'captures': rows} for url, rows in captures.items()}
        stored = with_failure_entries(stored, self.failure_statuses, self.reviewed)
        atomic_write(self.manifest_path, (json.dumps(stored, indent=2, sort_keys=True) + '\n').encode())
        self.uses_dirty = False
        self.last_manifest_write = time.monotonic()

    def migrate_indexes(self):
        legacy = [self.root / name for name in LEGACY_INDEXES if (self.root / name).exists()]
        if not legacy:
            return
        if not self.manifest_path.exists():
            for path, row in self.manifest.items():
                self.record_download(path, row)
            self.write_manifest()
        for path in legacy:
            path.unlink(missing_ok=True)

    def nearest(self, url, stamp, established_only=False):
        target = instant(stamp)
        entries = self.records.get(url, ())
        if established_only:
            entries = [row for row in entries if stamp in (row['capture'], row.get('requested_capture'))]
        return min(entries, key=lambda row: (abs(instant(row['capture']) - target), row['capture']), default=None)


class Transient(Exception):
    pass


class LimitReached(Exception):
    pass


def wayback_target(url):
    try:
        parsed = urlsplit(url)
        if (parsed.scheme == 'https' and parsed.hostname == 'web.archive.org'
                and parsed.port in (None, 443) and parsed.username is None):
            return
    except ValueError:
        pass
    raise Unavailable('Redirect left Wayback')


def read_body(body, limit=None):
    if isinstance(body, Path):
        with body.open('rb') as stream:
            return stream.read(-1 if limit is None else limit)
    return body[:limit]


class CaptureLookup:
    def __init__(self, request, max_bytes):
        self.request = request
        self.max_bytes = max_bytes
        self.cdx_retry_at = 0

    def cdx_nearest(self, url, stamp):
        if time.monotonic() < self.cdx_retry_at:
            return [], [Transient('CDX temporarily unavailable')]
        candidates = set()
        errors = []
        for bound, limit in (('to', '-20'), ('from', '20')):
            params = {'url': url, 'matchType': 'exact', 'output': 'json',
                      'fl': 'timestamp,original', 'filter': 'statuscode:(2[0-9][0-9]|30[1278])',
                      bound: stamp, 'limit': limit}
            try:
                _, _, payload = self.request(WAYBACK + '/cdx/search/cdx?' + urlencode(params), 2_000_000)
                body = read_body(payload)
                rows = json.loads(body)
                if not isinstance(rows, list) or rows and rows[0] != ['timestamp', 'original']:
                    raise ValueError('Unexpected CDX response')
                for capture, original in rows[1:]:
                    if STAMP.fullmatch(capture) and (original := normalize_asset_url(original)) and same_resource(url, original):
                        instant(capture)
                        candidates.add((capture, original))
            except (Transient, Unavailable, ValueError, IndexError, TypeError) as error:
                errors.append(error)
        if len(errors) == 2:
            self.cdx_retry_at = time.monotonic() + 30
        target = instant(stamp)
        return sorted(candidates, key=lambda pair: (abs(instant(pair[0]) - target), pair[0], pair[1] != url)), errors

    def fetch(self, url, stamp, kind, cached):
        candidates, errors = self.cdx_nearest(url, stamp)
        # Identity replay can still find a capture when CDX is unavailable, or
        # when only the archived redirect/revisit record can be replayed.
        petabox = None
        for capture, original in dict.fromkeys(candidates + [(stamp, url)]):
            try:
                saved = cached(original, capture)
                if saved is not None:
                    check_local_petabox(saved['path'])
                    return (saved['capture'], saved['original_url'], saved['wayback_url'],
                            saved['content_type'], saved['path'])
                fetched, headers, body = self.request(capture_url(capture, original), self.max_bytes)
                resolved = asset_replay_parts(fetched)
                if not resolved:
                    raise Transient('Missing archive capture timestamp')
                capture, final = resolved
                final = normalize_asset_url(final)
                if headers.get('Memento-Datetime'):
                    capture = email.utils.parsedate_to_datetime(headers['Memento-Datetime']).astimezone(dt.timezone.utc).strftime('%Y%m%d%H%M%S')
                instant(capture)
                if not final:
                    raise Transient('Missing original resource URL')
                prefix = read_body(body, 4096)
                if not prefix and not headers.get('Memento-Datetime'):
                    raise Transient('Empty response without a capture header')
                mime = response_type(headers.get('Content-Type', ''), final, kind, prefix)
                return capture, final, fetched, mime, body
            except PetaboxCapture as error:
                petabox = error
            except Unavailable:
                continue
            except (Transient, ValueError, TypeError) as error:
                errors.append(error)
        if errors:
            reason = '; '.join(dict.fromkeys(map(str, errors)))
            raise Transient(reason)
        if petabox is not None:
            raise petabox
        raise Unavailable('No usable Wayback response')


def response_type(mime, url, kind, body):
    # Archived converters sometimes say text/html even when they sent JavaScript.
    if kind in ('script', 'css', 'image') and HTML_START.match(body[:4096]):
        raise Unavailable(f'HTML page in place of expected {kind}')
    if kind in ('script', 'css'):
        safe_type = {'script': 'application/javascript', 'css': 'text/css'}[kind]
        charset = re.search(r'charset\s*=\s*([\w-]+)', mime, re.I)
        return safe_type + ('; charset=' + charset[1] if charset else '')
    return mime or mimetypes.guess_type(urlsplit(url).path)[0] or 'application/octet-stream'


def atomic_write(path, data):
    with tempfile.NamedTemporaryFile(dir=path.parent, prefix='.external-', delete=False) as output:
        temporary = Path(output.name)
        try:
            output.write(data)
            output.close()
            temporary.replace(path)
        finally:
            temporary.unlink(missing_ok=True)


def capture_key(row):
    return row['capture'], row['original_url'], row.get('request_url', row['original_url'])


def portable_component(value):
    encoded = quote(value, safe="!$&'()+,;=@%-._~") or '%00'
    trimmed = encoded.rstrip('.')
    encoded = trimmed + '%2E' * (len(encoded) - len(trimmed))
    if WINDOWS_DEVICE.match(encoded) or encoded.casefold() == '.git':
        encoded = f'%{ord(encoded[0]):02X}' + encoded[1:]
    return encoded


def path_available(root, path):
    if len(os.fsencode(path)) >= 4096:
        return False
    components = path.relative_to(root).parts
    current = root
    for index, component in enumerate(components):
        match = next((entry for entry in current.iterdir() if entry.name.casefold() == component.casefold()), None)
        if match is None:
            return True
        if index == len(components) - 1 or match.name != component or match.is_symlink() or not match.is_dir():
            return False
        current = match
    return False


def capture_path(archive, row):
    existing = archive.locations.get(capture_key(row))
    if existing is not None:
        relative = existing.relative_to(archive.root).as_posix()
        return existing, archive.manifest[relative].get('hashed', [])

    original = urlsplit(row['original_url'])
    directory = archive.root / original.hostname / row['capture']
    components = original.path.removeprefix('/').split('/')
    if not components[-1]:
        mime = row['content_type'].split(';', 1)[0]
        components[-1] = 'index' + (mimetypes.guess_extension(mime) or '')

    names = [portable_component(component) for component in components]
    hashed = []
    extension = re.search(r'\.[a-zA-Z0-9]{1,12}$', names[-1])
    extension = extension[0] if extension else ''
    for index, name in enumerate(names):
        if len(name) > NAME_LIMIT:
            suffix = extension if index == len(names) - 1 else ''
            names[index] = '~' + hashlib.sha256(components[index].encode()).hexdigest() + suffix
            hashed = ['path']

    if original.query:
        query = portable_component(original.query)
        if len(names[-1] + QUERY_SEPARATOR + query) > NAME_LIMIT and len(query) > 64:
            query = hashlib.sha256(original.query.encode()).hexdigest()
            hashed.append('query')
        if len(names[-1] + QUERY_SEPARATOR + query) > NAME_LIMIT:
            names[-1] = '~' + hashlib.sha256(components[-1].encode()).hexdigest() + extension
            if 'path' not in hashed:
                hashed.append('path')
        names[-1] += QUERY_SEPARATOR + query

    path = directory.joinpath(*names)
    if path_available(archive.root, path):
        return path, hashed

    digest = hashlib.sha256(json.dumps(capture_key(row)).encode()).hexdigest()
    for folder in (path.parent, directory):
        path = folder / ('~' + digest + extension)
        if path_available(archive.root, path):
            return path, ['url']
    raise Unavailable(f'No portable destination for {row["original_url"]}')


def save_capture(archive, url, stamp, kind, referring_page, site, result):
    capture, original, fetched, mime, payload = result
    body = read_body(payload)
    row = {'request_url': url, 'original_url': original, 'wayback_url': fetched,
           'capture': capture, 'requested_capture': stamp, 'content_type': mime, 'kind': kind,
           'bytes': len(body), 'sha256': hashlib.sha256(body).hexdigest(),
           'site': site, 'referring_page': referring_page}
    path, hashed = capture_path(archive, row)
    if hashed:
        row['hashed'] = hashed
    if path.resolve() != path:
        raise Unavailable(f'External capture destination contains a symlink: {path}')
    path.parent.mkdir(parents=True, exist_ok=True)
    archive.register(path, row)
    archive.write_manifest()
    atomic_write(path, body)
    archive.add(path, row)
    return archive.files[path]


SCHEMA = """
CREATE TABLE IF NOT EXISTS capture_state (
    path TEXT PRIMARY KEY, site TEXT NOT NULL, anchor TEXT NOT NULL,
    bytes INTEGER NOT NULL, sha256 TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sources (
    path TEXT, site TEXT, mtime INTEGER, size INTEGER, PRIMARY KEY(path, site)
);
CREATE TABLE IF NOT EXISTS jobs (
    site TEXT, url TEXT, anchor TEXT, kind TEXT, referrer TEXT,
    status TEXT DEFAULT 'pending', last_run INTEGER DEFAULT 0, detail TEXT DEFAULT '',
    PRIMARY KEY(site, url, anchor)
);
CREATE INDEX IF NOT EXISTS job_status ON jobs(status, last_run);
CREATE TABLE IF NOT EXISTS asset_referrers (
    site TEXT, url TEXT, anchor TEXT, referrer TEXT, PRIMARY KEY(site,url,anchor,referrer)
);
INSERT OR IGNORE INTO asset_referrers SELECT site,url,anchor,referrer FROM jobs;

"""



# Keep job outcomes compatible with the standalone backfill. Membership limits
# each worker to URLs discovered by its own mirror selection and referring site.
MEMBERSHIP = """
CREATE TABLE IF NOT EXISTS mirror_asset_queue (
    id INTEGER PRIMARY KEY, selection TEXT NOT NULL, site TEXT NOT NULL,
    url TEXT NOT NULL, anchor TEXT NOT NULL, expanded INTEGER NOT NULL DEFAULT 0, referrer_path TEXT,
    UNIQUE(selection,site,url,anchor)
);
CREATE INDEX IF NOT EXISTS mirror_asset_order ON mirror_asset_queue(selection,site,id);
"""


@contextmanager
def open_asset_store(root, selection):
    root.mkdir(parents=True, exist_ok=True)
    state = root / QUEUE_STATE
    with state.with_suffix('.lock').open('a') as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError as error:
            raise RuntimeError('Another downloader is writing this external archive') from error
        db = sqlite3.connect(state, check_same_thread=False)
        try:
            db.executescript(SCHEMA + MEMBERSHIP)
            if 'referrer_path' not in {row[1] for row in db.execute('PRAGMA table_info(mirror_asset_queue)')}:
                db.execute('ALTER TABLE mirror_asset_queue ADD COLUMN referrer_path TEXT')
            archive = ExternalArchive(root, db)
            archive.migrate_indexes()
            archive.sync_uses()
            try:
                yield AssetStore(archive, selection)
            finally:
                archive.sync_uses()
        finally:
            db.close()


class AssetStore:
    def __init__(self, archive, selection):
        self.archive = archive
        self.db = archive.db
        self.selection = selection
        self.site_scopes = {}
        self.lock = threading.RLock()
        self.fetch_locks = WeakValueDictionary()

    def site_selection(self, site):
        return self.selection + self.site_scopes.get(site, '')

    def record_failure(self, url, status):
        # Capture entries and failures share one manifest and one writer lock.
        with self.lock:
            urls = self.archive.failure_statuses
            if urls.get(url) == status:
                return
            self.archive.reviewed.pop(url, None)
            if status is None:
                del urls[url]
            else:
                urls[url] = status
            self.archive.write_manifest()

    def scan_local_captures(self, row):
        """Seed this selection from published and staged primary response bodies."""
        site = row['domain']
        with self.lock, self.db:
            self.db.execute('DELETE FROM mirror_asset_queue WHERE selection=? AND site=?',
                            (self.site_selection(site), site))
        roots = list(dict.fromkeys((MIRROR, DUMP)))
        roots.extend((MIRROR/'.wayback-machine-download'/'staging').glob('*/' + site))
        scheme = urlsplit(row['url']).scheme
        originals = local_capture_urls(row)
        count = 0
        for root in roots:
            if not root.is_dir() or root.is_symlink():
                continue
            for host in root.iterdir():
                if not family(host.name.split(':')[0], site) or host.is_symlink() or not host.is_dir():
                    continue
                for capture in host.iterdir():
                    stamp = capture.name
                    if (not STAMP.fullmatch(stamp) or not in_date_range(stamp, row['start'], row['end'])
                            or capture.is_symlink() or not capture.is_dir()):
                        continue
                    for body in capture.rglob('*'):
                        if STOP.is_set():
                            return count
                        if body.is_symlink() or not body.is_file():
                            continue
                        relative = body.relative_to(root)
                        original = originals.get(relative)
                        if not original and body.name == 'index.html':
                            original = originals.get(relative.parent)
                        if not original:
                            path = body.relative_to(capture).as_posix()
                            if '?' in path:
                                path = path.removesuffix('/index.html')
                            original = f'{scheme}://{host.name}/{path}'
                        mime = mimetypes.guess_type(body.name.partition('?')[0])[0] or ''
                        self.discover(site, original, stamp, body, mime)
                        count += 1
        return count

    def discover(self, site, original, stamp, content, mime='', external=False, source_path=None):
        suffix = Path(urlsplit(original).path).suffix.lower()
        media = mime.partition(';')[0].lower()
        if suffix == '.css' or media == 'text/css':
            parse = css_urls
        elif suffix in ('.js', '.mjs') or 'javascript' in media:
            parse = script_urls
        elif suffix in HTML_SUFFIXES or media in ('text/html', 'application/xhtml+xml', 'image/svg+xml') or HTML_START.match(read_body(content, 4096)):
            parse = Markup
        else:
            return
        refs = {}
        source_host = urlsplit(original).netloc
        def visit(value, base, kind):
            url = normalize_asset_url(value, base)
            if url and (external or not same_host(urlsplit(url).netloc, source_host)):
                refs.setdefault(url, kind)
        parse(decode_text(read_body(content), mime), original, visit)
        if refs:
            path = source_path or (content if isinstance(content, Path) else None)
            referrer_path = os.path.relpath(path, MIRROR) if path is not None else None
            with self.lock, self.db:
                self.db.executemany('INSERT OR IGNORE INTO jobs(site,url,anchor,kind,referrer) VALUES (?,?,?,?,?)',
                                    ((site, url, stamp, kind, original) for url, kind in refs.items()))
                self.db.executemany('INSERT OR IGNORE INTO asset_referrers VALUES (?,?,?,?)',
                                    ((site, url, stamp, original) for url in refs))
                self.db.executemany(
                    'INSERT INTO mirror_asset_queue(selection,site,url,anchor,referrer_path) VALUES (?,?,?,?,?) '
                    'ON CONFLICT(selection,site,url,anchor) DO UPDATE SET referrer_path=excluded.referrer_path '
                    'WHERE mirror_asset_queue.referrer_path IS NULL AND excluded.referrer_path IS NOT NULL',
                    ((self.site_selection(site), site, url, stamp, referrer_path) for url in refs))

    def jobs(self, site, unfinished=False):
        condition = "AND (j.status IN ('pending','retry') OR (j.status='saved' AND q.expanded=0)) " if unfinished else ""
        cursor = 0
        while True:
            with self.lock:
                row = self.db.execute(
                    'SELECT q.id,j.url,j.anchor,j.kind,j.referrer,j.status,j.detail,q.referrer_path FROM mirror_asset_queue q '
                    'JOIN jobs j USING(site,url,anchor) WHERE q.selection=? AND q.site=? AND q.id>? '
                    f'{condition}ORDER BY q.id LIMIT 1', (self.site_selection(site), site, cursor)).fetchone()
            if row is None:
                return
            cursor = row[0]
            yield row

    def outcome(self, site):
        with self.lock:
            return dict(self.db.execute(
                "SELECT CASE WHEN j.status='saved' AND q.expanded=0 THEN 'pending' ELSE j.status END AS outcome, COUNT(*) "
                "FROM mirror_asset_queue q JOIN jobs j USING(site,url,anchor) "
                "WHERE q.selection=? AND q.site=? GROUP BY outcome", (self.site_selection(site), site)))

    def sites_with_failed_assets(self, rows):
        failed = {url for url, status in self.archive.failure_statuses.items() if status == 'retry'}
        if not failed:
            return set()
        origins = set()
        known = set()
        for site, url, stamp in self.db.execute('SELECT site,url,anchor FROM jobs'):
            requested = capture_url(stamp, url)
            if requested in failed:
                origins.add(site)
                known.add(requested)
        result = set()
        for row in rows:
            site = row['domain']
            if site not in origins and known == failed:
                continue
            if not self.outcome(site):
                # A different date selection or a rebuilt DB needs fresh, in-scope referrers.
                self.scan_local_captures(row)
                for _, url, stamp, _, referrer, _, _, _ in self.jobs(site):
                    if STOP.is_set():
                        return result
                    for record in self.archive.records.get(url, ()):
                        use = dict(site=site, capture=stamp, url=referrer)
                        if use in record.get('used-by', ()):
                            self.discover(site, record['original_url'], record['capture'], record['path'],
                                          record['content_type'], external=True)
            if any(capture_url(job[2], job[1]) in failed for job in self.jobs(site, unfinished=True)):
                result.add(site)
        return result

    def cached_capture(self, original, capture):
        with self.lock:
            for row in self.archive.records.get(original, ()):
                if row['capture'] == capture and row['path'].is_file():
                    return row

    def resolve(self, site, job, lookup, offline):
        job_id, url, anchor, kind, referrer, status, detail, referrer_path = job
        requested = capture_url(anchor, url)
        with self.lock:
            fetch_lock = self.fetch_locks.setdefault((url, anchor), threading.Lock())
        with fetch_lock:
            with self.lock:
                saved = self.archive.files.get(self.archive.root / detail) if status == 'saved' else None
                saved = saved or self.archive.nearest(url, anchor, established_only=True)
                prior_status = self.archive.failure_statuses.get(requested)
            try:
                if saved and saved['path'].is_file():
                    try:
                        check_local_petabox(saved['path'])
                    except PetaboxCapture:
                        saved = None  # Another indexed capture may still be usable.
                if saved is None or not saved['path'].is_file():
                    if prior_status in ('missing', 'petabox'):
                        if status == 'missing':
                            return None
                        if prior_status == 'petabox':
                            raise PetaboxCapture()
                        raise Unavailable('Previously checked: no usable Wayback response')
                    if offline:
                        raise Transient('External capture missing from offline cache')
                    if not referrer_path:  # Queued by an older downloader.
                        parent = self.cached_capture(referrer, anchor)
                        path = parent['path'] if parent else mirror_path(dict(url=referrer, capture=anchor))
                        if path.is_dir():
                            path = path/'index.html'
                        referrer_path = os.path.relpath(path, MIRROR) if path.is_file() else capture_url(anchor, referrer)
                    token = EXTERNAL_REFERRER.set(referrer_path)
                    try:
                        result = lookup.fetch(url, anchor, kind, self.cached_capture)
                    finally:
                        EXTERNAL_REFERRER.reset(token)
                    with self.lock:
                        existing = self.archive.locations.get((result[0], result[1], url))
                        saved = self.archive.files.get(existing)
                        if saved is None or not saved['path'].is_file():
                            saved = save_capture(self.archive, url, anchor, kind, referrer, site, result)
                self.discover(site, saved['original_url'], saved['capture'], saved['path'],
                              saved['content_type'], external=True)
                status, detail = 'saved', str(saved['path'].relative_to(self.archive.root))
            except Unavailable as error:
                status, detail = error.status, str(error)
            except Transient as error:
                status, detail = 'retry', str(error)
            except (DeferredFetch, LimitReached):
                if not offline and not STOP.is_set():
                    self.record_failure(requested, 'retry')
                raise
            with self.lock, self.db:
                job_status = 'missing' if status == 'petabox' else status
                self.db.execute('UPDATE jobs SET status=?, detail=? WHERE site=? AND url=? AND anchor=?',
                                (job_status, detail, site, url, anchor))
                self.db.execute('UPDATE mirror_asset_queue SET expanded=? WHERE id=?', (status == 'saved', job_id))
                if status == 'saved':
                    self.archive.update_job_uses(detail, site, url, anchor)
                if status == 'saved' or not (offline or STOP.is_set()):
                    self.record_failure(requested, None if status == 'saved' else status)
            return saved['path'] if status == 'saved' else None


class MirrorWorker:
    def __init__(self, args, cache, number, tor=None):
        tor = tor or SimpleNamespace(RateGate=RateGate, TorSession=TorSession)
        self.args, self.cache = args, cache
        self.http_cooldown_seconds = getattr(args, 'http_cooldown_seconds', HTTP_COOLDOWN_SECONDS)
        self.stage = None
        self.root = STATE/'workers'/str(number)
        self.root.mkdir(parents=True, exist_ok=True)
        def stop_before_transfer():
            # A different worker can detect an outage while this one waits for its rate slot.
            cache.network.wait()
            return STOP.is_set() or (STATE/'STOP').exists()
        self.gate = tor.RateGate(RATE_DIR or BASE/'tor-top', args.interval, stop=stop_before_transfer)
        self.port = args.ports[number] if args.ports else None
        sockets = getattr(args, 'tor_sockets', None)
        endpoint = sockets[number % len(sockets)] if sockets else None
        if endpoint:
            self.port = f'managed-{number % len(sockets) + 1}'
        if self.port:
            shim = SimpleNamespace(BASE=self.root, requests=requests, DeferredFetch=DeferredFetch, save=save,
                                   SOCKS_SOCKET=endpoint,
                                   MAX_RESPONSE_BYTES=args.max_file_bytes, ResponseLimitExceeded=ValueError,
                                   TOR_CONFIG_DIR=getattr(args, 'tor_config_dir', Path.home() / 'etc/tor'))
            self.session = tor.TorSession(shim, self.port, self.gate, self.http_cooldown_seconds)
        else:
            self.session = requests.Session()
            self.session.headers['User-Agent'] = 'HistoricalWebsiteResearch/1.0 (bounded archival asset review)'

    def working_path(self, path):
        if self.stage is not None and not path.exists() and path.is_relative_to(MIRROR):
            return self.stage / path.relative_to(MIRROR)
        return path

    def record_download(self, url, status, offline=False):
        if status and (offline or STOP.is_set()):
            return
        if self.cache.failed_downloads:
            self.cache.failed_downloads.update(url, status)

    @contextmanager
    def track_download(self, url, offline=False):
        try:
            yield
        except (OSError, ValueError) as error:
            self.record_download(url, error.status if isinstance(error, CaptureMissing) else 'retry', offline)
            raise
        else:
            self.record_download(url, None)

    def request(self, url, state, max_bytes=None):
        while True:
            self.cache.network.wait()
            try:
                return self._request_once(url, state, max_bytes)
            except NetworkOutage as outage:
                self.cache.network.recover(outage)

    def _request_once(self, url, state, max_bytes):
        if (STATE/'STOP').exists():STOP.set()
        if STOP.is_set(): raise DeferredFetch('Stopped')
        if state['requests'] >= self.args.max_requests: raise ValueError('network request limit')
        remaining=min(self.args.max_file_bytes,self.args.max_bytes-state.get('downloaded_bytes',0))
        if max_bytes is not None:
            remaining = min(remaining, max_bytes)
        if remaining<=0:raise ValueError('site download byte limit')
        if not url.startswith('https://web.archive.org/'):
            raise ValueError('Non-Wayback request rejected')
        state['requests'] += 1
        stamp = time.time_ns()
        body_path = self.root/(str(stamp)+'.body')
        meta_path = self.root/(str(stamp)+'.json')
        meta = dict(requested_url=url, started_utc=dt.datetime.now(dt.timezone.utc).isoformat(), tor_port=self.port)
        outcome = 'error'
        transfer_started = None
        to_disk = getattr(self.args, 'mode', None) == 'cdx' and '/web/' in urlsplit(url).path
        try:
            if self.port:
                self.session.module.MAX_RESPONSE_BYTES=remaining
                self.session.module.RESPONSE_PATH = body_path if to_disk else None
                response = self.session.get(url, allow_redirects=False)
                if not to_disk: body_path.write_bytes(response.content)
            else:
                self.gate.wait()
                report_download(url)
                transfer_started = time.monotonic()
                response = self.session.get(url, timeout=(20,45), allow_redirects=False, stream=True)
                meta.update(status=response.status_code, headers=dict(response.headers))
                length = 0
                try:
                    with body_path.open('wb') as partial:
                        for chunk in response.iter_content(65536):
                            partial.write(chunk); length += len(chunk)
                            if length > remaining:
                                raise ValueError('individual file size limit (partial response retained)')
                finally:
                    response.close()
                if response.status_code in (429,503):
                    retry = response.headers.get('Retry-After','')
                    try: delay=float(retry)
                    except ValueError:
                        try: delay=email.utils.parsedate_to_datetime(retry).timestamp()-time.time()
                        except (TypeError,ValueError): delay=0
                    self.gate.backoff(max(self.http_cooldown_seconds, delay))
            size = body_path.stat().st_size
            with body_path.open('rb') as stream:
                data = stream.read(16384) if to_disk else stream.read()
            meta.update(status=response.status_code, headers=dict(response.headers), bytes=size)
            if not to_disk: meta['sha256'] = key_bytes(data)
            if size > remaining: raise ValueError('individual file/site download size limit')
            outcome = response.status_code
            if response.status_code == 429 or response.status_code >= 500:
                raise DeferredFetch(f'Archive HTTP {response.status_code}',
                                    retry_in_pass=response.status_code not in (429, 503))
            return response.status_code, dict(response.headers), data, body_path, meta_path
        except InterruptedError as error:
            STOP.set();meta['error']=str(error)
            outcome = 'stopped'
            raise DeferredFetch('Stopped while waiting for rate limit') from error
        except requests.RequestException as error:
            meta['error'] = str(error)
            outage = local_network_outage(error, self.port)
            if outage:
                state['requests'] -= 1  # Preserve the request budget for the retry after reconnection.
                outcome = 'network offline'
                raise outage from error
            if isinstance(error,requests.exceptions.ProxyError):
                outcome = 'proxy error'
                STOP.set()
                print('DOWNLOAD STOP: local proxy/listener unavailable: ' + str(error), file=sys.stderr, flush=True)
                raise DeferredFetch('Local proxy unavailable: '+str(error)) from error
            if outcome == 'error':
                message = str(error).lower()
                timed_out = (isinstance(error, requests.exceptions.Timeout) or message.startswith('curl 28 ')
                             or 'timed out' in message or 'subprocess timeout' in message)
                outcome = 'timeout' if timed_out else 'transport error'
                if timed_out:
                    seconds = getattr(error, 'timeout_seconds', None)
                    if seconds is None and transfer_started is not None:
                        seconds = time.monotonic() - transfer_started
                    if seconds is not None:
                        meta['timeout_seconds'] = round(seconds, 3)
            if isinstance(error, DeferredFetch):
                raise
            raise DeferredFetch(str(error)) from error
        except ValueError as error:
            meta['error']=str(error)
            if 'size limit' in str(error).lower():
                outcome = 'size limit'
            raise
        finally:
            if self.port:
                transfer_started = getattr(self.session, 'transfer_started', None)
            elapsed = time.monotonic() - transfer_started if transfer_started is not None else None
            transferred=body_path.stat().st_size if body_path.exists() else 0
            if self.port:transferred=max(transferred,getattr(self.session.module,'LAST_RESPONSE_BYTES',0))
            state['downloaded_bytes']=state.get('downloaded_bytes',0)+transferred
            meta['retained_response_bytes']=transferred
            save(meta_path, meta)
            with LOCK:
                with (STATE/'requests.jsonl').open('a') as out: out.write(json.dumps(meta)+'\n')
            report_download(url, self.port, outcome, elapsed)
            self.last_download_outcome = outcome

    @contextmanager
    def cdx_lookup(self, target):
        self.last_download_outcome = None
        try:
            yield
        except (OSError, ValueError) as error:
            # A successful HTTP transfer can still contain an unusable index.
            # Cache and pagination failures may have no transfer at all.
            if self.last_download_outcome in (None, 200, 'error') and not STOP.is_set():
                report(f'CDX: {target}: {error}')
            raise

    def fetch(self, item, state):
        with self.cache.lock:
            lock = self.cache.fetch_locks.setdefault(item['url'], threading.Lock())
        with lock:
            return self._fetch(item, state)

    def _fetch(self, item, state):
        capture = item.get('capture') or state['anchor']
        # CDX already checked the exact destination on disk.
        if getattr(self.args, 'mode', None) != 'cdx' or DUMP != MIRROR:
            cached = self.cache.get(item['url'], capture, max_days=0 if item.get('capture') else 7,
                                    start=getattr(self.args, 'start', None), end=getattr(self.args, 'end', None))
            if cached: return cached
        url = 'https://web.archive.org/web/'+capture+'id_/'+item['url']
        if self.cache.failed_downloads:
            prior_status = self.cache.failed_downloads.status(url)
            if prior_status == 'petabox':
                raise PetaboxCapture()
            if prior_status == 'missing':
                raise CaptureMissing('Previously checked: no archived response')
        seen = set()
        for _ in range(6):
            if url in seen: raise ValueError('redirect loop')
            seen.add(url)
            status, headers, data, path, meta = self.request(url,state)
            if status == 200:
                error = archive_error(data)
                if error == 'petabox':
                    raise PetaboxCapture()
                if error:
                    raise DeferredFetch('Wayback infrastructure/error page, not an original site capture')
                parts = replay_parts(url,headers)
                if not parts: raise ValueError('No actual capture timestamp')
                record = dict(url=parts[1],capture=parts[0],path=str(path),metadata=str(meta),source='Wayback download')
                if getattr(self.args, 'mode', None) != 'cdx':
                    self.cache.add(parts[1],parts[0],path,str(meta),'Wayback download')
                return record
            if status in (301,302,303,307,308):
                headers = requests.structures.CaseInsensitiveDict(headers)
                url = urljoin(url, headers.get('Location', ''))
                if not url.startswith('https://web.archive.org/'):
                    # HTTP Wayback redirects may be upgraded; never follow a live target.
                    if url.startswith('http://web.archive.org/'): url='https:'+url[5:]
                    else: raise ValueError('Redirect leaves Wayback: '+url)
                if item.get('exact'):
                    target = replay_parts(url)
                    if (target and target[0] != capture and same_resource(item['url'], target[1])
                            and headers.get('X-Archive-Redirect-Reason') == 'found capture at ' + target[0]):
                        raise CaptureMissing(f"Exact capture {capture} unavailable: Wayback selected {target[0]} for {target[1]}")
                continue
            if status in (404,410): raise CaptureMissing('Not archived: HTTP '+str(status))
            raise DeferredFetch(f'Archive access failed: HTTP {status}', retry_in_pass=False)
        raise ValueError('redirect limit')

    def fetch_in_range(self, item, state, start, end):
        record = self.fetch(item, state)
        if in_date_range(record['capture'], start, end):
            return record
        # Nearest replay may select a capture just outside the user's range
        # even if one exists inside. Query the nearest edge of the range.
        params = {'url': item['url'], 'matchType': 'exact', **cdx_dates(start, end),
                  'fl': 'timestamp,original', 'filter': 'statuscode:200', 'output': 'json',
                  'limit': 1 if start and record['capture'] < start else -1}
        index_url = 'https://web.archive.org/cdx/search/cdx?' + urlencode(params)
        with self.cdx_lookup(item['url']), self.track_download(index_url):
            status, _, data, _, _ = self.request(index_url, state)
            if status != 200:
                raise DeferredFetch(f'CDX returned HTTP {status}')
            rows, _ = parse_cdx_page(data)
        if rows:
            stamp, original = rows[0]
            if in_date_range(stamp, start, end):
                try:
                    with self.track_download(capture_url(stamp, original)):
                        return self.fetch(dict(item, url=original, capture=stamp), state)
                except CaptureMissing:
                    # The original request succeeded outside the range. Only the indexed alternative is missing.
                    return record
        return record  # Caller records out_of_period without publishing the body.

    def add(self,state,url,role,referrer,depth=0,base=None):
        url=normalize(url,base or referrer)
        if not url: return
        if getattr(self.cache, 'external', None) and role != 'page' and not same_host(
                urlsplit(url).netloc, urlsplit(referrer).netloc):
            return  # The external asset queue handles embedded cross-host URLs.
        if role=='page':
            if not family(urlsplit(url).hostname,state['domain']): return
            if depth > self.args.depth: return
            if not PAGE_EXT.search(urlsplit(url).path) and Path(urlsplit(url).path).suffix: return
        items=state['items']
        item=items.get(url)
        if item:
            if referrer not in item['referrers']: item['referrers'].append(referrer)
            if base and base not in item.setdefault('contexts',[]):item['contexts'].append(base)
            # A nav link may later turn out to be an embedded frame dependency.
            if role in ('frame','asset') and item['role']=='page': item['role']=role
            return
        if len(items) >= 2000:
            state['reference_limit']=True;return
        items[url]=dict(url=url,role=role,referrers=[referrer],contexts=[base or referrer],depth=depth,status='pending',attempts=0)

    def discover(self,state,item,record,data):
        url=record['url'];path=urlsplit(url).path.lower()
        mime=mimetypes.guess_type(path)[0] or ''
        if record.get('metadata'):
            try:
                headers=json.loads(Path(record['metadata']).read_text()).get('headers',{})
                mime={k.lower():v for k,v in headers.items()}.get('content-type',mime)
            except (OSError,ValueError): pass
        if getattr(self.cache, 'external', None):
            self.cache.external.discover(state['domain'], url, record['capture'], data, mime,
                                         source_path=Path(record['path']))
        try:text=data.decode('utf-8-sig')
        except UnicodeDecodeError:
            match=re.search(r'charset\s*=\s*[\"\']?([\w-]+)', mime, re.I) or re.search(r'charset\s*=\s*[\"\']?([\w-]+)',data[:4096].decode('ascii','ignore'),re.I)
            try:text=data.decode(match[1] if match else 'windows-1252',errors='replace')
            except LookupError:text=data.decode('windows-1252',errors='replace')
        is_html = not path.endswith(('.js','.mjs','.css')) and bool(re.search(r'<(?:!doctype\s+html|html|head|body|frameset)\b', text[:12000],re.I))
        if is_html:
            item['is_html']=True
            state['html_pages']=sum(bool(i.get('is_html')) for i in state['items'].values())
            refs=References(text)
            if refs.overflow: state['reference_limit']=True
            base=normalize(refs.base,url) if refs.base else url
            base=base or url
            for value,role,codebase in sorted(refs.refs,key=lambda r:r[1]=='page'):
                effective=urljoin(base,codebase.rstrip('/')+'/') if codebase else base
                self.add(state,value,role,url,item['depth']+(1 if role in ('page','frame') else 0),effective)
        elif 'css' in mime or path.endswith('.css'):
            for value in css_refs(text): self.add(state,value,'asset',url,item['depth'])
        elif 'javascript' in mime or path.endswith(('.js','.mjs')):
            # Script literal relative URLs resolve in the embedding document's
            # context; source-relative candidates are also retained explicitly.
            for value in script_refs(text):
                for context in dict.fromkeys(item.get('contexts',item['referrers'])[:4]+[url]):
                    self.add(state,value,'script-asset',url,item['depth'],context)
        return is_html

    def index(self,state):
        params=dict(url=state['domain'],matchType='domain',output='json',fl='timestamp,original,mimetype,statuscode',
                    filter='statuscode:200',collapse='urlkey',limit=str(self.args.index_limit),
                    **cdx_dates(self.args.start, self.args.end))
        index_url = 'https://web.archive.org/cdx/search/cdx?' + urlencode(params)
        with self.track_download(index_url):
            status,headers,data,path,meta=self.request(index_url,state)
            if status!=200: raise DeferredFetch('CDX status '+str(status))
            try:
                result=json.loads(data)
                rows=[dict(zip(result[0],row)) for row in result[1:self.args.index_limit+1]] if result else []
            except (TypeError,ValueError,IndexError,KeyError): raise DeferredFetch('Invalid CDX response')
        for row in rows:
            url=row.get('original','')
            if ASSET_EXT.search(url): self.add(state,url,'indexed-asset','http://'+state['domain']+'/',0)
            elif PAGE_EXT.search(urlsplit(url).path) or not Path(urlsplit(url).path).suffix:
                self.add(state,url,'page','http://'+state['domain']+'/',1)
        state['index']=dict(status='saved',rows=len(rows),possibly_truncated=len(rows)>=self.args.index_limit,metadata=str(meta))

    def run_site(self,row,offline=False):
        domain=row['domain'];state_path=STATE/'domains'/(domain+'.json')
        state=json.loads(state_path.read_text()) if state_path.exists() else None
        start, end = self.args.start, self.args.end
        if state is None or state.get('date_scope') != row.get('date_scope'):
            url,anchor,source=seed_for(row)
            if not in_date_range(anchor, start, end):
                anchor, source = max(start or ANCHOR, ANCHOR), None
                if end:
                    anchor = min(anchor, end)
            state=dict(domain=domain,date_scope=row.get('date_scope'),anchor=anchor,homepage=normalize(url,url),items={},requests=0,bytes=0,files=0,html_pages=0,index={'status':'pending'})
            self.add(state,url,'homepage',url)
            if source and Path(source).exists(): self.cache.add(url,anchor,Path(source),source='scan homepage')
        state.setdefault('downloaded_bytes',0)
        if not self.args.index_limit:
            state['index']['status']='disabled'
        elif state['index']['status']=='disabled':
            state['index']['status']='pending'
        limits={name:getattr(self.args,name) for name in ('max_files','max_pages','max_requests','max_bytes','max_file_bytes','depth','index_limit','start','end')}
        if state.get('limits') != limits:
            for item in state['items'].values():
                if item['status'] in ('limited','out_of_period'):item['status']='pending'
            if state['index']['status']=='limited':state['index']['status']='pending'
        state['limits']=limits
        if not any(i['role']=='homepage' and i['status']=='saved' for i in state['items'].values()):
            url,anchor,source=seed_for(row)
            if source and Path(source).exists() and in_date_range(anchor, start, end):
                state.update(anchor=anchor,homepage=normalize(url,url))
                self.add(state,url,'homepage',url)
                self.cache.add(url,anchor,Path(source),source='scan homepage')
        # A previous failure never becomes a completed/negative site verdict.
        for item in state['items'].values():
            if item['status'] == 'saved' and not self.working_path(Path(item['record']['path'])).is_file():
                state['files'] -= 1
                state['bytes'] -= item['record'].get('bytes', 0)
                item.update(status='pending', expanded=False)
            if item['status']=='deferred':item['status']='pending'
        examined=set()
        priorities={'homepage':0,'asset':1,'frame':2,'script-asset':3,'page':4,'indexed-asset':5}
        try:
            while not STOP.is_set():
                candidates=[i for u,i in state['items'].items() if (i['status']=='pending' or (i['status']=='saved' and (not i.get('expanded') or not i.get('record',{}).get('source_path')))) and u not in examined]
                candidates.sort(key=lambda i:(priorities[i['role']],i['url']!=state['homepage'],i['depth']))
                if (STATE/'STOP').exists():STOP.set();break
                if not candidates:
                    if not offline and state['index']['status'] in ('pending','deferred') and self.args.index_limit:
                        if state['files']>=self.args.max_files or state['requests']>=self.args.max_requests or state['bytes']>=self.args.max_bytes or state['downloaded_bytes']>=self.args.max_bytes:
                            state['index']['status']='limited';break
                        try:
                            with self.cdx_lookup(domain):
                                self.index(state)
                        except DeferredFetch as error:state['index']=dict(status='deferred',error=str(error));break
                        except ValueError as error:state['index']=dict(status='limited',error=str(error));break
                        save(state_path,state);continue
                    break
                item=candidates[0];examined.add(item['url'])
                if item['status']=='saved':
                    if not item['record'].get('source_path'):
                        original=self.cache.get(item['url'],item['record']['capture'],max_days=0)
                        if original and key_bytes(Path(original['path']).read_bytes())==item['record']['sha256']:
                            item['record']['source_path']=original['source_path']
                    try:
                        self.discover(state,item,item['record'],self.working_path(Path(item['record']['path'])).read_bytes())
                        item['expanded']=True
                        item.pop('expansion_error',None)
                    except (OSError,ValueError,TypeError) as error:
                        item['expansion_error']=str(error)
                    save(state_path,state);continue
                if state['files']>=self.args.max_files or state['bytes']>=self.args.max_bytes:
                    item.update(status='limited',reason='site file/byte limit');continue
                if item['role'] in ('page','frame') and state['html_pages']>=self.args.max_pages:
                    item.update(status='limited',reason='HTML page limit');continue
                if item['role']=='frame' and item['depth']>3:
                    item.update(status='limited',reason='frame nesting limit');continue
                requested = capture_url(item.get('capture') or state['anchor'], item['url'])
                unavailable_status = 'missing'
                try:
                    if offline:
                        record=self.cache.get(item['url'],state['anchor'],start=start,end=end)
                        if not record:continue
                    else:
                        item['attempts']+=1
                        record=self.fetch_in_range(item, state, start, end)
                    if not in_date_range(record['capture'], start, end):
                        item.update(status='out_of_period',record=record);continue
                    data=Path(record['path']).read_bytes()
                    if len(data)>self.args.max_file_bytes or state['bytes']+len(data)>self.args.max_bytes:
                        item.update(status='limited',reason='file/site byte limit',record=record);continue
                    final_path=mirror_path(record)
                    destination=self.working_path(final_path)
                    destination.parent.mkdir(parents=True,exist_ok=True)
                    if destination.exists():
                        if key_bytes(destination.read_bytes())!=key_bytes(data):
                            raise ValueError('Existing mirror path has different bytes; retained source separately: '+str(record['path']))
                    else:
                        with LOCK:
                            # Atomic publication; never rewrite an archived capture.
                            if not destination.exists():
                                temp=destination.with_name(destination.name+'.'+str(threading.get_ident())+'.new')
                                temp.write_bytes(data);temp.replace(destination)
                            elif key_bytes(destination.read_bytes())!=key_bytes(data):raise ValueError('Mirror path conflict')
                    record.setdefault('source_path',record['path'])
                    record.update(path=str(final_path.resolve()),sha256=key_bytes(data),bytes=len(data))
                    item.update(status='saved',record=record)
                    state['files']+=1;state['bytes']+=len(data)
                    if item['role']=='homepage':state['anchor']=record['capture']
                    try:
                        self.discover(state,item,record,data)
                        item['expanded']=True
                    except (OSError,ValueError,TypeError) as error:
                        item['expanded']=False;item['expansion_error']=str(error)
                except CaptureMissing as error:
                    unavailable_status = error.status
                    item.update(status='unavailable',reason=str(error))
                    parsed=urlsplit(item['url'])
                    if item['role']=='homepage' and not parsed.hostname.startswith('www.'):
                        alternate=urlunsplit((parsed.scheme,'www.'+parsed.netloc,parsed.path,parsed.query,''))
                        self.add(state,alternate,'homepage',item['url'])
                except DeferredFetch as error:item.update(status='deferred',reason=str(error))
                except (ValueError,OSError) as error:item.update(status='limited',reason=str(error))
                finally:
                    outcomes = {'saved': None, 'deferred': 'retry', 'unavailable': unavailable_status, 'limited': 'retry'}
                    if item['status'] in outcomes:
                        self.record_download(requested, outcomes[item['status']], offline)
                    save(state_path,state)
            self.finish_crawl(state)
            save(state_path,state)
            report(f"DOMAIN: {domain} {state['status']} {state['counts']}")
            return state
        except Exception:
            save(state_path,state)
            raise


    def finish_crawl(self, state):
        counts={s:sum(i['status']==s for i in state['items'].values()) for s in ('saved','pending','deferred','unavailable','limited','out_of_period')}
        state['counts']=counts
        state['status']=('pending' if any(i['status']=='saved' and not i.get('expanded') for i in state['items'].values()) or counts['pending'] or counts['deferred'] or state['index']['status'] in ('pending','deferred') else
                         'partial' if counts['unavailable'] or counts['limited'] or counts['out_of_period'] or state.get('reference_limit') or state['index']['status']=='limited' else 'complete')
        state['updated_utc']=dt.datetime.now(dt.timezone.utc).isoformat()

    def capture_destination(self, original, stamp):
        destination = mirror_path(dict(url=original, capture=stamp))
        # Ruby dumps used foo/index.html for extensionless URLs. Leave room
        # for a capture of foo/bar at the same timestamp.
        parts = urlsplit(original)
        if self.working_path(destination).is_dir() or (not self.working_path(destination).exists() and not parts.query
                                    and not Path(parts.path).suffix and destination.name != 'index.html'):
            destination = destination / 'index.html'
        if not destination.resolve().is_relative_to(MIRROR):
            raise ValueError('Mirror path escapes root')
        return destination

    def download_capture(self, original, stamp, state, offline, result=None):
        record = dict(url=original, capture=stamp)
        published_path = self.capture_destination(original, stamp)
        destination = self.working_path(published_path)
        store = getattr(self.cache, 'external', None)
        if destination.is_file():
            check_local_petabox(destination)
            if store:
                store.discover(state['domain'], original, stamp, destination, source_path=published_path)
            return destination
        if result is not None:
            check_local_petabox(Path(result['path']))
        elif offline:
            result = self.cache.get(original, stamp, max_days=0)
            if result is None:
                raise DeferredFetch('Capture missing from offline cache')
        else:
            result = self.fetch(dict(record, exact=True), state)
        if result['capture'] != stamp and same_resource(original, result['url']):
            # Wayback's nearest-date replay can also switch between bare and www hosts.
            raise CaptureMissing(f"Exact capture {stamp} unavailable: Wayback replayed {result['capture']} for {result['url']}")
        if result['url'] != original:
            raise DeferredFetch(f"Replay resolved to {result['capture']} {result['url']}")
        source = Path(result['path'])
        size = source.stat().st_size
        if size > self.args.max_file_bytes or state['bytes'] + size > self.args.max_bytes:
            raise ValueError('mirror byte limit')
        destination.parent.mkdir(parents=True, exist_ok=True)
        # The worker response is already complete. Publish it atomically, including
        # when a subdomain was also requested as a separate input domain.
        try:
            os.link(source, destination)
        except FileExistsError:
            pass
        except OSError as error:
            if error.errno != errno.EXDEV:
                raise
            with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as temp:
                stage = Path(temp.name)
            try:
                shutil.copyfile(source, stage)
                try:
                    os.link(stage, destination)
                except FileExistsError:
                    pass
            finally:
                stage.unlink(missing_ok=True)
        if store:
            mime = ''
            if result.get('metadata'):
                headers = json.loads(Path(result['metadata']).read_text()).get('headers', {})
                mime = requests.structures.CaseInsensitiveDict(headers).get('Content-Type', '')
            store.discover(state['domain'], original, stamp, destination, mime, source_path=published_path)
        return destination

    def retry_index(self, row, index_url, state, repair):
        """Keep the failed seed until every discovered capture has a file or a recorded outcome."""
        url = index_url
        completed = {}
        while not STOP.is_set():
            if url in completed:
                raise DeferredFetch('Repeated CDX resume key')
            params = dict(parse_qsl(urlsplit(url).query))
            try:
                with self.cdx_lookup(row['domain']):
                    status, _, body, _, _ = self.request(url, state)
                    if status != 200:
                        raise DeferredFetch(f'CDX returned HTTP {status}')
                    captures, cursor = parse_cdx_page(body, params['fl'].split(','))
            except (OSError, ValueError):
                if not STOP.is_set():
                    self.record_download(url, 'retry')
                    for previous, outcome in completed.items():
                        self.record_download(previous, outcome)
                raise
            for stamp, raw in captures:
                original = normalize(raw, raw)
                if (original and family(urlsplit(original).hostname, row['domain'])
                        and in_date_range(stamp, row['start'], row['end'])):
                    repair(capture_url(stamp, original), stamp, original, listed=True)
            completed[url] = 'empty' if not captures and not cursor and 'resumeKey' not in params else None
            if not cursor:
                if not STOP.is_set():
                    for previous, outcome in completed.items():
                        self.record_download(previous, outcome)
                    if (self.args.mode == 'cdx' and params.get('url') == row['domain']
                            and params.get('matchType') == 'domain' and 'collapse' not in params
                            and params.get('from') == row['start'] and params.get('to') == row['end']):
                        state['index_complete'] = True
                        state.pop('reason', None)
                return
            params['resumeKey'] = unquote_plus(cursor)
            url = url.split('?', 1)[0] + '?' + urlencode(params)

    def retry_captures(self, row, urls, indexes=()):
        domain = row['domain']
        checkpoint = STATE/'domains'/(domain + '.json')
        saved = json.loads(checkpoint.read_text()) if checkpoint.exists() else {}
        same_scope = bool(saved) and saved.get('date_scope') == row.get('date_scope')
        state = saved if same_scope else dict(date_scope=row.get('date_scope'))
        state.setdefault('domain', domain)
        state.setdefault('items', {})
        state.setdefault('files', 0)
        state.setdefault('bytes', 0)
        state['requests'] = state['downloaded_bytes'] = 0
        state['status'] = state.get('primary_status', state.get('status', 'complete'))
        ok = True
        external = self.cache.external
        if external:
            with external.lock:
                last_job = external.db.execute('SELECT COALESCE(MAX(id),0) FROM mirror_asset_queue').fetchone()[0]
        attempted = set()
        stage = domain_stage(row) if self.args.failed_only else None
        staged_root = stage if stage and stage.is_dir() else None

        def repair(requested, stamp, original, listed=False):
            nonlocal ok
            if STOP.is_set():
                raise InterruptedError('Stop requested during repair')
            if requested in attempted:
                return
            status = self.cache.failed_downloads.status(requested)
            if not listed and status != 'retry':
                return
            item_key = stamp + ' ' + original if self.args.mode == 'cdx' else original
            item = state['items'].get(item_key)
            if status in ('missing', 'petabox'):
                if self.args.mode == 'cdx':
                    item = state['items'].setdefault(item_key, dict(url=original, role='capture', capture=stamp))
                    item['status'] = 'unavailable'
                    item.setdefault('reason', 'Previously checked: no archived response')
                return
            local_result = None
            if listed or self.args.mode == 'cdx':
                destination = self.capture_destination(original, stamp)
                if self.working_path(destination).is_file():
                    try:
                        check_local_petabox(self.working_path(destination))
                    except PetaboxCapture as error:
                        self.record_download(requested, error.status)
                        if item:
                            item.update(status='unavailable', reason=str(error))
                        return
                    self.record_download(requested, None)
                    if self.args.mode == 'cdx':
                        state['items'].pop(item_key, None)
                    return
                if staged_root:
                    staged = staged_root / destination.relative_to(MIRROR)
                    if staged.is_file() and staged.resolve().is_relative_to(staged_root):
                        local_result = dict(url=original, capture=stamp, path=str(staged))
            if state['files'] >= self.args.max_files or state['requests'] >= self.args.max_requests or state['downloaded_bytes'] >= self.args.max_bytes:
                raise LimitReached('Repair reached the configured download limit')
            attempted.add(requested)
            try:
                with self.track_download(requested):
                    if listed or self.args.mode == 'cdx':
                        path = self.download_capture(original, stamp, state, False, result=local_result)
                    else:
                        record = self.fetch_in_range(dict(url=original, capture=stamp), state, row['start'], row['end'])
                        if not in_date_range(record['capture'], row['start'], row['end']):
                            raise DeferredFetch('Replay outside selected dates')
                        path = self.download_capture(record['url'], record['capture'], state, False, result=record)
                        if item:
                            body = path.read_bytes()
                            published = MIRROR/path.relative_to(self.stage) if self.stage and path.is_relative_to(self.stage) else path
                            record.update(source_path=record['path'], path=str(published),
                                          bytes=len(body), sha256=key_bytes(body))
                            item.update(record=record, status='saved')
                            self.discover(state, item, record, body)
                            item['expanded'] = True
                    state['files'] += 1
                    state['bytes'] += path.stat().st_size
                    if item and self.args.mode == 'cdx':
                        del state['items'][item_key]
            except (ValueError, OSError) as error:
                if not isinstance(error, CaptureMissing):
                    ok = False
                if listed and self.args.mode == 'cdx':
                    item = state['items'].setdefault(item_key, dict(url=original, role='capture', capture=stamp))
                if item:
                    item.update(status='unavailable' if isinstance(error, CaptureMissing) else 'deferred', reason=str(error))
        try:
            for index_url in indexes:
                if self.cache.failed_downloads.status(index_url) == 'retry':
                    try:
                        self.retry_index(row, index_url, state, repair)
                    except (OSError, ValueError) as error:
                        report(f'CDX repair: {error}')
                        ok = False
            for requested, stamp, original in urls:
                repair(requested, stamp, original)
        except (LimitReached, InterruptedError) as error:
            report(f'{domain}: {error}')
            ok = False
        if self.args.mode == 'cdx' and state.get('index_complete'):
            outcomes = {i['status'] for i in state['items'].values()}
            state['status'] = 'pending' if 'deferred' in outcomes else 'partial' if outcomes else 'complete'
        elif self.args.mode == 'crawl' and 'index' in state:
            self.finish_crawl(state)
        if self.cache.external:
            assets_ok = self.finish_external_assets(state, False, retry_after_id=last_job)
            ok = ok and assets_ok
        elif same_scope or (not saved and state.get('index_complete')):
            save(checkpoint, state)
        return ok

    def finish_external_assets(self, state, offline, retry_after_id=None):
        store = self.cache.external
        site = state['domain']
        def request(url, limit):
            for _ in range(6):
                wayback_target(url)
                try:
                    status, headers, _, path, _ = self.request(url, state, max_bytes=limit)
                except DeferredFetch as error:
                    if STOP.is_set() or not error.retry_in_pass:
                        raise
                    raise Transient(str(error)) from error
                except ValueError as error:
                    raise LimitReached(str(error)) from error
                headers = requests.structures.CaseInsensitiveDict(headers)
                if status in (301, 302, 303, 307, 308) and headers.get('Location'):
                    url = urljoin(url, headers['Location'])
                    if url.startswith('http://web.archive.org/'):
                        url = 'https:' + url[5:]
                    continue
                if status in (404, 410, 451):
                    raise Unavailable(f'HTTP {status}')
                error = archive_error(read_body(path, 16384)) if status == 200 else 'failed'
                if error == 'petabox':
                    raise PetaboxCapture()
                if error:
                    raise Transient(f'Unusable Wayback response (HTTP {status})')
                return url, headers, path
            raise Transient('Wayback redirect limit')

        lookup = CaptureLookup(request, min(self.args.max_file_bytes, 64 * 1024 * 1024))
        state['primary_status'] = state['status']
        files, size = state['files'], state['bytes']
        limited = False
        repaired = True
        for job in store.jobs(site, unfinished=retry_after_id is not None):
            if STOP.is_set():
                break
            if retry_after_id is not None and job[0] <= retry_after_id:
                with store.lock:
                    if store.archive.failure_statuses.get(capture_url(job[2], job[1])) != 'retry':
                        continue
            if files >= self.args.max_files or size >= self.args.max_bytes:
                limited = True
                break
            lookup.max_bytes = min(lookup.max_bytes, self.args.max_bytes - size)
            try:
                path = store.resolve(site, job, lookup, offline)
            except DeferredFetch:
                repaired = False
                break
            except LimitReached as error:
                state['reason'] = str(error)
                limited = True
                break
            if path:
                files += 1
                size += path.stat().st_size
            elif retry_after_id is not None and store.archive.failure_statuses.get(capture_url(job[2], job[1])) == 'retry':
                repaired = False
        counts = state['external_assets'] = store.outcome(site)
        if self.args.download_external_assets_only:
            state.update(files=files, bytes=size)
        if limited:
            if state['status'] == 'complete':
                state['status'] = 'partial'
        elif counts.get('pending') or counts.get('retry'):
            state['status'] = 'pending'
        elif counts.get('missing') and state['status'] == 'complete':
            state['status'] = 'partial'
        save(STATE/'domains'/(site+'.json'), state)
        return repaired and not limited and not STOP.is_set()


class CDXWorker(MirrorWorker):
    """Enumerate every indexed successful capture, including unlinked files."""

    def index_page(self, state, cursor, offline):
        params = {'url': state['domain'], 'matchType': 'domain', 'output': 'json',
                  'fl': 'timestamp,original', 'filter': 'statuscode:200',
                  **cdx_dates(self.args.start, self.args.end), 'limit': 1000,
                  'showResumeKey': 'true'}
        if cursor:
            params['resumeKey'] = unquote_plus(cursor)
        index_url = 'https://web.archive.org/cdx/search/cdx?' + urlencode(params)
        ledger = self.cache.failed_downloads
        if not cursor and ledger and ledger.status(index_url) == 'empty':
            return dict(rows=[], next=None, generation=state['generation'])
        path = STATE / 'indexes' / state['domain'] / (key(cursor) + '.json')
        if path.exists():
            page = json.loads(path.read_text())
            if page['generation'] == state['generation']:
                if not cursor and not page['rows'] and page['next'] is None:
                    self.record_download(index_url, 'empty')
                return page
        if offline:
            raise DeferredFetch('CDX page missing from offline cache')
        try:
            status, _, body, _, _ = self.request(index_url, state)
            if status != 200:
                raise DeferredFetch(f'CDX returned HTTP {status}')
            rows, next_cursor = parse_cdx_page(body)
        except (OSError, ValueError):
            self.record_download(index_url, 'retry')
            raise
        self.record_download(index_url, 'empty' if not cursor and not rows and next_cursor is None else None)
        page = dict(rows=rows, next=next_cursor, generation=state['generation'])
        save(path, page)
        return page

    def run_site(self, row, offline=False):
        domain = row['domain']
        path = STATE / 'domains' / (domain + '.json')
        previous = json.loads(path.read_text()) if path.exists() else {}
        generation = previous.get('generation', time.time_ns())
        if previous.get('date_scope') != row.get('date_scope') or (previous.get('status') == 'complete' and not offline):
            generation = time.time_ns()  # Include newly indexed captures on a later run.
        state = dict(domain=domain, date_scope=row.get('date_scope'), generation=generation, status='pending', items={},
                     requests=0, files=0, bytes=0, downloaded_bytes=0)
        save(path, state)
        cursor = ''
        visited = set()
        try:
            while not STOP.is_set():
                with self.cdx_lookup(domain):
                    if cursor in visited:
                        raise DeferredFetch('CDX returned a repeated resume key')
                    visited.add(cursor)
                    page = self.index_page(state, cursor, offline)
                for stamp, raw in page['rows']:
                    if STOP.is_set():
                        break
                    url = normalize(raw, raw)
                    if not url or not family(urlsplit(url).hostname, domain) or not in_date_range(stamp, self.args.start, self.args.end):
                        continue
                    if state['files'] >= self.args.max_files:
                        raise ValueError('mirror file limit')
                    try:
                        with self.track_download(f'https://web.archive.org/web/{stamp}id_/{url}', offline):
                            file = self.download_capture(url, stamp, state, offline)
                    except (FileNotFoundError, DeferredFetch, ValueError, OSError) as error:
                        status = 'deferred' if isinstance(error, DeferredFetch) else 'unavailable'
                        state['items'][stamp + ' ' + url] = dict(url=url, role='capture', status=status,
                                                                 reason=str(error), capture=stamp)
                        if state['requests'] >= self.args.max_requests or state['downloaded_bytes'] >= self.args.max_bytes:
                            raise ValueError('request or byte limit reached') from error
                    else:
                        state['files'] += 1
                        state['bytes'] += file.stat().st_size
                save(path, state)
                cursor = page['next']
                if not cursor:
                    if not STOP.is_set():
                        state['index_complete'] = True
                        if not state['items']:
                            state['status'] = 'complete'
                        elif all(i['status'] == 'unavailable' for i in state['items'].values()):
                            state['status'] = 'partial'
                    break
        except (DeferredFetch, ValueError, OSError) as error:
            state['reason'] = str(error)
            if isinstance(error, ValueError):
                state['status'] = 'partial'
        finally:
            save(path, state)
        return state


def local_capture_urls(row):
    """Recover original schemes, query strings and extensionless names from local checkpoints."""
    site = row['domain']
    urls = {}
    selection = BASE / key(str(MIRROR))[:12]
    runs = [*selection.glob('cdx-*'), *selection.glob('crawl-*')]
    for run in runs:
        for folder in (run, *run.glob('external-*')):
            for page in (folder/'indexes'/site).glob('*.json'):
                for stamp, raw in json.loads(page.read_text())['rows']:
                    if not in_date_range(stamp, row['start'], row['end']):
                        continue
                    original = normalize(raw, raw)
                    if original and family(urlsplit(original).hostname, site):
                        try:
                            rel = mirror_path(dict(url=original, capture=stamp)).relative_to(MIRROR)
                        except ValueError:
                            continue
                        urls[rel] = original
            checkpoint = folder/'domains'/(site+'.json')
            if run.name.startswith('crawl-') and checkpoint.is_file():
                for item in json.loads(checkpoint.read_text()).get('items', {}).values():
                    if item.get('status') == 'saved':
                        record = item['record']
                        path = Path(record['path'])
                        if path.is_relative_to(MIRROR):
                            urls[path.relative_to(MIRROR)] = record['url']
    return urls


def parse_cdx_page(body, fields=None):
    fields = fields or ['timestamp', 'original']
    try:
        data = json.loads(body)
    except ValueError as error:
        raise DeferredFetch('Invalid JSON from CDX') from error
    if data == []:
        return [], None
    if not isinstance(data, list) or data[:1] != [fields] or fields[:2] != ['timestamp', 'original']:
        raise DeferredFetch('Missing CDX field header')
    rows = data[1:]
    cursor = None
    if len(rows) >= 2 and rows[-2] == []:
        tail = rows[-1]
        if not isinstance(tail, list) or len(tail) != 1 or not isinstance(tail[0], str) or not tail[0]:
            raise DeferredFetch('Invalid CDX resume key')
        rows, cursor = rows[:-2], tail[0]
    for row in rows:
        if (not isinstance(row, list) or len(row) != len(fields) or not all(isinstance(x, str) for x in row)
                or not re.fullmatch(r'\d{14}', row[0]) or not row[1].startswith(('http://', 'https://'))):
            raise DeferredFetch('Invalid CDX capture row')
    return (rows if len(fields) == 2 else [row[:2] for row in rows]), cursor


def date_bound(value, end=False):
    """Expand a year, month or day to its inclusive UTC boundary."""
    if re.fullmatch(r'\d{4}-\d{2}(-\d{2})?', value):
        value = value.replace('-', '')
    if not value.isascii() or not value.isdigit() or len(value) not in (4, 6, 8, 14):
        raise ValueError('Use YYYY, YYYY-MM, YYYY-MM-DD, or YYYYMMDDhhmmss')
    if len(value) == 4:
        value += '12' if end else '01'
    if len(value) == 6:
        day = calendar.monthrange(int(value[:4]), int(value[4:]))[1] if end else 1
        value += f'{day:02}'
    if len(value) == 8:
        value += '235959' if end else '000000'
    dt.datetime.strptime(value, '%Y%m%d%H%M%S')
    return value


def read_skip_file(path):
    rules = json.loads(path.read_text(encoding='utf-8-sig'))
    if not isinstance(rules, dict):
        raise ValueError('Expected an object mapping domains to before/after dates')
    result = {}
    for name, rule in rules.items():
        domain = domain_rows([(1, name)])[0]['domain'].removeprefix('www.')
        if name.lower().rstrip('.').removeprefix('www.') != domain or domain in result:
            raise ValueError(f'Invalid or duplicate skip-file domain: {name}')
        if (not isinstance(rule, dict) or not rule.keys() & {'before', 'after'}
                or rule.keys() - {'before', 'after', 'beforeNotes', 'afterNotes'}):
            raise ValueError(f'{name}: expected before and/or after')
        for bound in ('before', 'after'):
            if bound + 'Notes' in rule and bound not in rule:
                raise ValueError(f'{name}: {bound}Notes requires {bound}')
        if not all(isinstance(value, str) for value in rule.values()):
            raise ValueError(f'{name}: dates and notes must be strings')
        start = date_bound(rule['before']) if 'before' in rule else None
        end = date_bound(rule['after'], end=True) if 'after' in rule else None
        if start and end and start > end:
            raise ValueError(f'{name}: empty capture window')
        result[domain] = start, end
    return result


def key_bytes(data): return hashlib.sha256(data).hexdigest()


def summary():
    counts={};files=bytes_=requests_=downloaded=0;rows=[];missing=[]
    for p in sorted((STATE/'domains').glob('*.json')):
        try:s=json.loads(p.read_text())
        except ValueError:continue
        status=s.get('status','pending');counts[status]=counts.get(status,0)+1
        files+=s['files'];bytes_+=s['bytes'];requests_+=s['requests'];downloaded+=s.get('downloaded_bytes',0)
        home=next((i.get('record',{}).get('path','') for i in s['items'].values() if i['role']=='homepage'),'')
        rows.append([s['domain'],status,str(s['files']),str(s['requests']),home])
        for item in s['items'].values():
            if item['status']!='saved':missing.append([s['domain'],item['status'],item['role'],item['url'],item.get('reason','')])
    save(STATE/'status.json',dict(updated_utc=dt.datetime.now(dt.timezone.utc).isoformat(),counts=counts,files=files,bytes=bytes_,downloaded_bytes=downloaded,requests=requests_))
    for name,header,records in [('progress.tsv',['domain','status','files','requests','homepage'],rows),('missing.tsv',['domain','status','role','url','reason'],missing)]:
        temp=STATE/(name+'.new')
        with temp.open('w') as out:
            writer=csv.writer(out,delimiter='\t');writer.writerow(header);writer.writerows(records)
        temp.replace(STATE/name)


def read_domains(path):
    """Read DNS A-record TSV, one domain/URL per line, or an existing JSON list.

    Existing classification fields in JSON are ignored; input order is retained.
    """
    text = path.read_text(encoding='utf-8-sig')
    if path.suffix.lower() == '.json':
        values = json.loads(text)
        if not isinstance(values, list): raise ValueError('Expected a JSON list')
        entries = []
        for number, row in enumerate(values, 1):
            if isinstance(row, dict):
                row = row.get('domain') or row.get('host') or row.get('url')
            entries.append((number, row))
    else:
        entries = []
        for number, line in enumerate(text.splitlines(), 1):
            if not line.strip() or line.lstrip().startswith('#'): continue
            value = line.split()[0]
            if value.lower() in ('domain', 'domain_name', 'hostname'): continue
            entries.append((number, value))
    return domain_rows(entries)


def domain_rows(entries):
    rows, seen = [], set()
    for number, value in entries:
        if not isinstance(value, str): raise ValueError('Missing domain on input row ' + str(number))
        raw = value.strip().rstrip('.')
        parts = replay_parts(raw)
        original = parts[1] if parts else raw if '://' in raw else 'http://' + raw + '/'
        url = normalize(original, original)
        host = urlsplit(url).hostname if url else None
        if not host or '.' not in host or len(host) > 253 or any(
                not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label) for label in host.split('.')):
            raise ValueError('Invalid domain on input row ' + str(number) + ': ' + value)
        if host in seen: continue
        seen.add(host)
        rows.append(dict(domain=host, source_line=number, url=url, capture=parts[0] if parts else None))
    if not rows: raise ValueError('No domains found')
    return rows


CLI_EPILOG = """\
Captures are saved as HOST/TIMESTAMP/PATH under the output directory.

Some necessary output metadata goes to a meta.json file.

The script also records clearly any failed download attempts so that those can be retried
later. A replay of the US Petabox landing page is recorded as "petabox" and skipped like "missing".

meta.json status glossary

  Eligible for --failed-only
    failed                      Download failed for an unspecified reason.
    failed-cdx-unavailable      The Wayback capture index lookup failed.
    failed-http-201             Replay returned an unexpected HTTP 201 Created.
    failed-http-400             Replay returned HTTP 400 Bad Request.
    failed-http-403             Replay returned HTTP 403 Forbidden.
    failed-http-500             Replay returned HTTP 500 Internal Server Error.
    failed-invalid-gzip         Replay advertised gzip but sent invalid gzip data.

  Unavailable captures skipped on later runs
    missing                     No usable capture was found.
    missing-other-timestamp     Wayback selected a different capture date.
    missing-http-404            Replay returned HTTP 404 Not Found.
    missing-http-410            Replay returned HTTP 410 Gone.
    missing-html-for-image      An image request returned an HTML page.
    missing-html-for-script     A script request returned an HTML page.
    missing-lookup-only         Lookup found no usable capture. Only the lookup
                                outcome was retained.
    petabox                     Replay returned the US Petabox landing page.

  Recovered captures excluded from retries
    recovered                   The capture was recovered.
    recovered-im_               Wayback image replay (im_) supplied bytes
                                matching the capture's CDX digest.
    recovered-short-read        Fewer bytes arrived than advertised, but the
                                received bytes matched the CDX digest.
    recovered-identical-capture Another capture supplied identical bytes,
                                verified against the requested CDX digest.

  An "empty": true flag marks a successful CDX query with zero captures.
  Future runs skip that query. statusNotes gives per-URL details when available.

Examples
  %(prog)s domains.txt --from 2010 --to 2012
  %(prog)s --mode crawl --timestamp 20200101000000 example.org
  Use --no-skip-existing when resuming a partial domain."""


def main():
    global BASE, STATE, MIRROR, DUMP, RATE_DIR, SEED_CACHE, ANCHOR
    parser = argparse.ArgumentParser(description=__doc__, epilog=CLI_EPILOG,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    control_only = any(flag in sys.argv[1:] for flag in ('--tor-kill', '--setup-tor-control'))
    parser.add_argument('domains', nargs='*' if control_only else '+', metavar='DOMAIN_OR_FILE',
                        help='Domains, homepage URLs, or domain list files (text, TSV, or JSON)')
    parser.add_argument('--sort', action='store_true',
                        help='Queue domains alphabetically (default: input order)')
    parser.add_argument('--mode', choices=['cdx','crawl'], default='cdx',
                        help='List captures in CDX (default), or crawl links from a homepage')
    parser.add_argument('--skip-file', type=Path, metavar='JSON',
                        help='Per-domain date exceptions with optional beforeNotes and afterNotes. '
                             'For example, {"example.org":{"after":"2012"}} skips 2013 onward')
    parser.add_argument('--skip-existing', action=argparse.BooleanOptionalAction, default=True,
                        help='Skip existing domain directories (default). Use --no-skip-existing to fill gaps.')
    parser.add_argument('--retry-failed', action=argparse.BooleanOptionalAction, default=True,
                        help='Finish with one retry pass for failed replay URLs, including skipped domains (default: on)')
    parser.add_argument('--failed-only', action='store_true',
                        help='Retry failed URLs from meta.json. Fetch new captures from recovered CDX pages and skip known missing URLs.')
    parser.add_argument('--output', '-o', type=Path, help='Mirror root (default: current directory)')
    assets = parser.add_mutually_exclusive_group()
    assets.add_argument('--download-external-assets', type=Path, metavar='OUTPATH',
                        help='Queue embedded third-party assets per site and save nearest captures in OUTPATH')
    assets.add_argument('--download-external-assets-only', type=Path, metavar='OUTPATH',
                        help='Read existing local site captures and download only their third-party assets to OUTPATH')
    parser.add_argument('--work-dir', type=Path, help='Checkpoint directory (default: OUTPUT/.wayback-machine-download)')
    parser.add_argument('--cache-dump', type=Path, help='Optional additional mirror to reuse')
    parser.add_argument('--rate-dir', type=Path, help='Shared rate gate; default: WORK_DIR/tor-top, compatible with the discovery scanner')
    proxy = parser.add_mutually_exclusive_group()
    proxy.add_argument('--tor', type=int, metavar='N', help='Start N private Tor instances (one worker per instance by default)')
    proxy.add_argument('--tor-kill', action='store_true', help='Stop downloader-managed Tor instances for this output directory and exit')
    proxy.add_argument('--ports', '--tor-ports', type=parse_ports, help='Existing Tor SOCKS ports, e.g. 9051-9070; configures missing control sockets for running tor-army instances')
    parser.add_argument('--tor-config-dir', type=Path, default=Path.home() / 'etc/tor', help='tor-army configs and local control sockets (default: %(default)s)')
    parser.add_argument('--setup-tor-control', action='store_true', help='Set up cookie-authenticated control sockets and reload selected tor-army instances, then exit without downloads')
    parser.add_argument('--workers', type=int, help='Override worker count (1–20; default: 1 direct or one per Tor instance)')
    parser.add_argument('--interval', type=float, default=1, help='Shared global request spacing, minimum 1 second; 15s per port')
    parser.add_argument('--http-cooldown-seconds', type=float, default=HTTP_COOLDOWN_SECONDS, metavar='SECONDS',
                        help='Default cooldown after HTTP 429 or 503 (default: %(default)s seconds)')
    parser.add_argument('--timestamp', help='Preferred homepage timestamp, YYYYMMDDhhmmss')
    parser.add_argument('--offline', action='store_true', help='Import cached files and discover dependencies without requests')
    parser.add_argument('--plan', action='store_true', help='Validate input/options and print the plan without downloads or state changes')
    parser.add_argument('--domain', action='append', help='Restrict to these input domains (repeatable)')
    parser.add_argument('--passes', type=int, default=3, help='Maximum attempts per domain (1–3; default: 3). Each domain retries independently after 60/120s')
    parser.add_argument('--max-files', type=int, default=None)
    parser.add_argument('--max-pages', type=int, default=12)
    parser.add_argument('--max-requests', type=int)
    parser.add_argument('--max-bytes', type=int)
    parser.add_argument('--max-file-bytes', type=int)
    parser.add_argument('--depth', type=int, default=1)
    parser.add_argument('--index-limit', type=int, default=0, help='Bounded CDX URL listing per site; 0 disables')
    parser.add_argument('--from', '--first-year', '-f', dest='start', metavar='DATE',
                        help='Inclusive first capture date (year, month, day, or 14-digit UTC timestamp); default: no lower bound')
    parser.add_argument('--to', '--last-year', '-t', dest='end', metavar='DATE', help='Inclusive last capture date; default: no upper bound')
    args = parser.parse_intermixed_args()
    if args.failed_only and (args.offline or not args.retry_failed):
        parser.error('--failed-only requires online retries')
    if not math.isfinite(args.http_cooldown_seconds) or args.http_cooldown_seconds < 0:
        parser.error('--http-cooldown-seconds must be finite and non-negative')
    for name, bound in [('max_files',200), ('max_requests',300), ('max_bytes',50*1024*1024),
                        ('max_file_bytes',8*1024*1024)]:
        if getattr(args, name) is None:
            setattr(args, name, bound if args.mode == 'crawl' else sys.maxsize)
    args.tor_config_dir = args.tor_config_dir.resolve()
    if args.setup_tor_control and not args.ports:
        parser.error('--setup-tor-control requires --ports')
    if args.tor_kill:
        return kill_managed_tor((args.output or Path.cwd()).resolve())
    if args.tor is not None and args.tor < 1:
        parser.error('--tor requires a positive number of instances')
    if args.workers is not None and not 1 <= args.workers <= 20:
        parser.error('--workers must be between 1 and 20')
    if args.ports and args.workers not in (None, 1):
        parser.error('Use --ports or --workers; Tor mode uses one worker per port')
    args.workers = args.workers or args.tor or 1
    if not 1 <= args.interval <= 60 or any(getattr(args,k) <= 0 for k in ('max_files','max_pages','max_requests','max_bytes','max_file_bytes')) or not 0 <= args.index_limit <= 1000 or not 0 <= args.depth <= 3 or not 1 <= args.passes <= 3:
        parser.error('Invalid limits')
    try:
        if args.start is not None:
            args.start = date_bound(args.start)
        if args.end is not None:
            args.end = date_bound(args.end, end=True)
        if args.start and args.end and args.end < args.start:
            raise ValueError('--to precedes --from')
        timestamp_key = args.timestamp or 'latest'
        if args.timestamp is None:
            now = dt.datetime.now(dt.timezone.utc).strftime('%Y%m%d%H%M%S')
            args.timestamp = max(now, args.start or now)
            if args.end:
                args.timestamp = min(args.timestamp, args.end)
        elif len(args.timestamp) != 14 or not in_date_range(date_bound(args.timestamp), args.start, args.end):
            raise ValueError('--timestamp must be a 14-digit timestamp inside the date range')
        rows = []
        for value in args.domains:
            path = Path(value)
            if '://' not in value and (path.is_file() or path.suffix.lower() in ('.json', '.txt', '.tsv') or '/' in value):
                rows.extend(read_domains(path))
            else:
                rows.extend(domain_rows([(1, value)]))
        unique = {}
        for row in rows:
            unique.setdefault(row['domain'], row)
        rows = list(unique.values())
        if args.sort:
            rows.sort(key=lambda row: row['domain'])
        rules = read_skip_file(args.skip_file) if args.skip_file else {}
        for row in rows:
            host = row['domain']
            # The most specific configured domain applies to its subdomains.
            rule = None
            while '.' in host and rule is None:
                rule = rules.get(host)
                host = host.partition('.')[2]
            start, end = args.start, args.end
            if rule:
                lower, upper = rule
                if lower and (not start or lower > start):
                    start = lower
                if upper and (not end or upper < end):
                    end = upper
                if (start, end) != (args.start, args.end):
                    row['date_scope'] = f'/{start or "any"}-{end or "any"}'
            row.update(start=start, end=end)
    except (OSError, ValueError) as error: parser.error(str(error))
    if args.domain:
        selected = {d.lower().rstrip('.') for d in args.domain}
        unknown = selected - {r['domain'] for r in rows}
        if unknown: parser.error('Not in input: ' + ', '.join(sorted(unknown)))
        rows = [r for r in rows if r['domain'] in selected]
    args.ports = args.ports or []
    MIRROR = (args.output or Path.cwd()).resolve()
    BASE = (args.work_dir or MIRROR/'.wayback-machine-download').resolve()
    selection_root = BASE / key(str(MIRROR))[:12]
    date_span = f"{args.start or 'any'}-{args.end or 'any'}" if args.start or args.end else 'all'
    suffix = '-' + timestamp_key if args.mode == 'crawl' else ''
    STATE = selection_root / f'{args.mode}-{date_span}{suffix}'
    # Resume checkpoints written before open bounds were named explicitly.
    if not STATE.exists() and (args.start is None or args.end is None):
        previous = selection_root / f"{args.mode}-{args.start or '00010101000000'}-{args.end or '99991231235959'}{suffix}"
        if previous.is_dir():
            STATE = previous
    external_root = args.download_external_assets_only or args.download_external_assets
    if external_root is not None:
        external_root = external_root.expanduser().resolve()
        if external_root == MIRROR:
            parser.error('External assets need a separate directory from the primary mirror')
        prefix = 'external-only-' if args.download_external_assets_only else 'external-'
        STATE = STATE / (prefix + key(str(external_root))[:12])
    if args.download_external_assets_only:
        args.skip_existing = False  # Existing captures are the input; never publish or discard primary staging.
    DUMP = (args.cache_dump or MIRROR).resolve()
    RATE_DIR = args.rate_dir.resolve() if args.rate_dir else BASE/'tor-top'
    ANCHOR = args.timestamp
    windows = {r['domain']: cdx_dates(r['start'], r['end']) for r in rows if r.get('date_scope')}
    skipped_dates = [r['domain'] for r in rows if r['start'] and r['end'] and r['start'] > r['end']]
    if skipped_dates:
        excluded = set(skipped_dates)
        rows = [r for r in rows if r['domain'] not in excluded]
    selected_rows = rows
    skipped = []
    if args.failed_only:
        rows = []  # All selected domains remain eligible for repair, regardless of existing directories.
    elif args.skip_existing:
        hosts = {p.name.lower().removeprefix('www.').removesuffix(':80').removesuffix(':443')
                 for p in MIRROR.iterdir() if p.is_dir()} if MIRROR.is_dir() else set()
        for row in rows:
            domain = row['domain']
            if domain.removeprefix('www.') not in hosts or domain_stage(row).is_dir():
                continue
            checkpoint = STATE/'domains'/(domain+'.json')
            if args.download_external_assets and checkpoint.is_file():
                saved = json.loads(checkpoint.read_text())
                counts = saved.get('external_assets', {})
                if counts.get('pending') or counts.get('retry'):
                    row['external_only'] = (saved.get('date_scope') == row.get('date_scope')
                                            and saved.get('primary_status') in ('partial', 'complete'))
                    continue
            skipped.append(domain)
        excluded = set(skipped)
        rows = [r for r in rows if r['domain'] not in excluded]
    settings = {k: str(v) if isinstance(v,Path) else v for k,v in vars(args).items()}
    plan = dict(options=settings, domains=len(rows), skipped_existing=len(skipped),
                first_domains=[r['domain'] for r in rows[:10]], output=str(MIRROR), state=str(STATE))
    if args.failed_only:
        plan.update(eligible_domains=len(selected_rows))
        del plan['domains'], plan['first_domains']
    if args.skip_file:
        plan.update(domain_date_windows=windows, skipped_by_date=skipped_dates)
    if args.plan:
        print(json.dumps(plan, indent=2)); return
    if args.setup_tor_control:
        try: setup_tor_control(args.tor_config_dir, args.ports)
        except (OSError, ValueError) as error: parser.error(str(error))
        print('Control setup complete. Rerun without --setup-tor-control to resume downloads.', flush=True)
        return
    if skipped_dates:
        print(f'Skipped {len(skipped_dates)} domains outside their capture windows.')
    retry_at_end = args.retry_failed and not args.offline
    if not rows and not (retry_at_end and selected_rows and (
            (MIRROR/'meta.json').exists() or external_root and (external_root/'meta.json').exists())):
        if args.failed_only:
            print('No failed URLs in the selected domains and date ranges.')
            return
        if not skipped: return
        print(f'All {len(skipped)} input domains already exist in the mirror.')
        return
    if not args.offline and (args.tor or args.ports) and not shutil.which('curl'):
        parser.error('Tor mode requires curl')
    if not args.offline and args.tor and not shutil.which('tor'):
        parser.error('--tor requires the tor executable in PATH')
    STATE.mkdir(parents=True, exist_ok=True); (STATE/'domains').mkdir(exist_ok=True)
    if not args.work_dir:
        ignore = BASE / '.gitignore'
        try:
            with ignore.open('x') as out:
                out.write('*\n')
        except FileExistsError:
            pass
    MIRROR.mkdir(parents=True, exist_ok=True); RATE_DIR.mkdir(parents=True, exist_ok=True)
    lock = (STATE/'controller.lock').open('a')
    try: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
    except BlockingIOError: parser.error('A downloader already holds this work directory')
    if (STATE/'STOP').exists(): parser.error('Remove ' + str(STATE/'STOP') + ' before resuming')
    if args.ports and not args.offline:
        try:
            setup_tor_control(args.tor_config_dir, args.ports, managed_only=True)
        except (OSError, ValueError) as error:
            report(f'TOR CONTROL: {error}. Continuing with SOCKS.')
    if args.tor and not args.offline:
        signal.signal(signal.SIGTERM, lambda *_: STOP.set())
    try:
        with ExitStack() as stack:
            store = None
            if external_root:
                store = stack.enter_context(open_asset_store(external_root, str(STATE)))
            cache = Cache()
            if not args.download_external_assets_only:
                cache.failed_downloads = FailedDownloads(MIRROR, STATE)
            cache.external = store
            if store:
                store.site_scopes = {r['domain']: r['date_scope'] for r in selected_rows if r.get('date_scope')}
            repair_jobs = final_retry_jobs(selected_rows, cache, args.failed_only) if not rows else None
            if not rows and not repair_jobs:
                print('No failed URLs in the selected domains and date ranges.')
                return
            args.tor_sockets = stack.enter_context(managed_tor(args.tor)) if args.tor and not args.offline else []
            return run_downloads(args, rows, plan, cache, selected_rows, repair_jobs)
    except (KeyboardInterrupt, InterruptedError):
        return 130
    except RuntimeError as error:
        print(error, file=sys.stderr)
        return 1


def schedule_domains(executor, rows, run, workers, attempts, check_stop, retry_delay=60):
    first_attempts = deque(range(len(rows)))
    retries = []  # (ready time, input position, attempt number)
    active = {}
    last_report = time.monotonic()
    summary()
    while (first_attempts or retries or active) and not check_stop():
        while len(active) < workers and not check_stop():
            if retries and retries[0][0] <= time.monotonic():
                _, index, attempt = heapq.heappop(retries)
                report(f"Retry {attempt}/{attempts}: {rows[index]['domain']}")
            elif first_attempts:
                index = first_attempts.popleft()
                attempt = 1
            else:
                break
            active[executor.submit(run, rows[index])] = index, attempt

        timeout = 1.0  # Poll the stop file even while all workers are busy.
        if retries and len(active) < workers:
            timeout = min(timeout, max(0, retries[0][0] - time.monotonic()))
        if active:
            done, _ = concurrent.futures.wait(active, timeout=timeout,
                                              return_when=concurrent.futures.FIRST_COMPLETED)
            for future in done:
                index, attempt = active.pop(future)
                status = future.result()
                if status in (None, 'pending') and attempt < attempts:
                    due = time.monotonic() + attempt * retry_delay
                    heapq.heappush(retries, (due, index, attempt + 1))
        elif retries:
            STOP.wait(timeout)
        if time.monotonic() - last_report >= 15:
            summary()
            last_report = time.monotonic()


def final_retry_jobs(selected_rows, cache, include_indexes=False):
    retry_urls = defaultdict(list)
    indexes = defaultdict(list)
    if cache.failed_downloads:
        cache.failed_downloads.update()
        by_specificity = sorted(selected_rows, key=lambda row: -len(row['domain']))
        for url, status in cache.failed_downloads.statuses.items():
            if status != 'retry':
                continue
            capture = asset_replay_parts(url)
            if capture:
                stamp, original = capture
                host = urlsplit(original).hostname or ''
                row = next((r for r in by_specificity if family(host, r['domain'])), None)
                if row and in_date_range(stamp, row['start'], row['end']):
                    retry_urls[row['domain']].append((url, stamp, original))
            elif include_indexes and url.startswith('https://web.archive.org/cdx/search/cdx?'):
                params = dict(parse_qsl(urlsplit(url).query))
                target = params.get('url', '')
                host = urlsplit(target if '://' in target else '//' + target).hostname or ''
                row = next((r for r in by_specificity if family(host, r['domain'])), None)
                if (row and (not row['start'] or params.get('from', '') >= row['start'])
                        and (not row['end'] or params.get('to', '9') <= row['end'])):
                    indexes[row['domain']].append(url)
    external_sites = cache.external.sites_with_failed_assets(selected_rows) if cache.external else set()
    return [(row, retry_urls[row['domain']], indexes[row['domain']]) for row in selected_rows
            if row['domain'] in retry_urls or row['domain'] in indexes or row['domain'] in external_sites]


def run_downloads(args, rows, plan, cache, selected_rows, repair_jobs=None):
    global SEED_CACHE
    external_store = cache.external
    if args.mode == 'crawl' and not args.download_external_assets_only: cache.load_scan()
    SEED_CACHE = cache
    save(STATE/'run.json', dict(plan, started_utc=dt.datetime.now(dt.timezone.utc).isoformat()))
    if args.failed_only:
        print('Failed URL repair:', len(repair_jobs), 'domain(s)', flush=True)
    else:
        order = 'alphabetical order' if args.sort else 'input order'
        print('Domains:', len(rows), f'({order}; download only)', flush=True)
    count = 1 if args.offline else len(args.ports) if args.ports else args.workers
    local = threading.local(); counter = iter(range(count)); assignment = threading.Lock()
    def publish(row):
        stage = domain_stage(row)
        if stage.is_dir():
            with LOCK:
                for host in stage.iterdir():
                    publish_stage(host, MIRROR/host.name)
                stage.rmdir()

    def worker_for(row):
        if not hasattr(local,'worker'):
            with assignment: number = next(counter)
            worker_class = CDXWorker if args.mode == 'cdx' else MirrorWorker
            local.worker = worker_class(copy(args),cache,number)
        local.worker.args.start, local.worker.args.end = row['start'], row['end']
        return local.worker

    def run(row):
        cache.network.wait()
        if STOP.is_set(): return
        worker_for(row)
        try:
            if args.skip_existing:
                local.worker.stage = domain_stage(row)
            if args.download_external_assets_only and not row.get('external_only'):
                count = external_store.scan_local_captures(row)
                state = dict(domain=row['domain'], status='complete' if count else 'partial', requests=0,
                             downloaded_bytes=0, files=0, bytes=0, items={}, local_captures=count)
                if not count:
                    state['reason'] = 'No local primary captures in the selected dates'
                    report(f"{row['domain']}: {state['reason']}")
            elif row.get('external_only'):
                state = json.loads((STATE/'domains'/(row['domain']+'.json')).read_text())
                if not external_store.outcome(row['domain']):
                    # The primary checkpoint survived deletion of the temporary external queue.
                    external_store.scan_local_captures(row)
                state['status'] = state['primary_status']
                state['requests'] = state['downloaded_bytes'] = 0
                if args.download_external_assets_only:
                    state['files'] = state['bytes'] = 0
            else:
                state = local.worker.run_site(row,args.offline)
            if external_store and not STOP.is_set():
                local.worker.finish_external_assets(state, args.offline)
                row['external_only'] = state['status'] == 'pending' and state['primary_status'] in ('partial', 'complete')
            if args.skip_existing and state['status'] in ('complete', 'partial'):
                publish(row)
            (STATE/'errors'/(row['domain']+'.json')).unlink(missing_ok=True)
            return state['status']
        except Exception as error:
            save(STATE/'errors'/(row['domain']+'.json'),dict(error=str(error),type=type(error).__name__))
            print('SITE ERROR',row['domain'],str(error),flush=True)
            return None
    interrupted = False
    def stop(signum, frame):
        nonlocal interrupted
        interrupted = True
        STOP.set()
    signal.signal(signal.SIGTERM, stop)
    executor = concurrent.futures.ThreadPoolExecutor(max_workers=count)
    emergency_stop = args.tor_sockets[0].parent/'stop' if args.tor_sockets else None
    domains=[r['domain'] for r in rows]
    retries_ok = True
    try:
        def check_stop():
            if (STATE/'STOP').exists() or (emergency_stop and emergency_stop.exists()):
                stop(None, None)
            return STOP.is_set()

        schedule_domains(executor, rows, run, count, 1 if args.offline else args.passes, check_stop)
        if args.retry_failed and not args.offline and not check_stop():
            repair = repair_jobs if repair_jobs is not None else final_retry_jobs(selected_rows, cache)
            def retry(job):
                row, urls, indexes = job
                if check_stop():
                    return False
                worker = worker_for(row)
                # In-progress domains keep their staging area; published files can be repaired directly.
                stage = domain_stage(row)
                worker.stage = stage if args.skip_existing and not args.failed_only and stage.is_dir() else None
                return worker.retry_captures(row, urls, indexes)
            if repair:
                if not args.failed_only:
                    report(f'Final capture retry: {len(repair)} domain(s)')
                pending = {executor.submit(retry, job) for job in repair}
                while pending and not check_stop():
                    done, pending = concurrent.futures.wait(pending, timeout=1,
                                                          return_when=concurrent.futures.FIRST_COMPLETED)
                    for future in done:
                        retries_ok = future.result() and retries_ok

    except KeyboardInterrupt:
        interrupted = True
        STOP.set(); print('Stopping; downloads and pending work retained.',flush=True)
    finally:
        stopped_early = interrupted or STOP.is_set()
        STOP.set()
        executor.shutdown(wait=True,cancel_futures=True)
        if args.skip_existing:
            for row in rows:
                domain = row['domain']
                stage = domain_stage(row)
                if stopped_early and stage.is_dir():
                    shutil.rmtree(stage)
                elif not stopped_early and not (STATE/'errors'/(domain+'.json')).exists():
                    publish(row)
        summary()
    print('Download status:', (STATE/'status.json').read_text(), flush=True)
    if interrupted: return 130
    if not retries_ok: return 1
    for domain in domains:
        path = STATE/'domains'/(domain+'.json')
        if ((STATE/'errors'/(domain+'.json')).exists() or not path.exists()
                or json.loads(path.read_text()).get('status') != 'complete'):
            return 1
    return 0


if __name__ == '__main__': sys.exit(main())