#!/usr/bin/env python3
"""
Download a list of TEOS XML ZIPs, load each into MySQL, then delete the extracted folder.

Usage:
    python bulk_load.py [--host HOST] [--port PORT] [--user USER]
                        [--password PASSWORD] [--database DATABASE]
                        [--skip-download]
                        --urls URL [URL ...]

--skip-download: assume each ZIP is already pre-staged at
    {tempdir}/charity_bulk/{name}.zip (e.g. scp'd or wget'd by hand).
    URLs are only used to derive the filename; no network fetch is attempted.
"""

import argparse
import http.client
import os
import re
import shutil
import socket
import ssl
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
from pathlib import Path

DOWNLOAD_TIMEOUT_SECONDS = 600

# Resource-exhaustion guards (override with --max-download-gb / --max-extract-gb).
DEFAULT_MAX_DOWNLOAD_GB = 20
DEFAULT_MAX_EXTRACT_GB = 100
EXTRACT_MAX_RATIO = 200  # reject archives that expand more than 200:1

# Derived-from-URL names are used as path components under the staging dir;
# anything else (e.g. "..", "", "a/b") is rejected before touching the fs.
_SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")

# Environment variable consulted when --password is not given, so the DB
# credential does not have to appear in the process argument vector.
PASSWORD_ENV_VAR = "CHARITY_DB_PASSWORD"

# Chunked-Range downloader knobs. Each chunk is a short, fresh HTTPS connection,
# which sidesteps mid-stream connection resets from Akamai-fronted hosts
# (e.g. apps.irs.gov) on rate-limited shared-hosting IPs.
CHUNK_SIZE_BYTES = 4 * 1024 * 1024
CHUNK_TIMEOUT_SECONDS = 120
CHUNK_RETRIES = 5
CHUNK_BACKOFF_SECONDS = 4
INTER_CHUNK_SLEEP_SECONDS = 0.25
PROGRESS_EVERY_N_CHUNKS = 8

LOADERS = {
    "IRS":   Path(__file__).parent / "load_to_mysql.py",
    "CRA":   Path(__file__).parent / "load_cra.py",
    "CCEW":  Path(__file__).parent / "load_ccew.py",
    "OSCR":  Path(__file__).parent / "load_oscr.py",
    "CCNI":  Path(__file__).parent / "load_ccni.py",
}

# Sources that ship a single CSV/JSON/SQL file directly (no ZIP-of-XML pattern).
DIRECT_FILE_SOURCES = {"OSCR", "CCNI"}

# Sources whose loader resolves URLs itself (e.g. via a dataset/catalog API).
# bulk_load.py passes the user-provided URL straight through to the loader's
# --input argument without downloading anything.
# CCEW is here because its download page links to multiple ZIPs that the loader
# fetches and extracts itself.
PASSTHROUGH_URL_SOURCES = {"CRA", "CCEW"}


def download(url: str, dest: Path, max_bytes: int) -> None:
    print(f"  Downloading {url.split('/')[-1]} ...", flush=True)

    # Fast path first: single-shot curl (or urllib). On healthy connections this
    # is ~2-3x faster than the chunked path's per-chunk handshake overhead.
    # Partial bytes are intentionally preserved on failure so the chunked
    # fallback can resume via Range: bytes=N-.
    fast_exc = None
    try:
        if shutil.which("curl"):
            _download_curl_oneshot(url, dest, max_bytes)
        else:
            _download_urllib_oneshot(url, dest, max_bytes)
        _enforce_size_cap(dest, max_bytes)
        return
    except Exception as exc:
        fast_exc = exc
        partial = dest.stat().st_size if dest.exists() else 0
        print(
            f"  Fast download failed ({exc}); resuming via chunked Range "
            f"from {partial // (1024 * 1024)} MB ...",
            flush=True,
        )

    # Resilient finisher: short Range requests dodge CDN mid-stream resets.
    try:
        _download_chunked(url, dest, max_bytes)
        _enforce_size_cap(dest, max_bytes)
        return
    except _ChunkedUnsupported as exc:
        # Server rejects HEAD / Range — nothing left but to re-raise the
        # original fast-path failure, which is the more informative error.
        raise fast_exc from exc


def _enforce_size_cap(dest: Path, max_bytes: int) -> None:
    size = dest.stat().st_size if dest.exists() else 0
    if size > max_bytes:
        dest.unlink(missing_ok=True)
        raise RuntimeError(
            f"download exceeded the {max_bytes // (1024 ** 3)} GB limit "
            f"({size} bytes); deleted. Raise --max-download-gb if legitimate."
        )


