#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Regression & Bisect Test Suite for seq=61154 (P0):
Verifies that both watcher.py (v10.6.4) and prompt-runner.py (v1.6.5-v10.6.4)
preserve Google login state (Local State, Cookies, Preferences, Secure Preferences,
Chromium PrefHashFilter super_mac HMAC, and myaccount.google.com session) across the
entire 5-step pipeline and under concurrent watcher + prompt-runner execution.
"""
import hashlib
import hmac
import importlib.util
import json
import os
import shutil
import sqlite3
import tempfile
import unittest
from pathlib import Path

KIT_DIR = Path(__file__).resolve().parent
V17_DIR = Path(os.environ.get("KIT_SCRIPTS_DIR") or (KIT_DIR / "scripts"))


def _load_mod(name, path):
    spec = importlib.util.spec_from_file_location(name, str(path))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


W17 = _load_mod("watcher_v17", V17_DIR / "watcher.py")
P17 = _load_mod("prompt_runner_v17", V17_DIR / "prompt-runner.py")

SEED_HMAC_KEY = b"chrome-pref-hash-seed-61154"
DEVICE_ID = "device-id-longyi-vm-01"


def _compute_mac(path_key, val_obj):
    msg = (
        DEVICE_ID
        + path_key
        + json.dumps(val_obj, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
    ).encode("utf-8")
    return hmac.new(SEED_HMAC_KEY, msg, hashlib.sha256).hexdigest().upper()


def _compute_super_mac(macs_dict):
    msg = (
        DEVICE_ID
        + json.dumps(macs_dict, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
    ).encode("utf-8")
    return hmac.new(SEED_HMAC_KEY, msg, hashlib.sha256).hexdigest().upper()


def _create_logged_in_google_seed_profile(seed_dir: Path, email="ippocrate284dimiceli@gmail.com"):
    (seed_dir / "Default" / "Network").mkdir(parents=True, exist_ok=True)
    local_state = {
        "os_crypt": {"encrypted_key": "RFBFAV_MOCK_KEY_61154_BASE64=="},
        "profile": {
            "info_cache": {
                "Default": {
                    "user_name": email,
                    "gaia_id": "10928374651029384756",
                    "is_consented_primary_account": True,
                }
            }
        },
    }
    (seed_dir / "Local State").write_text(
        json.dumps(local_state, ensure_ascii=False, separators=(",", ":")),
        encoding="utf-8",
    )
    for cpath in [seed_dir / "Default" / "Cookies", seed_dir / "Default" / "Network" / "Cookies"]:
        conn = sqlite3.connect(str(cpath))
        conn.execute(
            "CREATE TABLE cookies (host_key TEXT, name TEXT, value TEXT, encrypted_value BLOB, path TEXT, is_secure INTEGER)"
        )
        for cname in ("SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-1PSID", "__Secure-3PSID", "LSID"):
            conn.execute(
                "INSERT INTO cookies VALUES (?, ?, ?, ?, '/', 1)",
                (".google.com", cname, "", f"ENC_{cname}_{email}".encode("utf-8")),
            )
        conn.commit()
        conn.close()

    account_info = [
        {
            "account_id": "10928374651029384756",
            "email": email,
            "gaia": "10928374651029384756",
            "is_under_advanced_protection": False,
        }
    ]
    google_services = {
        "account_id": "10928374651029384756",
        "consented_to_sync": True,
        "last_username": email,
        "signin_scoped_device_id": "device-scoped-id-61154-abcdef",
    }
    extensions_settings = {
        "hnmpcagpplmpfojmgmnngilcnanddlhb": {"state": 1, "location": 4}
    }
    macs = {
        "account_info": _compute_mac("account_info", account_info),
        "google": {"services": _compute_mac("google.services", google_services)},
        "extensions": {"settings": _compute_mac("extensions.settings", extensions_settings)},
    }
    prefs = {
        "account_info": account_info,
        "google": {"services": google_services},
        "extensions": {"settings": extensions_settings},
        "partition": {"default_zoom_level": {"x": 1.0}},
        "protection": {"macs": macs, "super_mac": _compute_super_mac(macs)},
    }
    (seed_dir / "Default" / "Preferences").write_text(
        json.dumps(prefs, ensure_ascii=False, separators=(",", ":")),
        encoding="utf-8",
    )
    (seed_dir / "Default" / "Login Data").write_bytes(b"SQLITE_LOGIN_DATA_61154")
    (seed_dir / "Default" / "Web Data").write_bytes(b"SQLITE_WEB_DATA_61154")


def _create_ws_donor_profile(ws_dir: Path, include_ldb_creds=True):
    ext_dir = (
        ws_dir
        / "Default"
        / "Extensions"
        / "hnmpcagpplmpfojmgmnngilcnanddlhb"
        / "4.0.0_0"
    )
    ext_dir.mkdir(parents=True, exist_ok=True)
    (ext_dir / "manifest.json").write_text(
        '{"name":"Windscribe","version":"4.0.0","manifest_version":3}',
        encoding="utf-8",
    )
    ldb_dir = (
        ws_dir
        / "Default"
        / "Local Extension Settings"
        / "hnmpcagpplmpfojmgmnngilcnanddlhb"
    )
    ldb_dir.mkdir(parents=True, exist_ok=True)
    if include_ldb_creds:
        payload = (
            'serverCredentials{"username":"wsuser61154","password":"wspass61154"}'
            'proxy{"hosts":["ams-195.whiskergalaxy.com"],"port":443}'
        )
        (ldb_dir / "000005.ldb").write_bytes(payload.encode("utf-8"))
    else:
        (ldb_dir / "000005.ldb").write_bytes(b"EMPTY_UNINITIALIZED_WS_LDB")

    ws_ext_settings = {
        "hnmpcagpplmpfojmgmnngilcnanddlhb": {
            "state": 1,
            "path": "hnmpcagpplmpfojmgmnngilcnanddlhb/4.0.0_0",
        }
    }
    ws_macs = {"extensions": {"settings": "DEAD9999BEEF0000111122223333444455556666777788889999AAAABBBBCCCC"}}
    ws_prefs = {
        "extensions": {"settings": ws_ext_settings},
        "protection": {"macs": ws_macs, "super_mac": "FOREIGN_WS_SUPER_MAC_0000"},
    }
    (ws_dir / "Default" / "Preferences").write_text(
        json.dumps(ws_prefs, ensure_ascii=False, separators=(",", ":")),
        encoding="utf-8",
    )
    (ws_dir / "Default" / "Secure Preferences").write_text(
        json.dumps(ws_prefs, ensure_ascii=False, separators=(",", ":")),
        encoding="utf-8",
    )


def _simulate_chromium_myaccount_check(profile_dir: Path):
    """Simulates Chromium loading profile_dir and navigating to https://myaccount.google.com/."""
    pdir = Path(profile_dir)
    if not (pdir / "Local State").is_file() or not (pdir / "Default" / "Cookies").is_file():
        return {"ok": False, "reason": "PROFILE_WIPED_OR_MISSING_FILES"}
    prefs_p = pdir / "Default" / "Preferences"
    if not prefs_p.is_file():
        return {"ok": False, "reason": "PREFS_MISSING"}
    prefs = json.loads(prefs_p.read_text(encoding="utf-8"))
    sec_p = pdir / "Default" / "Secure Preferences"
    if sec_p.is_file():
        sec = json.loads(sec_p.read_text(encoding="utf-8"))
        sec_macs = sec.get("protection", {}).get("macs", {})
        if _compute_super_mac(sec_macs) != sec.get("protection", {}).get("super_mac", ""):
            return {"ok": False, "reason": "SECURE_PREFS_SUPER_MAC_INVALID"}
        if "account_info" not in sec and "account_info" not in sec_macs:
            return {"ok": False, "reason": "SECURE_PREFS_INCOMPLETE_WIPED_ACCOUNT_INFO"}
    macs = prefs.get("protection", {}).get("macs", {})
    expected_sm = _compute_super_mac(macs)
    actual_sm = prefs.get("protection", {}).get("super_mac", "")
    if expected_sm != actual_sm:
        return {"ok": False, "reason": f"PREFS_SUPER_MAC_INVALID:{expected_sm[:12]}!={actual_sm[:12]}"}
    acc = prefs.get("account_info", [])
    if not acc:
        return {"ok": False, "reason": "NO_ACCOUNT_INFO"}
    return {"ok": True, "reason": "LOGGED_IN", "email": acc[0]["email"]}


