from __future__ import annotations

import argparse
import base64
import csv
import hashlib
import io
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
from zipfile import ZIP_STORED, ZipFile, ZipInfo


HERE = Path(__file__).resolve().parent
PIP_VERSION = "25.1.1"
COMMON = "c3-k00-common"
LEGACY = "c3-k00-legacy"
MODERN = "c3-k00-modern"
FLEX = "c3-k00-flex"
WINDOWS = "c3-k00-win-marker"
POSIX = "c3-k00-posix-marker"
TAGGED = "c3-k00-win-tag"
FIXTURES = (
    (COMMON, "1.0", (), "py3-none-any"),
    (COMMON, "2.0", (), "py3-none-any"),
    (LEGACY, "1.0", (f"{COMMON}==1.0",), "py3-none-any"),
    (
        MODERN, "1.0",
        (
            f"{COMMON}==2.0",
            f'{WINDOWS}==1.0; sys_platform == "win32"',
            f'{POSIX}==1.0; sys_platform != "win32"',
        ),
        "py3-none-any",
    ),
    (FLEX, "1.0", (f"{COMMON}>=1,<2",), "py3-none-any"),
    (FLEX, "2.0", (f"{COMMON}>=2,<3",), "py3-none-any"),
    (WINDOWS, "1.0", (), "py3-none-any"),
    (POSIX, "1.0", (), "py3-none-any"),
    (TAGGED, "1.0", (), "py3-none-win_amd64"),
)


def wheel(directory, name, version, dependencies, tag, variant="original"):
    module = name.replace("-", "_")
    dist_info = f"{module}-{version}.dist-info"
    metadata = f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\nRequires-Python: >=3.12\n"
    metadata += "".join(f"Requires-Dist: {dep}\n" for dep in dependencies)
    files = {
        f"{module}/__init__.py": f'BUILD_VARIANT = "{variant}"\n',
        f"{dist_info}/METADATA": metadata + "\n",
        f"{dist_info}/WHEEL": (
            "Wheel-Version: 1.0\nGenerator: c3-k00-offline-fixture\n"
            f"Root-Is-Purelib: true\nTag: {tag}\n"
        ),
    }
    record = io.StringIO(newline="")
    writer = csv.writer(record, lineterminator="\n")
    for name_in_zip, content in files.items():
        value = content.encode("utf-8")
        digest = base64.urlsafe_b64encode(hashlib.sha256(value).digest()).rstrip(b"=").decode()
        writer.writerow((name_in_zip, f"sha256={digest}", len(value)))
    writer.writerow((f"{dist_info}/RECORD", "", ""))
    files[f"{dist_info}/RECORD"] = record.getvalue()

    output = directory / f"{module}-{version}-{tag}.whl"
    with ZipFile(output, "w", compression=ZIP_STORED) as archive:
        for name_in_zip, content in files.items():
            entry = ZipInfo(name_in_zip)
            entry.create_system = 3
            entry.external_attr = 0o100644 << 16
            archive.writestr(entry, content.encode("utf-8"))
    return output


