#!/usr/bin/env python3
"""Acceptance & deterministic red-side mutation suite for host 61236/61249 step-0b xdotool release."""
import hashlib
import importlib.util
import os
import shutil
import subprocess
import time
import unittest
from pathlib import Path

KIT_DIR = Path(__file__).resolve().parent

EXPECTED_DEBS = {
    "debs/libxdo3.deb": (22202, "3506c2824a74255439813f824a1629387452d52c6efd6d7916b8b54e458175e8", "libxdo3", "1:3.20160805.1-5build1", "amd64"),
    "debs/libxtst6.deb": (12642, "632d74c760f0a4e844c499e7bc1eca4c709aa096fde783a7a6807604aef77545", "libxtst6", "2:1.2.3-1.1build1", "amd64"),
    "debs/xdotool.deb": (42556, "58a202c74bce31ca2d72d4d514942a5ab6191932696adc5d21d909c9216b13cb", "xdotool", "1:3.20160805.1-5build1", "amd64"),
    "debs/libx11-6.deb": (653072, "9102f73477081a9a57994c80587ca9760341f644ed51bdfa46f2248083d418b3", "libx11-6", "2:1.8.7-1ubuntu0.1", "amd64"),
    "debs/libx11-data.deb": (115970, "5cb70f7a8e7178e0bae4fd49eee49feaed623d2d821caf6ea5862b66f9e9630b", "libx11-data", "2:1.8.7-1ubuntu0.1", "all"),
    "debs/libxcb1.deb": (47730, "e1c6611d11ad7398326f1bf028afc34c3b14c51d917a3426b966ed4b9687fa58", "libxcb1", "1.15-1ubuntu2", "amd64"),
    "debs/libxau6.deb": (7160, "e40d29f1d1a62393bacaedebe0da3d9006084152a9f7e5e029293f08ce1c5c80", "libxau6", "1:1.0.9-1build6", "amd64"),
    "debs/libxdmcp6.deb": (10254, "bcd336fce11ce2a45f34d0f95e6980af22529f22147e8f98c156e5cee8ee42bb", "libxdmcp6", "1:1.1.3-0ubuntu6", "amd64"),
    "debs/libxext6.deb": (30406, "45783969a9ece9d7b7b733b8c60981584c53c6bc5ee3b42d295d2f80d1285679", "libxext6", "2:1.3.4-1build2", "amd64"),
    "debs/libxinerama1.deb": (6396, "c8c93a3efdbb06e314f41bf48af4ca3652e4a3826bab5b9e00887660e619f239", "libxinerama1", "2:1.1.4-3build1", "amd64"),
    "debs/libxkbcommon0.deb": (121944, "2b9caeb423efb540296a1cb20b872cc630c23908407ecb5c1c787a617622d664", "libxkbcommon0", "1.6.0-1build1", "amd64"),
    "debs/libbsd0.deb": (41238, "f3857b0863ac5cfd4263e9bf6cfb1d4be88d5321e4070d5bc2b62b0949e6c86f", "libbsd0", "0.12.1-1build1.1", "amd64"),
    "debs/libmd0.deb": (26976, "e5ba01d3c41f256aaf57ec59aa0554857162e3e7f97cdfbff1ed2c0e8d720ee7", "libmd0", "1.1.0-2build1.1", "amd64"),
    "debs/x11-common.deb": (21748, "b545fa5196dd7467ba3770d6ce575abcd7941071961ea9f7535a319d9d20fd46", "x11-common", "1:7.7+23ubuntu3", "all"),
    "debs/xkb-data.deb": (397328, "e99f2a0b4c56cdf35dec489e56b6a8418826cab8ce6306ec6d0bd98e2cd0014a", "xkb-data", "2.41-2ubuntu1.1", "all"),
    "debs/lsb-base.deb": (4606, "08a563e3c1984acdb295f12b77b4ec18d2ccf52fd03280a5bea29e506a3350ee", "lsb-base", "11.6", "all"),
}

