#!/usr/bin/env python3
"""POSIX environment-boundary fixture. Synthetic markers only; no network."""
import json
import os
from pathlib import Path
import subprocess
import sys
import unittest

CANARY = "FAKE_SUPERVISOR_CREDENTIAL_9c72"
KEY = "DEMO_CONTROL_TOKEN"
FUTURE_KEY = "DEMO_FUTURE_CREDENTIAL"
PROBE = """import json, os
print(json.dumps({k: os.environ.get(k) for k in
('DEMO_CONTROL_TOKEN', 'DEMO_FUTURE_CREDENTIAL', 'DEMO_TOOL_MODE')}))
"""


def tool_environment():
    # Fixed application policy, not a copy of the supervisor environment.
    return {"LANG": "C", "DEMO_TOOL_MODE": "offline"}


def launch(env):
    result = subprocess.run(
        [sys.executable, "-I", "-S", "-c", PROBE],
        env=env, shell=False, close_fds=True, stdin=subprocess.DEVNULL,
        capture_output=True, text=True, check=True, timeout=10,
    )
    return json.loads(result.stdout)


def case(mode):
    if mode == "inherited":
        env = None
    elif mode == "copied":
        env = {**os.environ, "DEMO_TOOL_MODE": "offline"}
    elif mode == "denylist":
        env = dict(os.environ)
        env.pop(KEY, None)
    elif mode == "explicit":
        env = tool_environment()
    else:
        raise ValueError("unknown case")
    before = os.environ.get(KEY)
    observed = launch(env)
    return {"observed": observed, "parent_unchanged": before == os.environ.get(KEY)}


def run_case(mode):
    # Start the demonstration supervisor in a synthetic environment.
    # Never pass the caller's real environment to the deliberately weak cases.
    fixture_env = {"LANG": "C", KEY: CANARY, FUTURE_KEY: "FAKE_FUTURE_42"}
    result = subprocess.run(
        [sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--case", mode],
        env=fixture_env, stdin=subprocess.DEVNULL, close_fds=True,
        capture_output=True, text=True, check=True, timeout=20,
    )
    return json.loads(result.stdout)


class EnvironmentTests(unittest.TestCase):
    def test_default_inherits(self):
        self.assertEqual(run_case("inherited")["observed"][KEY], CANARY)

    def test_copy_keeps_credential(self):
        self.assertEqual(run_case("copied")["observed"][KEY], CANARY)

    def test_denylist_misses_new_key(self):
        observed = run_case("denylist")["observed"]
        self.assertIsNone(observed[KEY])
        self.assertEqual(observed[FUTURE_KEY], "FAKE_FUTURE_42")

    def test_explicit_excludes_both(self):
        observed = run_case("explicit")["observed"]
        self.assertIsNone(observed[KEY])
        self.assertIsNone(observed[FUTURE_KEY])

    def test_explicit_preserves_tool_setting(self):
        self.assertEqual(run_case("explicit")["observed"]["DEMO_TOOL_MODE"], "offline")

    def test_parent_not_mutated(self):
        self.assertTrue(run_case("explicit")["parent_unchanged"])

    def test_mapping_is_fresh(self):
        env = tool_environment()
        env[KEY] = CANARY
        self.assertNotIn(KEY, tool_environment())


if __name__ == "__main__":
    if os.name != "posix":
        raise SystemExit("This fixture targets POSIX; Windows needs a separate runtime policy.")
    if len(sys.argv) == 3 and sys.argv[1] == "--case":
        print(json.dumps(case(sys.argv[2]), sort_keys=True))
    elif sys.argv[1:] == ["--test"]:
        unittest.main(argv=[sys.argv[0]], verbosity=2)
    elif not sys.argv[1:]:
        print(json.dumps({m: run_case(m) for m in
                          ("inherited", "copied", "denylist", "explicit")}, indent=2))
    else:
        raise SystemExit("Usage: python3 agent-subprocess-environment.py [--test]")
