"""Reproduce process environment boundaries with synthetic values only."""
import json
import os
import platform
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory

MODE = "GUMI_ENV_MODE"
MARKER = "GUMI_ENV_MARKER"
BASH = ["/bin/bash", "--noprofile", "--norc"]
SELF = [sys.executable, "-I", str(Path(__file__).resolve())]


def checked(args, *, env=None, cwd=None):
    return subprocess.run(
        args, env=env, cwd=cwd, check=True, capture_output=True, text=True,
        timeout=12,
    ).stdout


def shell_cases():
    cases = [
        ("assign_and_export", r'''
unset GUMI_ENV_MODE
GUMI_ENV_MODE=local
printf 'shell=%s\n' "$GUMI_ENV_MODE"
/usr/bin/printenv GUMI_ENV_MODE
printf 'before_export_status=%s\n' "$?"
export GUMI_ENV_MODE
/usr/bin/printenv GUMI_ENV_MODE
''', ["shell=local", "before_export_status=1", "local"]),
        ("one_command_only", r'''
export GUMI_ENV_MODE=base
GUMI_ENV_MODE=preview /usr/bin/printenv GUMI_ENV_MODE
/usr/bin/printenv GUMI_ENV_MODE
''', ["preview", "base"]),
        ("subshell_group", r'''
export GUMI_ENV_MODE=base
(
    export GUMI_ENV_MODE=preview
    /usr/bin/printenv GUMI_ENV_MODE
    /bin/bash --noprofile --norc -c 'printf "%s\n" "$GUMI_ENV_MODE"'
)
/usr/bin/printenv GUMI_ENV_MODE
''', ["preview", "preview", "base"]),
        ("argument_expansion", r'''
export GUMI_ENV_MODE=base
GUMI_ENV_MODE=preview /usr/bin/printf '%s\n' "$GUMI_ENV_MODE"
GUMI_ENV_MODE=preview /bin/bash --noprofile --norc -c 'printf "%s\n" "$GUMI_ENV_MODE"'
''', ["base", "preview"]),
        ("execute_and_source", r'''
export GUMI_ENV_MODE=base
/bin/bash --noprofile --norc ./demo-settings.sh
/usr/bin/printenv GUMI_ENV_MODE
. ./demo-settings.sh
/usr/bin/printenv GUMI_ENV_MODE
''', ["base", "from-file"]),
        ("missing_and_empty", r'''
unset GUMI_ENV_MODE
/usr/bin/printenv GUMI_ENV_MODE
printf 'missing_status=%s\n' "$?"
export GUMI_ENV_MODE=
/usr/bin/printenv GUMI_ENV_MODE
printf 'empty_status=%s\n' "$?"
''', ["missing_status=1", "", "empty_status=0"]),
    ]
    out = {}
    with TemporaryDirectory(prefix="gumi-environment-lab-") as d:
        Path(d, "demo-settings.sh").write_text(
            "export GUMI_ENV_MODE=from-file\n", encoding="utf-8",
        )
        for name, command, expected in cases:
            lines = checked([*BASH, "-c", command], env={}, cwd=d).splitlines()
            assert lines == expected, (name, lines)
            out[name] = lines
    return out


def probe():
    # Only the two fixture keys are read and included in the report.
    return {"mode": os.environ.get(MODE), "marker": os.environ.get(MARKER)}


def child_probe(env=None):
    return json.loads(checked([*SELF, "--probe"], env=env))


def python_cases():
    # This function runs in a separate interpreter with a synthetic environment.
    assert probe() == {"mode": "before", "marker": "retained"}
    replacement = child_probe({MODE: "preview"})
    child_env = os.environ.copy()
    child_env[MODE] = "preview"
    merged = child_probe(child_env)
    assert replacement == {"mode": "preview", "marker": None}
    assert merged == {"mode": "preview", "marker": "retained"}

    missing, empty = child_probe({}), child_probe({MODE: ""})
    assert missing["mode"] is None and empty["mode"] == ""
    assert probe()["mode"] == "before"  # Passing env did not modify this process.

    with subprocess.Popen(
        [*SELF, "--linger"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE, text=True,
    ) as child:
        # The old child exists; it won't read the value until receiving input.
        os.environ[MODE] = "after"
        try:
            stdout, stderr = child.communicate("read\n", timeout=8)
        except subprocess.TimeoutExpired:
            child.kill()
            child.communicate()
            raise
        if child.returncode:
            raise RuntimeError(stderr)
    running = json.loads(stdout)
    later = child_probe()
    reused = child_probe(child_env)
    assert running == {
        "read_after_parent_change": "before",
        "after_own_change": "child",
        "grandchild": {"mode": "child", "marker": "retained"},
    }
    assert later == {"mode": "after", "marker": "retained"}
    assert reused == {"mode": "preview", "marker": "retained"}
    return {
        "replacement": replacement, "merged": merged,
        "missing_and_empty": {"missing": missing["mode"], "empty": empty["mode"]},
        "running_and_new": {
            "old_child": running, "new_child": later, "reused_mapping": reused,
            "parent_after": probe(),
        },
    }


def run():
    shell = shell_cases()
    worker = json.loads(checked(
        [*SELF, "--python-cases"], env={MODE: "before", MARKER: "retained"},
    ))
    return {
        "environment": {
            "os": platform.system(), "os_version": platform.mac_ver()[0] or platform.release(),
            "machine": platform.machine(), "python": sys.version.split()[0],
            "bash": checked([*BASH, "--version"], env={}).splitlines()[0],
        },
        "shell_cases": shell, "python_cases": worker,
    }


if __name__ == "__main__":
    args = sys.argv[1:]
    if args == ["--probe"]:
        result = probe()
    elif args == ["--linger"]:
        assert sys.stdin.readline() == "read\n"
        before = os.environ[MODE]
        os.environ[MODE] = "child"
        result = {
            "read_after_parent_change": before,
            "after_own_change": os.environ[MODE],
            "grandchild": child_probe(),
        }
    elif args == ["--python-cases"]:
        result = python_cases()
    elif not args:
        result = run()
    else:
        raise SystemExit("Run without arguments to reproduce the lab.")
    print(json.dumps(result, ensure_ascii=False, indent=2))
