"""Load or check all three Foray 382 experiments in an existing Neo4j database."""

import argparse
import hashlib
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from time import monotonic
from urllib.parse import urlsplit
from urllib.request import urlopen


SITE = "https://experimentsin.ai/reopen-project-graphs/"
ARCHI = "essai-01/archisurance.py"
HISTORICAL = "essai-02/replay.py"
HASHES = {
    ARCHI: "fcc3b057411489c8f6db481df81cef72a73e1018c9991a85c3a913ef6c20da9d",
    HISTORICAL: "8e0f2c2de4dbe3ba995edffdd11e0993eed65e1cfa041a65d944f3e4b2d001d9",
}
CONNECTION_KEYS = ("NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD", "NEO4J_DATABASE")


def connection_env(credentials):
    env = os.environ.copy()
    if credentials:
        # A credential download belongs to one instance. Do not mix its values
        # with credentials for a different instance in the caller's environment.
        for key in CONNECTION_KEYS:
            env.pop(key, None)
        for line in credentials.read_text(encoding="utf-8-sig").splitlines():
            key, sep, value = line.strip().partition("=")
            if sep and key.strip() in CONNECTION_KEYS:
                value = value.strip()
                if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
                    value = value[1:-1]
                env[key.strip()] = value
    if not all(env.get(k) for k in CONNECTION_KEYS[:3]):
        raise ValueError("Supply the Aura credentials download or set the three Neo4j connection variables.")
    uri = urlsplit(env["NEO4J_URI"])
    if not uri.hostname or uri.username or uri.password:
        raise ValueError("Use a database URI without embedded credentials.")
    if uri.hostname not in {"localhost", "127.0.0.1", "::1"} and uri.scheme not in {"neo4j+s", "bolt+s"}:
        raise ValueError("Remote database connections require a certificate-verified TLS URI.")
    return env


def loader(relative, scratch):
    local = Path(__file__).resolve().parent / relative
    if local.is_file():
        data = local.read_bytes()
    else:
        with urlopen(SITE + relative, timeout=30) as response:
            data = response.read()
    if hashlib.sha256(data).hexdigest() != HASHES[relative]:
        raise ValueError("The loader differs from this release. Download the current reopen.py and retry.")
    target = scratch / Path(relative).name
    target.write_bytes(data)
    return target


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--credentials", type=Path, help="Neo4j Aura credentials download.")
    parser.add_argument("--load", action="store_true", help="Import the scoped records, then verify. Default: check only.")
    args = parser.parse_args()
    env = connection_env(args.credentials)
    try:
        import neo4j  # noqa: F401
    except ImportError:
        parser.exit(2, "Install the official driver in this Python environment with: python -m pip install neo4j\n")
    start = monotonic()
    with tempfile.TemporaryDirectory(prefix="foray382-") as directory:
        folder = Path(directory)
        archi, historical = (loader(relative, folder) for relative in (ARCHI, HISTORICAL))
        jobs = [
            ("ArchiSurance", archi, ["--load" if args.load else "--check"]),
            ("Seven waste-removal models", historical, ["waste"]),
            ("Health and Complete IT exports", historical, ["federal"]),
        ]
        for name, script, flags in jobs:
            if script == historical and not args.load:
                flags.append("--check-only")
            print(name, flush=True)
            subprocess.run([sys.executable, str(script), *flags], env=env, check=True)
    print(f"All three checks passed in {monotonic() - start:.1f} seconds.")


if __name__ == "__main__":
    try:
        main()
    except (OSError, ValueError, subprocess.CalledProcessError) as error:
        sys.exit(str(error))