class _ChunkedUnsupported(Exception):
    """Server doesn't advertise a Content-Length or rejected Range requests."""


def _make_ssl_context() -> ssl.SSLContext:
    # Full certificate + hostname verification. If a regulator host ever ships
    # a broken chain, pin that host's CA via ctx.load_verify_locations() —
    # never disable verification globally.
    return ssl.create_default_context()


def _head_content_length(url: str, ctx: ssl.SSLContext) -> int:
    req = urllib.request.Request(
        url,
        method="HEAD",
        headers={"User-Agent": "Mozilla/5.0", "Connection": "close"},
    )
    with urllib.request.urlopen(req, timeout=CHUNK_TIMEOUT_SECONDS, context=ctx) as resp:
        length = resp.headers.get("Content-Length")
        if length is None:
            raise _ChunkedUnsupported("no Content-Length on HEAD")
        return int(length)


def _fetch_range(url: str, start: int, end: int, ctx: ssl.SSLContext) -> bytes:
    headers = {
        "User-Agent": "Mozilla/5.0",
        "Range": f"bytes={start}-{end}",
        "Connection": "close",
        "Accept-Encoding": "identity",
    }
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(req, timeout=CHUNK_TIMEOUT_SECONDS, context=ctx) as resp:
        if resp.status not in (200, 206):
            raise RuntimeError(f"unexpected status {resp.status} for Range {start}-{end}")
        return resp.read()


def _download_chunked(url: str, dest: Path, max_bytes: int) -> None:
    ctx = _make_ssl_context()

    try:
        total = _head_content_length(url, ctx)
    except _ChunkedUnsupported:
        raise
    except (urllib.error.HTTPError, urllib.error.URLError) as exc:
        raise _ChunkedUnsupported(f"HEAD failed: {exc}")

    if total > max_bytes:
        raise RuntimeError(
            f"remote file is {total} bytes, over the {max_bytes // (1024 ** 3)} GB "
            f"limit. Raise --max-download-gb if legitimate."
        )

    start = dest.stat().st_size if dest.exists() else 0
    if start > total:
        # Stale partial larger than remote (server rotated file?) — restart.
        dest.unlink(missing_ok=True)
        start = 0
    if start == total:
        return

    chunk_index = 0
    transient = (
        ConnectionResetError,
        socket.timeout,
        TimeoutError,
        http.client.IncompleteRead,
        http.client.RemoteDisconnected,
        urllib.error.URLError,
        ssl.SSLError,
    )

    with open(dest, "ab") as f:
        pos = start
        while pos < total:
            end = min(pos + CHUNK_SIZE_BYTES - 1, total - 1)
            for attempt in range(1, CHUNK_RETRIES + 1):
                try:
                    data = _fetch_range(url, pos, end, ctx)
                    if not data:
                        raise RuntimeError("empty chunk body")
                    f.write(data)
                    f.flush()
                    pos += len(data)
                    break
                except transient as exc:
                    if attempt == CHUNK_RETRIES:
                        raise RuntimeError(
                            f"chunk {pos}-{end} failed after {CHUNK_RETRIES} attempts: {exc}"
                        )
                    time.sleep(CHUNK_BACKOFF_SECONDS * (2 ** (attempt - 1)))
            chunk_index += 1
            if chunk_index % PROGRESS_EVERY_N_CHUNKS == 0 or pos >= total:
                pct = int(100 * pos / total) if total else 100
                print(
                    f"  Downloaded {pos // (1024 * 1024)}/{total // (1024 * 1024)} MB ({pct}%)",
                    flush=True,
                )
            time.sleep(INTER_CHUNK_SLEEP_SECONDS)

    actual = dest.stat().st_size
    if actual != total:
        raise RuntimeError(f"size mismatch after chunked download: got {actual}, expected {total}")


def _download_curl_oneshot(url: str, dest: Path, max_bytes: int) -> None:
    """Single-shot curl with resume. On failure, partial bytes stay on disk
    so the chunked fallback can pick up where this left off."""
    cmd = [
        "curl",
        "--fail",
        "--location",
        "--silent",
        "--show-error",
        "--user-agent", "Mozilla/5.0",
        "--continue-at", "-",
        "--speed-limit", "1000",
        "--speed-time", "30",
        "--max-filesize", str(max_bytes),
        "--output", str(dest),
        url,
    ]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(
            f"curl exited {result.returncode}: {result.stderr.strip() or 'no stderr'}"
        )