FROZEN_CORE_SHAS = {
    "scripts/watcher.py": "eed8976d715a3e303d238776d88dbe5341e7ee0016204069d2654625b6ead1aa",
    "scripts/prompt-runner.py": "13e2ebb30bf94c0df3e7a2318c889d9613778c41d60a9e5a9af1128a97a0c94c",
    "socks-ensure-detached.sh": "c05b8a0b553826976e3dcfc66207d599bcf5971ca14e35c6c5809a8495465f15",
    "verify-planb-host-acceptance.sh": "182197e9a4f8a54836028bf9c2bbff89f051b921b4f18f7d3e843c38027d92a2",
    "vpn-tunnel.sh": "e816d2662c40e0f6c3d70f5a7ae07d7757bbdae7a53d5f1ce3cce3d9241344be",
    "vnc-keep.sh": "a2c16a4c8ab46a7a69838f93b73642ab50499effc24b98de705c7a71e44cd3fb",
    "stack-watchdog.sh": "42c1fd7fe57463d8d423abf6fa7df3a175b967ebcb002fb03abdd10525f79f71",
}


def _extract_step_0b_script(start_all_text: str) -> str:
    start_marker = 'echo "=== 0b. xdotool（如缺就用本地.deb 裝）==="'
    end_marker = 'echo "=== 0c. 啟動／校整 8 條 SOCKS 隧道'
    i = start_all_text.index(start_marker)
    j = start_all_text.index(end_marker, i)
    return "set -euo pipefail\n" + start_all_text[i:j]


def _load_watcher_module():
    spec = importlib.util.spec_from_file_location("watcher_v1066", str(KIT_DIR / "scripts" / "watcher.py"))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