def sha256(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def wheelhouses(base):
    original, changed = base / "wheels", base / "changed-wheels"
    original.mkdir()
    changed.mkdir()
    wheels = {(item[0], item[1]): wheel(original, *item) for item in FIXTURES}
    for item in FIXTURES:
        variant = "changed" if item[0:2] == (COMMON, "1.0") else "original"
        wheel(changed, *item, variant=variant)
    return original, changed, wheels


def lock_text(wheels):
    entries = ((FLEX, "1.0"), (COMMON, "1.0"), (LEGACY, "1.0"))
    return "".join(f"{name}=={version} --hash=sha256:{sha256(wheels[name, version])}\n" for name, version in entries)


def prove(root, report):
    env = {
        key: value for key, value in os.environ.items()
        if not key.upper().startswith(("PIP_", "PYTHON")) and key.upper() != "VIRTUAL_ENV"
    }
    env.update(PIP_CONFIG_FILE=os.devnull, PYTHONUTF8="1")
    original, changed, wheels = wheelhouses(root)
    report["wheels"] = {
        path.name: {"bytes": path.stat().st_size, "sha256": sha256(path)}
        for path in wheels.values()
    }
    changed_common = changed / wheels[COMMON, "1.0"].name
    report["changed_wheel"] = {"name": changed_common.name, "sha256": sha256(changed_common)}
    locked = HERE / "requirements-a.lock.txt"
    if locked.read_bytes() != lock_text(wheels).encode("utf-8"):
        raise RuntimeError("the committed lock does not match the generated wheels")

    def run(label, command, expected=0, contains=(), *, target_env=env):
        arguments = list(map(str, command))
        result = subprocess.run(
            arguments, cwd=root, env=target_env, capture_output=True, encoding="utf-8",
            errors="replace", check=False, timeout=70,
        )
        report["commands"].append(
            dict(label=label, cmd=arguments, returncode=result.returncode,
                 stdout=result.stdout, stderr=result.stderr)
        )
        text = result.stdout + result.stderr
        if result.returncode != expected or any(item not in text for item in contains):
            raise RuntimeError(f"{label} produced unexpected output:\n{text}")
        return result.stdout

    def make_venv(name):
        path = root / name
        run(f"{name} create", [sys.executable, "-I", "-m", "venv", path])
        executable = path / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
        run(f"{name} pip version", [executable, "-m", "pip", "--version"], contains=(f"pip {PIP_VERSION} ",))
        report["venv_config"][name] = (path / "pyvenv.cfg").read_text(encoding="utf-8")
        return executable

    def pip(executable, label, args, *, expected=0, contains=()):
        return run(label, [executable, "-m", "pip", "--isolated", "--disable-pip-version-check",
                           "--no-cache-dir", *args], expected, contains)

    def install(executable, label, args, *, source=original, expected=0, contains=()):
        return pip(executable, label,
                   ["install", "--no-index", "--find-links", source, "--only-binary=:all:", *args],
                   expected=expected, contains=contains)

    def inventory(executable, label):
        code = (
            "import json; from importlib.metadata import distributions; "
            'print(json.dumps({p.metadata["Name"]:p.version for p in distributions() '
            'if p.metadata["Name"].startswith("c3-k00-")}, sort_keys=True))'
        )
        return json.loads(run(label, [executable, "-I", "-c", code]))

    def probe_command(executable):
        code = (
            'import json,os,sys; print(json.dumps(dict(executable=sys.executable,'
            'prefix=sys.prefix,base_prefix=sys.base_prefix,'
            'virtual_env=os.getenv("VIRTUAL_ENV"))))'
        )
        return [executable, "-I", "-c", code]

    def import_common(executable, label):
        code = (
            'import c3_k00_common, json; from importlib.metadata import version; '
            'print(json.dumps(dict(version=version("c3-k00-common"), '
            'module_file=c3_k00_common.__file__, variant=c3_k00_common.BUILD_VARIANT)))'
        )
        imported = json.loads(run(label, [executable, "-I", "-c", code]))
        if not Path(imported["module_file"]).is_relative_to(executable.parent.parent):
            raise RuntimeError(f"{label}: module imported from outside its venv")
        return imported["version"], imported["variant"]

    def must_equal(label, actual, expected):
        if actual != expected:
            raise RuntimeError(f"{label}: received {actual!r}, expected {expected!r}")
        report["observations"][label] = actual

    a = make_venv("env-a")
    b = make_venv("env-b")
    clean = make_venv("env-clean")
    base_info = json.loads(run("base interpreter", probe_command(sys.executable)))
    a_info = json.loads(run("A by full path without activation", probe_command(a)))
    must_equal("base interpreter is outside venv", base_info["prefix"] == base_info["base_prefix"], True)
    must_equal("A uses its own prefix", a_info["prefix"] != a_info["base_prefix"], True)
    must_equal("A without activation VIRTUAL_ENV", a_info["virtual_env"], None)
    must_equal("A site packages initially empty of fixtures", inventory(a, "A initial packages"), {})

    if sys.platform == "win32":
        ps_env = dict(env, C3_LAB_A=str(a.parent.parent), C3_LAB_B=str(b))
        probe = root / "probe.py"
        probe.write_text(probe_command(a)[-1] + "\n", encoding="utf-8")
        ps_env["C3_LAB_PROBE"] = str(probe)
        commands = (
            '& (Join-Path $env:C3_LAB_A "Scripts/Activate.ps1"); '
            'python -I $env:C3_LAB_PROBE; '
            'if ($LASTEXITCODE) { exit $LASTEXITCODE }; '
            '& $env:C3_LAB_B -I $env:C3_LAB_PROBE; '
            'if ($LASTEXITCODE) { exit $LASTEXITCODE }; '
            'deactivate; '
            '$env:VIRTUAL_ENV -eq $null'
        )
        activated, explicit_b, deactivated = run(
            "PowerShell activate A / explicit B / deactivate",
            ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", commands],
            target_env=ps_env,
        ).splitlines()
        activated, explicit_b = json.loads(activated), json.loads(explicit_b)
        must_equal("PATH selects A after activation", Path(activated["executable"]), a)
        must_equal("B full path selects B while A is activated", Path(explicit_b["executable"]), b)
        must_equal("B inherits A VIRTUAL_ENV from shell", Path(explicit_b["virtual_env"]), a.parent.parent)
        must_equal("deactivation clears VIRTUAL_ENV", deactivated.strip(), "True")

    else:
        import shlex
        probe = root / "probe.py"
        probe.write_text(probe_command(a)[-1] + "\n", encoding="utf-8")
        q = shlex.quote
        commands = (
            f"set -e; . {q(str(a.parent / 'activate'))}; "
            f"python -I {q(str(probe))}; "
            f"{q(str(b))} -I {q(str(probe))}; "
            'deactivate; if [ -z "${VIRTUAL_ENV+x}" ]; then echo True; else echo False; fi'
        )
        activated, explicit_b, deactivated = run(
            "POSIX activate A / explicit B / deactivate", ["/bin/bash", "-c", commands]
        ).splitlines()
        activated, explicit_b = json.loads(activated), json.loads(explicit_b)
        must_equal("PATH selects A after activation", Path(activated["executable"]), a)
        must_equal("B full path selects B while A is activated", Path(explicit_b["executable"]), b)
        must_equal("B inherits A VIRTUAL_ENV from shell", Path(explicit_b["virtual_env"]), a.parent.parent)
        must_equal("deactivation clears VIRTUAL_ENV", deactivated.strip(), "True")

    # One install request for the conflicting roots. Inspect the clean venv afterwards.
    install(clean, "joint roots conflict", ["-r", HERE / "requirements-conflict.txt"],
            expected=1, contains=("ResolutionImpossible", "c3-k00-common==1.0", "c3-k00-common==2.0"))
    must_equal("conflicting request left no fixture installed", inventory(clean, "clean after conflict"), {})

    # A constraint file alone does not request a package. The conflicting constraint
    # later rejects the candidate required by Legacy.
    install(clean, "constraint without requested package", ["-c", HERE / "constraints-common2.txt"],
            expected=1, contains=("You must give at least one requirement to install",))
    install(clean, "install Modern; constrain unrelated Flex", [MODERN, "-c", HERE / "constraints-flex1.txt"])
    marker = WINDOWS if sys.platform == "win32" else POSIX
    must_equal("constraint cannot pull in Flex; marker selects one package",
               inventory(clean, "clean after Modern plus unrelated constraint"),
               {MODERN: "1.0", COMMON: "2.0", marker: "1.0"})

    plan_path = root / "flex-plan.json"
    plan = ["--dry-run", "--ignore-installed", "--report", plan_path]
    install(a, "plan Flex without other roots", [*plan, FLEX], contains=(f"{FLEX}-2.0",))
    install(a, "same Flex request; constrain Common below 2",
            [*plan, FLEX, "-c", HERE / "constraints-common1.txt"], contains=(f"{FLEX}-1.0",))
    install(a, "install Legacy + unpinned Flex", ["-r", HERE / "requirements-a.txt"])
    must_equal("A selects compatible versions", inventory(a, "A packages after backtracking"),
               {LEGACY: "1.0", FLEX: "1.0", COMMON: "1.0"})
    install(b, "install Modern in B", [MODERN])
    must_equal("B selects newer Common and current marker", inventory(b, "B resolved packages"),
               {MODERN: "1.0", COMMON: "2.0", marker: "1.0"})
    pip(a, "A dependencies consistent", ["check"], contains=("No broken requirements found",))
    pip(b, "B dependencies consistent", ["check"], contains=("No broken requirements found",))
    must_equal("A imports Common 1.0 after B installation",
               import_common(a, "A imports Common"), ("1.0", "original"))
    must_equal("B imports Common 2.0 from its own environment",
               import_common(b, "B imports Common"), ("2.0", "original"))
    install(b, "Legacy with incompatible Common constraint", [LEGACY, "-c", HERE / "constraints-common2.txt"],
            expected=1, contains=("ResolutionImpossible", "c3-k00-common==2.0"))

    # Separate clean environments ensure an already-installed package cannot bypass
    # the artifact download and hash check. Only the generated wheels are candidates.
    rebuild = make_venv("env-rebuild")
    must_equal("rebuild starts empty of fixtures", inventory(rebuild, "rebuild initial packages"), {})
    install(rebuild, "rebuild from hashes", ["--require-hashes", "-r", locked])
    must_equal("rebuild reproduces A distributions", inventory(rebuild, "rebuild installed packages"),
               {LEGACY: "1.0", FLEX: "1.0", COMMON: "1.0"})
    pip(rebuild, "rebuild dependencies consistent", ["check"], contains=("No broken requirements found",))
    must_equal("rebuild imports original Common 1.0",
               import_common(rebuild, "rebuild imports Common"), ("1.0", "original"))
    rejected = make_venv("env-reject")
    install(rejected, "same name/version wheel, changed bytes", ["--require-hashes", "-r", locked],
            source=changed, expected=1, contains=("DO NOT MATCH THE HASHES", sha256(changed_common)))
    must_equal("hash rejection left no fixture installed", inventory(rejected, "hash rejection packages"), {})

    download = ["download", "--no-index", "--find-links", original, "--only-binary=:all:", "--no-deps"]
    targeted = ["--python-version", "3.12", "--implementation", "cp", "--abi", "cp312"]
    pip(a, "target is Windows AMD64", [*download, *targeted, "--platform", "win_amd64", "--dest", root / "win", TAGGED],
        contains=(f"{TAGGED.replace('-', '_')}-1.0-py3-none-win_amd64.whl",))
    pip(a, "target is Linux x86-64", [*download, *targeted, "--platform", "manylinux_2_17_x86_64",
                                     "--dest", root / "linux", TAGGED],
        expected=1, contains=("No matching distribution found",))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--report", type=Path)
    parser.add_argument("--print-lock", action="store_true")
    args = parser.parse_args()
    with tempfile.TemporaryDirectory(prefix="c3-k000102-") as temporary:
        root = Path(temporary)
        if args.print_lock:
            _, _, wheels = wheelhouses(root)
            print(lock_text(wheels), end="")
            return
        if args.report is None:
            parser.error("--report is required")
        if platform.python_implementation() != "CPython" or sys.version_info[:3] != (3, 13, 5):
            parser.error("use base CPython 3.13.5, whose ensurepip provides pip 25.1.1")
        report = {
            "environment": {"python": sys.version, "platform": platform.platform(),
                            "machine": platform.machine(), "sys_platform": sys.platform,
                            "runner": str(sys.executable)},
            "commands": [], "observations": {}, "venv_config": {},
        }
        try:
            prove(root, report)
        finally:
            # pathlib objects in observations describe measured path equality.
            args.report.write_text(
                json.dumps(report, ensure_ascii=False, indent=2, default=str) + "\n", encoding="utf-8",
            )
        print(f"{len(report['commands'])} commands and {len(report['observations'])} observations verified")


if __name__ == "__main__":
    main()