class TestProfileGoogleLoginPreservation61154(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp(prefix="/tmp/test_61154_"))
        self.seed_root = self.tmp / "local-profiles"
        self.ws_root = self.tmp / "ws-profiles"
        self.ram_watcher = self.tmp / "shm-watcher-profiles"
        self.ram_pr = self.tmp / "shm-prompt-runner-profiles"
        for d in (self.seed_root, self.ws_root, self.ram_watcher, self.ram_pr):
            d.mkdir(parents=True, exist_ok=True)
        _create_logged_in_google_seed_profile(self.seed_root / "ai-58", "ippocrate284dimiceli@gmail.com")
        _create_logged_in_google_seed_profile(self.seed_root / "ai-8", "seat8.longyi@gmail.com")
        _create_ws_donor_profile(self.ws_root / "ws-11", include_ldb_creds=True)
        _create_ws_donor_profile(self.ws_root / "ws-12-empty", include_ldb_creds=False)

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def test_01_reproduce_v16_failures_and_verify_v17_step1_and_step2(self):
        """Proves v16 corrupts Preferences/Secure Preferences in Step ①/② while v17 preserves every credential byte."""
        # 1. Simulate unpatched v16 Step ① + Step ② (foreign ws-11 Secure Preferences overwrite + Preferences mutation)
        ram_v16 = self.tmp / "shm-v16"
        staged_16 = P17._stage_seed_profile_to_ramdisk(
            "P58", "ai-58", seed_root=self.seed_root, ramdisk_root=ram_v16
        )
        shutil.copy2(
            self.ws_root / "ws-11" / "Default" / "Secure Preferences",
            staged_16 / "Default" / "Secure Preferences",
        )
        res_16 = _simulate_chromium_myaccount_check(staged_16)
        self.assertFalse(res_16["ok"], "v16 must fail due to Preferences/Secure Preferences tampering")

        # 2. Run v17 Step ① + Step ② on both prompt-runner and watcher
        for mod, sid, prof, rroot in [
            (P17, "P58", "ai-58", self.ram_pr),
            (W17, "A8", "ai-8", self.ram_watcher),
        ]:
            staged_17 = mod._stage_seed_profile_to_ramdisk(
                sid, prof, seed_root=self.seed_root, ramdisk_root=rroot
            )
            mod._merge_ws_extension_layer(self.ws_root / "ws-11", staged_17)

            # Verify credential integrity helper
            integrity = mod.verify_profile_google_session_integrity(
                staged_17, reference_seed_dir=self.seed_root / prof
            )
            self.assertTrue(integrity["ok"], f"v17 integrity failed for {sid}: {integrity}")
            self.assertFalse(
                (staged_17 / "Default" / "Secure Preferences").exists(),
                "v17 must NOT inject foreign Secure Preferences from ws-11",
            )
            # Verify extension files ARE merged
            ext_manifest = (
                staged_17
                / "Default"
                / "Extensions"
                / "hnmpcagpplmpfojmgmnngilcnanddlhb"
                / "4.0.0_0"
                / "manifest.json"
            )
            self.assertTrue(ext_manifest.is_file(), "Windscribe extension files must be merged")
            # Verify Chromium PrefHashFilter super_mac & myaccount login state
            res_17 = _simulate_chromium_myaccount_check(staged_17)
            self.assertTrue(res_17["ok"], f"v17 myaccount check failed: {res_17}")

    def test_02_concurrent_watcher_and_prompt_runner_ramdisk_isolation(self):
        """Proves watcher and prompt-runner no longer wipe each other's staged profiles."""
        # 1. Default RAMDISK_PROFILES_DIR is isolated between watcher.py and prompt-runner.py
        self.assertIn("watcher-profiles", str(W17.RAMDISK_PROFILES_DIR))
        self.assertIn("prompt-runner-profiles", str(P17.RAMDISK_PROFILES_DIR))

        # 2. Even if both point to the SAME shared ramdisk directory, live PID lock in .staged_by_watcher protects staged profile
        shared_ram = self.tmp / "shm-shared-watcher-profiles"
        staged_pr = P17._stage_seed_profile_to_ramdisk(
            "P58", "ai-58", seed_root=self.seed_root, ramdisk_root=shared_ram
        )
        # Simulate another live process ID (parent PID or current init PID 1) holding ai-58
        marker = staged_pr / ".staged_by_watcher"
        marker.write_text(f"P58:ai-58:{os.getppid()}:1761110000\n", encoding="utf-8")

        # Now Watcher stages ai-8 in the same shared_ram
        staged_w = W17._stage_seed_profile_to_ramdisk(
            "A8", "ai-8", seed_root=self.seed_root, ramdisk_root=shared_ram
        )
        self.assertTrue(staged_pr.is_dir(), "ai-58 locked by live PID must NOT be wiped by Watcher")
        self.assertTrue(staged_w.is_dir(), "ai-8 must be staged cleanly")
        self.assertTrue(_simulate_chromium_myaccount_check(staged_pr)["ok"])
        self.assertTrue(_simulate_chromium_myaccount_check(staged_w)["ok"])

    def test_03_stage_a_harvest_and_bootstrap_never_touch_seat_google_profile(self):
        """Proves Stage A and Bootstrap open Chromium in an isolated temp dir, never on seat profile_dir."""
        for mod, sid in [(W17, "A8"), (P17, "P58")]:
            staged = mod._stage_seed_profile_to_ramdisk(
                sid, "ai-58", seed_root=self.seed_root, ramdisk_root=self.tmp / f"shm-{sid}"
            )
            # Merge an uninitialized ws profile so LevelDB direct harvest misses on staged
            mod._merge_ws_extension_layer(self.ws_root / "ws-12-empty", staged)

            launched_dirs = []

            class MockPage:
                def goto(self, url, **kw):
                    pass

                def evaluate(self, js):
                    return {
                        "serverCredentials": {"username": "u61154", "password": "p61154"},
                        "proxy": {"hosts": ["tok-123.whiskergalaxy.com"], "port": 443},
                    }

                def close(self):
                    pass

            class MockBrowser:
                pages = [MockPage()]

                def new_page(self):
                    return MockPage()

                def close(self):
                    pass

            class MockChromium:
                def launch_persistent_context(self, user_data_dir, **kw):
                    launched_dirs.append(Path(user_data_dir).resolve())
                    # Simulate Stage A Chromium mutating Preferences in whatever dir it opens!
                    pfile = Path(user_data_dir) / "Default" / "Preferences"
                    pfile.parent.mkdir(parents=True, exist_ok=True)
                    pfile.write_text('{"corrupted_by_stage_a":true}', encoding="utf-8")
                    return MockBrowser()

            class MockPlaywright:
                chromium = MockChromium()

            # Ensure _resolve_ws_profiles_dir points to an empty dir so Stage A falls back to launching browser
            old_env = os.environ.get("WATCHER_WS_PROFILES_DIR")
            os.environ["WATCHER_WS_PROFILES_DIR"] = str(self.tmp / "empty-ws")
            try:
                res = mod._stage_a_harvest_windscribe(
                    MockPlaywright(), sid, staged, 11080, timeout_ms=2000
                )
            finally:
                if old_env is None:
                    os.environ.pop("WATCHER_WS_PROFILES_DIR", None)
                else:
                    os.environ["WATCHER_WS_PROFILES_DIR"] = old_env

            self.assertTrue(res.get("ok"), f"Stage A harvest should succeed: {res}")
            self.assertEqual(len(launched_dirs), 1)
            self.assertNotEqual(
                launched_dirs[0],
                staged.resolve(),
                "Stage A browser MUST NOT open the seat's Google profile_dir directly!",
            )
            self.assertFalse(
                launched_dirs[0].exists(),
                "Stage A isolated temp dir must be cleaned up after harvest",
            )
            # And seat profile's Google credentials must remain 100% intact!
            chk = mod.verify_profile_google_session_integrity(
                staged, reference_seed_dir=self.seed_root / "ai-58"
            )
            self.assertTrue(chk["ok"], f"Seat profile credentials must be untouched after Stage A: {chk}")

    def test_04_seed_resolution_prefers_credential_bearing_profile(self):
        """Proves _resolve_seed_profile_dir skips empty skeleton dirs and selects local-profiles with Cookies/Local State."""
        skeleton_workshop = self.tmp / "workshop-profiles"
        (skeleton_workshop / "ai-58" / "Default").mkdir(parents=True, exist_ok=True)
        for mod in (W17, P17):
            old_sys = mod.SYSTEM_DIR
            old_prof = mod.PROFILES_DIR
            mod.SYSTEM_DIR = self.tmp
            mod.PROFILES_DIR = self.seed_root
            try:
                resolved = mod._resolve_seed_profile_dir("ai-58")
                self.assertEqual(resolved.resolve(), (self.seed_root / "ai-58").resolve())
            finally:
                mod.SYSTEM_DIR = old_sys
                mod.PROFILES_DIR = old_prof

    def test_05_google_companion_domains_routed_to_11090_and_probe_helper(self):
        """Proves all Google session companion domains route to 11090 SERVER_DIRECT and probe_myaccount_google_login_state works."""
        companion_hosts = [
            "accounts.google.com",
            "myaccount.google.com",
            "ogs.google.com",
            "play.google.com",
            "id.google.com",
            "consent.google.com",
            "clients1.google.com",
            "clients4.google.com",
            "clients6.google.com",
            "signaler-pa.clients6.google.com",
            "waa-pa.clients6.google.com",
            "apis.google.com",
            "www.googleapis.com",
            "oauth2.googleapis.com",
            "ssl.gstatic.com",
            "lh3.googleusercontent.com",
        ]
        for mod in (W17, P17):
            for h in companion_hosts:
                self.assertTrue(
                    mod._is_google_account_destination(h),
                    f"{h} must route via 11090 SERVER_DIRECT in {mod.__name__}",
                )
            for non_g in ("arena.ai", "auth.arena.ai", "api.ipify.org", "whiskergalaxy.com"):
                self.assertFalse(mod._is_google_account_destination(non_g))

            # Verify probe_myaccount_google_login_state on logged-in vs signed-out mock page
            class LoggedInMyAccountPage:
                url = "https://myaccount.google.com/?utm_source=sign_in_no_continue&pli=1"

                def goto(self, u, **kw):
                    pass

                def wait_for_timeout(self, ms):
                    pass

                def locator(self, sel):
                    class Loc:
                        def inner_text(self, **kw):
                            return "Welcome, Ippocrate Dimiceli\nippocrate284dimiceli@gmail.com\nManage your info, privacy, and security"

                    return Loc()

            probe_ok = mod.probe_myaccount_google_login_state(LoggedInMyAccountPage(), "P58")
            self.assertTrue(probe_ok["ok"])
            self.assertEqual(probe_ok["email"], "ippocrate284dimiceli@gmail.com")
            self.assertFalse(mod.is_arena_session_missing(LoggedInMyAccountPage(), "P58"))



    def test_06_shell_scripts_coordinator_pid_and_safe_ramdisk_cleanup(self):
        """Proves vnc-keep.sh checks watcher-coordinator.pid and start-watcher.sh clean_stale_watcher_ramdisk preserves live PID dirs."""
        import subprocess
        kit_dir = KIT_DIR
        vk_txt = (kit_dir / "vnc-keep.sh").read_text(encoding="utf-8")
        sw_txt = (kit_dir / "start-watcher.sh").read_text(encoding="utf-8")
        self.assertIn("watcher-coordinator.pid", vk_txt)
        self.assertIn("clean_stale_watcher_ramdisk", sw_txt)
        self.assertNotIn("rm -rf /dev/shm/watcher-profiles", sw_txt)
        # Verify sha256sums.txt passes sha256sum -c
        r = subprocess.run(["sha256sum", "-c", "sha256sums.txt"], cwd=str(kit_dir), capture_output=True, text=True)
        self.assertEqual(r.returncode, 0, f"sha256sums.txt failed: {r.stderr}")


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