def _download_urllib_oneshot(url: str, dest: Path, max_bytes: int) -> None:
    """Single-shot urllib with resume. Partial bytes survive on failure."""
    ctx = _make_ssl_context()
    existing = dest.stat().st_size if dest.exists() else 0
    headers = {"User-Agent": "Mozilla/5.0"}
    if existing:
        headers["Range"] = f"bytes={existing}-"
    req = urllib.request.Request(url, headers=headers)
    with urllib.request.urlopen(
        req, timeout=DOWNLOAD_TIMEOUT_SECONDS, context=ctx
    ) as resp:
        mode = "ab" if existing and resp.status == 206 else "wb"
        written = existing if mode == "ab" else 0
        with open(dest, mode) as f:
            while True:
                chunk = resp.read(1 << 20)
                if not chunk:
                    break
                written += len(chunk)
                if written > max_bytes:
                    raise RuntimeError(
                        f"download exceeded the {max_bytes // (1024 ** 3)} GB limit; "
                        f"aborting. Raise --max-download-gb if legitimate."
                    )
                f.write(chunk)


def _zip_is_intact(path: Path) -> bool:
    """True if the zip has a readable central directory with at least one entry.

    Does NOT decompress entries — IRS TEOS zips ship as deflate64 (method 9),
    which Python's stdlib zipfile cannot decode but system `unzip` can. A
    structurally valid central directory is enough to rule out a truncated
    download; actual extraction defers to `_extract_zip`.
    """
    if not path.exists() or path.stat().st_size == 0:
        return False
    if not zipfile.is_zipfile(path):
        return False
    try:
        with zipfile.ZipFile(path) as zf:
            return len(zf.namelist()) > 0
    except (zipfile.BadZipFile, OSError):
        return False


def _derive_name(url: str) -> str | None:
    """Derive a filesystem-safe staging name from the URL's last path segment.
    Returns None (caller must skip the URL) for anything that could escape or
    collide outside the staging directory: empty, '.', '..', separators, etc."""
    name = url.split("/")[-1].split("?")[0].replace(".zip", "")
    if name in ("", ".", "..") or not _SAFE_NAME_RE.fullmatch(name):
        return None
    return name


def _assert_contained(path: Path, base: Path) -> None:
    """Refuse to operate on a path that resolves outside the staging base."""
    resolved = path.resolve()
    base_resolved = base.resolve()
    if resolved != base_resolved and base_resolved not in resolved.parents:
        raise RuntimeError(f"refusing to touch {resolved}: outside {base_resolved}")


def _validate_zip_members(zip_path: Path, max_total_bytes: int) -> None:
    """Reject archives that would traverse outside the extraction dir, expand
    past the absolute cap, or expand at a zip-bomb compression ratio."""
    total_uncompressed = 0
    with zipfile.ZipFile(zip_path) as zf:
        for info in zf.infolist():
            member = Path(info.filename)
            if member.is_absolute() or ".." in member.parts:
                raise RuntimeError(f"zip member has unsafe path: {info.filename!r}")
            total_uncompressed += info.file_size

    if total_uncompressed > max_total_bytes:
        raise RuntimeError(
            f"archive expands to {total_uncompressed} bytes, over the "
            f"{max_total_bytes // (1024 ** 3)} GB limit. Raise --max-extract-gb "
            f"if legitimate."
        )

    compressed = zip_path.stat().st_size
    if compressed and total_uncompressed / compressed > EXTRACT_MAX_RATIO:
        raise RuntimeError(
            f"archive compression ratio {total_uncompressed // max(compressed, 1)}:1 "
            f"exceeds {EXTRACT_MAX_RATIO}:1 — refusing (possible zip bomb)."
        )


def _extract_zip(zip_path: Path, dest_dir: Path, max_total_bytes: int) -> None:
    """Extract zip into dest_dir. Prefers system `unzip` (supports deflate64,
    which Python's stdlib zipfile does not)."""
    _validate_zip_members(zip_path, max_total_bytes)
    if shutil.which("unzip"):
        result = subprocess.run(
            ["unzip", "-o", "-q", str(zip_path), "-d", str(dest_dir)],
            capture_output=True,
            text=True,
        )
        if result.returncode != 0:
            raise RuntimeError(
                f"unzip exited {result.returncode}: {result.stderr.strip() or 'no stderr'}"
            )
        return
    shutil.unpack_archive(str(zip_path), str(dest_dir))