class TestStep0bXdotool61249(unittest.TestCase):
    def test_01_debs_hashes_versions_and_frozen_invariants(self):
        for rel, (exp_sz, exp_sha, exp_pkg, exp_ver, exp_arch) in EXPECTED_DEBS.items():
            p = KIT_DIR / rel
            self.assertTrue(p.is_file(), f"Missing {rel}")
            self.assertEqual(p.stat().st_size, exp_sz)
            self.assertEqual(hashlib.sha256(p.read_bytes()).hexdigest(), exp_sha)
            meta = subprocess.check_output(["dpkg-deb", "-I", str(p)], text=True)
            self.assertIn(f" Package: {exp_pkg}\n", meta)
            self.assertIn(f" Version: {exp_ver}\n", meta)
            self.assertIn(f" Architecture: {exp_arch}\n", meta)
            self.assertNotIn("1.2.3-1build2", meta)

        for rel, exp_sha in FROZEN_CORE_SHAS.items():
            p = KIT_DIR / rel
            self.assertEqual(hashlib.sha256(p.read_bytes()).hexdigest(), exp_sha, f"Frozen file drifted: {rel}")

        for sh in ("start-all.sh", "bootstrap.sh", "setup.sh", "update-programs.sh"):
            subprocess.run(["bash", "-n", str(KIT_DIR / sh)], check=True)

    def test_02_step_0b_all_branches_and_deterministic_red_mutation(self):
        import tempfile
        snippet = _extract_step_0b_script((KIT_DIR / "start-all.sh").read_text(encoding="utf-8"))
        with tempfile.TemporaryDirectory(prefix="step0b_mock_") as td:
            td_p = Path(td)
            fake_bin = td_p / "bin"
            fake_bin.mkdir()
            for cmd_name in ("bash", "mkdir", "install", "cp", "cat", "rm", "head", "grep", "chmod"):
                real = shutil.which(cmd_name)
                if real:
                    (fake_bin / cmd_name).symlink_to(real)

            sudo_sh = fake_bin / "sudo"
            sudo_sh.write_text('#!/bin/bash\nexec "$@"\n', encoding="utf-8")
            sudo_sh.chmod(0o755)

            dpkg_sh = fake_bin / "dpkg"
            dpkg_sh.write_text(
                '#!/bin/bash\n'
                'set -e\n'
                'shift\n'
                'for f in "$@"; do\n'
                '  head -c 4 "$f" | grep -q "^!<ar" || { echo "corrupt deb: $f" >&2; exit 2; }\n'
                'done\n'
                'cat > "' + str(fake_bin / "xdotool") + '" <<\'EOS\'\n'
                '#!/bin/bash\n'
                'echo "xdotool version 3.20160805.1"\n'
                'EOS\n'
                'chmod 0755 "' + str(fake_bin / "xdotool") + '"\n',
                encoding="utf-8",
            )
            dpkg_sh.chmod(0o755)

            home = td_p / "home"
            arena = home / "workspace" / "arena-system"
            (arena / "logs").mkdir(parents=True)
            empty_here = td_p / "empty_persistent"
            empty_here.mkdir()

            base_env = {"PATH": str(fake_bin), "HOME": str(home), "ARENA_HOME": str(arena)}

            # Branch 1: missing .debs -> warns with ⚠️ and NEVER exits under set -euo pipefail
            r1 = subprocess.run(["bash", "-c", snippet + '\necho SURVIVED_1'], env={**base_env, "HERE": str(empty_here)}, capture_output=True, text=True, check=True)
            self.assertIn("⚠️ 本地.deb 唔齊", r1.stdout)
            self.assertIn("SURVIVED_1", r1.stdout)

            # Branch 2: corrupt .debs -> warns with ⚠️ and NEVER exits under set -euo pipefail
            (arena / "debs").mkdir(parents=True, exist_ok=True)
            for fn in ("libxdo3.deb", "libxtst6.deb", "xdotool.deb"):
                (arena / "debs" / fn).write_bytes(b"bad!")
            r2 = subprocess.run(["bash", "-c", snippet + '\necho SURVIVED_2'], env={**base_env, "HERE": str(empty_here)}, capture_output=True, text=True, check=True)
            self.assertIn("⚠️ xdotool.deb 安裝失敗", r2.stdout)
            self.assertIn("SURVIVED_2", r2.stdout)

            # Branch 3: clean auto-populate from $HERE/debs -> $HOME/workspace/arena-system/debs + boot.log evidence
            shutil.rmtree(arena / "debs")
            boot_log = arena / "logs" / "boot.log"
            boot_log.write_text("", encoding="utf-8")
            r3 = subprocess.run(["bash", "-c", snippet], env={**base_env, "HERE": str(KIT_DIR)}, capture_output=True, text=True, check=True)
            self.assertTrue((arena / "debs" / "xdotool.deb").is_file())
            self.assertIn("xdotool 裝返咗：xdotool version 3.20160805.1", r3.stdout)
            self.assertIn("xdotool 裝返咗：xdotool version 3.20160805.1", boot_log.read_text(encoding="utf-8"))

            # Branch 4: idempotent skip when xdotool already present
            dpkg_sh.write_text("#!/bin/bash\nexit 99\n", encoding="utf-8")
            r4 = subprocess.run(["bash", "-c", snippet + '\necho IDEMPOTENT_OK'], env={**base_env, "HERE": str(KIT_DIR)}, capture_output=True, text=True, check=True)
            self.assertIn("IDEMPOTENT_OK", r4.stdout)

            # Deterministic Red-Side Structural Mutation: breaking step 0b dpkg command MUST fail recovery
            (fake_bin / "xdotool").unlink()
            red_snippet = snippet.replace('sudo dpkg -i "$DEBDIR"/*.deb', "false")
            subprocess.run(["bash", "-c", red_snippet], env={**base_env, "HERE": str(KIT_DIR)}, capture_output=True, text=True, check=True)
            self.assertFalse((fake_bin / "xdotool").exists(), "Red mutation must deterministically fail to restore xdotool")

    @unittest.skipUnless(os.environ.get("KIT_LIVE_DPKG_TEST") == "1", "live dpkg 雙軌制：預設跳過；一次性機器設 KIT_LIVE_DPKG_TEST=1 先跑。常駐硬閘＝test_04 確定性閉包測試（A87 61363／A62）")
    def test_03_live_dpkg_and_watcher_preflight_acceptance_with_real_x11(self):
        import tempfile
        xvfb_bin = shutil.which("Xvfb")
        disp = f":{80 + (os.getpid() % 15)}"
        xvfb_proc = None
        old_disp = os.environ.get("DISPLAY")
        try:
            if xvfb_bin:
                xvfb_proc = subprocess.Popen([xvfb_bin, disp, "-screen", "0", "640x480x24"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                for _ in range(30):
                    if Path(f"/tmp/.X11-unix/X{disp.lstrip(':')}").exists():
                        break
                    time.sleep(0.1)
                os.environ["DISPLAY"] = disp

            watcher = _load_watcher_module()
            if subprocess.run(["sudo", "-n", "true"], capture_output=True).returncode == 0:
                subprocess.run(["sudo", "dpkg", "--purge", "xdotool"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                ok_before, _ = watcher._preflight_check_xdotool_executable("A16")
                self.assertFalse(ok_before, "Preflight gate must block when /usr/bin/xdotool is absent")

                snippet = _extract_step_0b_script((KIT_DIR / "start-all.sh").read_text(encoding="utf-8"))
                with tempfile.TemporaryDirectory(prefix="step0b_live_") as td:
                    home = Path(td)
                    arena = home / "workspace" / "arena-system"
                    (arena / "logs").mkdir(parents=True)
                    boot_log = arena / "logs" / "boot.log"
                    with boot_log.open("wb") as bf:
                        subprocess.run(
                            ["bash", "-c", snippet],
                            env={**os.environ, "HOME": str(home), "ARENA_HOME": str(arena), "HERE": str(KIT_DIR)},
                            stdout=bf,
                            stderr=subprocess.STDOUT,
                            check=True,
                        )
                    boot_txt = boot_log.read_text(encoding="utf-8")
                    self.assertEqual(boot_txt.count("xdotool 裝返咗：xdotool version 3.20160805.1"), 1, boot_txt)
                    self.assertTrue((arena / "debs" / "libxdo3.deb").is_file())
                    self.assertTrue((arena / "debs" / "libxtst6.deb").is_file())
                    self.assertTrue((arena / "debs" / "xdotool.deb").is_file())

            self.assertTrue(Path("/usr/bin/xdotool").is_file() and os.access("/usr/bin/xdotool", os.X_OK))
            if xvfb_proc is not None:
                ok_xdo, detail_xdo = watcher._preflight_check_xdotool_executable("A16")
                self.assertTrue(ok_xdo, f"watcher xdotool_executable preflight failed: {detail_xdo}")
            ok_ldd, detail_ldd = watcher._preflight_check_shared_libraries_ldd("A16")
            self.assertTrue(ok_ldd, f"watcher shared_libraries_ldd preflight failed: {detail_ldd}")
        finally:
            if old_disp is None:
                os.environ.pop("DISPLAY", None)
            else:
                os.environ["DISPLAY"] = old_disp
            if xvfb_proc is not None:
                xvfb_proc.terminate()
                xvfb_proc.wait(timeout=5)

    def test_04_deb_dependency_closure_deterministic(self):
        # v20.1 硬閘（A87 61363 建議）：唔使 root、唔使真裝，用 dpkg-deb -f 核實
        # debs/ 全集 Depends 遞歸閉包；唯一豁免＝Essential 套件（libc6／sysvinit-utils）。
        import re as _re
        EXEMPT = {"libc6", "sysvinit-utils"}
        paths = sorted((KIT_DIR / "debs").glob("*.deb"))
        self.assertEqual(len(paths), 16, "v20.1 deb 集應為 16 粒")
        pkgs = {}
        for dp in paths:
            meta = subprocess.check_output(["dpkg-deb", "-f", str(dp), "Package", "Depends"], text=True)
            pkgs[_re.search(r"Package:\s*(\S+)", meta).group(1)] = meta
        for name, meta in pkgs.items():
            m = _re.search(r"Depends:\s*(.+)", meta)
            if not m:
                continue
            for part in m.group(1).split(","):
                alts = [a.strip().split(" ")[0].split("(")[0].split(":")[0] for a in part.split("|") if a.strip()]
                self.assertTrue(any(a in pkgs or a in EXEMPT for a in alts),
                                f"{name} 依賴未閉包：{part.strip()}（alts={alts}）")


if __name__ == "__main__":
    unittest.main(verbosity=2)
