"""Run from a current-main checkout containing rescan-installed-gh.e2e.ts.
Requires vp, zsh, and gh. Set RESCAN_ZSH to a separately extracted zsh if needed.
Creates an isolated PATH and zsh profile; never changes the account's profiles.
"""
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile

checkout = pathlib.Path.cwd()
root = pathlib.Path(tempfile.mkdtemp(prefix="rescan-proof-"))
initial = root / "initial-bin"
initial.mkdir()
(root / "installed-bin").mkdir()
profiles = root / "profiles"
profiles.mkdir()
real_gh = shutil.which("gh")
zsh = os.environ.get("RESCAN_ZSH") or shutil.which("zsh")
if not real_gh or not zsh:
    raise SystemExit("Install gh and zsh before running this driver")
for directory in os.environ["PATH"].split(os.pathsep):
    source = pathlib.Path(directory)
    if not source.is_dir():
        continue
    for executable in source.iterdir():
        target = initial / executable.name
        try:
            if executable.name != "gh" and not target.exists() and not target.is_symlink() and executable.is_file() and os.access(executable, os.X_OK):
                target.symlink_to(executable)
        except PermissionError:
            pass
# The scenario writes this fragment after the app is running; each side's fresh
# T3 home removes the previous side's fragment before its server starts.
fragment = checkout / ".t3/scenarios/login-profile"
(profiles / ".zshenv").write_text(f'export PATH="{initial}"\n')
(profiles / ".zprofile").write_text(f'if [ -f "{fragment}" ]; then\n source "{fragment}"\nfi\n')
env = dict(os.environ, PATH=str(initial), SHELL=zsh, ZDOTDIR=str(profiles), T3CODE_DEV_SEED="0", RESCAN_FIXTURE_ROOT=str(root), RESCAN_REAL_GH=real_gh)
env.pop("GH_TOKEN", None)
env.pop("GITHUB_TOKEN", None)
config = checkout / "scripts/e2e.config.ts"
original = config.read_text()
configured = original.replace("executable: resolved.node,", 'executable: resolved.node,\n          inheritEnv: ["SHELL", "ZDOTDIR"],') if 'inheritEnv: ["SHELL", "ZDOTDIR"]' not in original else original
configured = configured.replace('  ],\n  // One server', '  ].filter((target) => target.name === "web"),\n  // One server')
config.write_text(configured)
command = ["vp", "run", "scenarios:prove", "scripts/scenarios/rescan-installed-gh.e2e.ts", "--base", "7462f234e89027943cf0d1a73d3ae1f36571d4e3", "--head", "8856e3b11ca7cd3f412542887e7a392dbc3ea393"]
try:
    result = subprocess.call(command + sys.argv[1:], env=env)
finally:
    config.write_text(original)
raise SystemExit(result)