def main():
    parser = argparse.ArgumentParser(description="Bulk-load TEOS XML ZIPs into MySQL")
    parser.add_argument("--host",     default="127.0.0.1")
    parser.add_argument("--port",     type=int, default=3306)
    parser.add_argument("--user",     default="root")
    parser.add_argument(
        "--password",
        default=os.environ.get(PASSWORD_ENV_VAR, ""),
        help=f"MySQL password. Prefer the {PASSWORD_ENV_VAR} environment "
             f"variable so the credential stays out of the process list.",
    )
    parser.add_argument("--database", default="irs990")
    parser.add_argument(
        "--max-download-gb",
        type=int,
        default=DEFAULT_MAX_DOWNLOAD_GB,
        help="Abort any single download larger than this (GB).",
    )
    parser.add_argument(
        "--max-extract-gb",
        type=int,
        default=DEFAULT_MAX_EXTRACT_GB,
        help="Refuse to extract an archive whose uncompressed size exceeds this (GB).",
    )
    parser.add_argument(
        "--source",
        default="IRS",
        choices=list(LOADERS.keys()),
        help="Data source: IRS (US), CRA (Canada), CCEW (E&W), OSCR (Scotland), CCNI (NI)",
    )
    parser.add_argument(
        "--ccew-mode",
        choices=("latest", "all"),
        default="latest",
        help="CCEW only: latest year per charity (default) or every AR cycle.",
    )
    parser.add_argument("--urls",     nargs="+", default=[], metavar="URL")
    parser.add_argument(
        "--skip-download",
        action="store_true",
        help="Skip network download; assume each ZIP is pre-staged at "
             "{tempdir}/charity_bulk/{name}.zip. URLs only used for naming.",
    )
    args = parser.parse_args()

    loader_script = LOADERS[args.source]
    if not loader_script.exists():
        print(
            f"ERROR: loader script not found for source={args.source}: {loader_script}",
            flush=True,
        )
        sys.exit(2)

    base_tmp = Path(tempfile.gettempdir()) / "charity_bulk"
    base_tmp.mkdir(exist_ok=True)

    max_download_bytes = args.max_download_gb * 1024 ** 3
    max_extract_bytes = args.max_extract_gb * 1024 ** 3

    # Hand the DB password to loader children via the environment, not argv,
    # so it never appears in the process table during multi-hour imports.
    child_env = {**os.environ, PASSWORD_ENV_VAR: args.password}

    # CCEW can self-resolve its dataset from the Charity Commission website,
    # so an empty --urls list runs the loader once with no --input. Other
    # sources still require at least one URL.
    if not args.urls:
        if args.source != "CCEW":
            print(
                f"ERROR: --urls is required for source={args.source}.",
                flush=True,
            )
            sys.exit(2)

        print("\n[1/1] Processing CCEW (auto-download)", flush=True)
        cmd = [
            sys.executable, str(loader_script),
            "--host",     args.host,
            "--port",     str(args.port),
            "--user",     args.user,
            "--database", args.database,
            "--mode",     args.ccew_mode,
        ]
        result = subprocess.run(cmd, env=child_env)
        if result.returncode != 0:
            print(f"  WARNING: loader exited with code {result.returncode}", flush=True)
        print("\nAll 1 input(s) complete.", flush=True)
        return

    total = len(args.urls)
    for idx, url in enumerate(args.urls, 1):
        # Only branches that stage files locally need `name`; passthrough
        # sources use it purely for display, so any URL shape is fine there.
        name = _derive_name(url)
        print(f"\n[{idx}/{total}] Processing {name or url}", flush=True)

        # ── Passthrough sources: loader resolves the URL itself ──────────────
        if args.source in PASSTHROUGH_URL_SOURCES:
            print(f"  Handing dataset URL to {args.source} loader ...", flush=True)
            cmd = [
                sys.executable, str(loader_script),
                "--host",     args.host,
                "--port",     str(args.port),
                "--user",     args.user,
                "--database", args.database,
                "--input",    url,
            ]
            if args.source == "CCEW":
                cmd += ["--mode", args.ccew_mode]
            result = subprocess.run(cmd, env=child_env)
            if result.returncode != 0:
                print(f"  WARNING: loader exited with code {result.returncode}", flush=True)
            print(f"  Done with {name or url}.", flush=True)
            continue

        # From here on `name` becomes a path component under base_tmp, so a
        # URL it can't be safely derived from is a hard skip.
        if name is None:
            print(
                f"  ERROR: cannot derive a safe staging name from URL {url!r}; "
                f"skipping.",
                flush=True,
            )
            continue

        # ── Direct CSV/JSON/SQL sources (no ZIP-of-XML) ──────────────────────
        if args.source in DIRECT_FILE_SOURCES:
            suffix = Path(url.split("?")[0]).suffix or ".dat"
            dest_path = base_tmp / f"{name}{suffix}"
            if args.skip_download:
                if not dest_path.exists():
                    print(
                        f"  ERROR: --skip-download set but no pre-staged file at {dest_path}",
                        flush=True,
                    )
                    continue
                print(f"  Using pre-staged file at {dest_path}", flush=True)
            else:
                try:
                    download(url, dest_path, max_download_bytes)
                except Exception as exc:
                    print(f"  ERROR downloading: {exc}", flush=True)
                    continue

            # If it's a ZIP wrapping CSVs, extract.
            target_path = dest_path
            if dest_path.suffix.lower() == ".zip":
                if not _zip_is_intact(dest_path):
                    print(
                        "  ERROR: zip failed integrity check (corrupt or truncated); "
                        "deleting and skipping",
                        flush=True,
                    )
                    dest_path.unlink(missing_ok=True)
                    continue
                extract_dir = base_tmp / name
                _assert_contained(extract_dir, base_tmp)
                extract_dir.mkdir(exist_ok=True)
                try:
                    _extract_zip(dest_path, extract_dir, max_extract_bytes)
                except Exception as exc:
                    print(f"  ERROR extracting: {exc}", flush=True)
                    dest_path.unlink(missing_ok=True)
                    continue
                target_path = extract_dir

            print(f"  Loading into MySQL via {args.source} loader ...", flush=True)
            cmd = [
                sys.executable, str(loader_script),
                "--host",     args.host,
                "--port",     str(args.port),
                "--user",     args.user,
                "--database", args.database,
                "--input",    str(target_path),
            ]
            result = subprocess.run(cmd, env=child_env)
            if result.returncode != 0:
                print(f"  WARNING: loader exited with code {result.returncode}", flush=True)

            print("  Cleaning up download ...", flush=True)
            if dest_path.exists():
                dest_path.unlink(missing_ok=True)
            if target_path != dest_path and target_path.exists():
                _assert_contained(target_path, base_tmp)
                shutil.rmtree(target_path, ignore_errors=True)

            print(f"  Done with {name}.", flush=True)
            continue

        # ── IRS path: ZIP of XML files ──────────────────────────────────────
        zip_path = base_tmp / f"{name}.zip"
        extract_dir = base_tmp / name
        _assert_contained(extract_dir, base_tmp)

        if args.skip_download:
            if not zip_path.exists():
                print(
                    f"  ERROR: --skip-download set but no pre-staged zip at {zip_path}",
                    flush=True,
                )
                continue
            print(f"  Using pre-staged zip at {zip_path}", flush=True)
        else:
            try:
                download(url, zip_path, max_download_bytes)
            except Exception as exc:
                print(f"  ERROR downloading: {exc}", flush=True)
                continue

        if not _zip_is_intact(zip_path):
            print(
                "  ERROR: zip failed integrity check (corrupt or truncated); "
                "deleting and skipping",
                flush=True,
            )
            zip_path.unlink(missing_ok=True)
            continue

        print("  Extracting ...", flush=True)
        extract_dir.mkdir(exist_ok=True)
        try:
            _extract_zip(zip_path, extract_dir, max_extract_bytes)
        except Exception as exc:
            print(f"  ERROR extracting: {exc}", flush=True)
            zip_path.unlink(missing_ok=True)
            continue
        finally:
            # Preserve pre-staged zip so the user can retry without re-staging;
            # auto-downloaded zips are disposable.
            if not args.skip_download:
                zip_path.unlink(missing_ok=True)

        xml_dir = extract_dir
        if not list(extract_dir.glob("*_public.xml")):
            subdirs = [p for p in extract_dir.rglob("*_public.xml")]
            if subdirs:
                xml_dir = subdirs[0].parent

        print("  Loading into MySQL ...", flush=True)
        cmd = [
            sys.executable, str(loader_script),
            "--host",     args.host,
            "--port",     str(args.port),
            "--user",     args.user,
            "--database", args.database,
            "--xml-dir",  str(xml_dir),
        ]
        result = subprocess.run(cmd, env=child_env)
        if result.returncode != 0:
            print(f"  WARNING: loader exited with code {result.returncode}", flush=True)

        print("  Deleting extracted XML folder ...", flush=True)
        _assert_contained(extract_dir, base_tmp)
        shutil.rmtree(extract_dir, ignore_errors=True)

        print(f"  Done with {name}.", flush=True)

    print(f"\nAll {total} input(s) complete.", flush=True)


if __name__ == "__main__":
    main()
