#!/usr/bin/env python3
"""Real built CLI proof. Usage: driver.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIR.
Build each apps/server with `vp run build:bundle` using test-stage public config.
Requires a disposable Linux user t3proof31906 with linger and a running user manager.
No credentials, network login, mocks, or application database seed are used.
"""
import os, sys, pathlib, subprocess, shlex, json, datetime, pwd
base, head, output = map(pathlib.Path, sys.argv[1:])
run = output / datetime.datetime.now(datetime.timezone.utc).strftime("run-%Y%m%d-%H%M%S")
run.mkdir(parents=True)
node = subprocess.check_output(["which", "node"], text=True).strip()
uid = subprocess.check_output(["id", "-u", "t3proof31906"], text=True).strip()
results = {}
for side, checkout in [("before", base), ("after", head)]:
    cwd = run / side
    cwd.mkdir()
    subprocess.run(["chmod", "777", str(cwd)], check=True)
    (cwd / "homes").mkdir(mode=0o777)
    (cwd / "homes").chmod(0o777)
    entry = checkout / "apps/server/dist/bin.mjs"
    shim = cwd / "launcher's $t3"
    shim.write_text("#!/bin/sh\nexec " + shlex.quote(node) + " " + shlex.quote(str(entry)) + ' "$@"\n')
    shim.chmod(0o755)
    env = dict(os.environ, T3CODE_DEV_SEED="0", NO_COLOR="1")
    env.pop("T3CODE_HOME", None)
    env.pop("T3CODE_CLI_PATH", None)
    text = [side.upper() + " | Linux x86_64 | real built CLI", "Fresh isolated homes; no account signed in.", ""]
    calls = [
      ("connect status", "homes/t3-home-A", False, False),
      ("connect publish", "homes/t3-home-A", False, False),
      ("service status", "homes/t3-home-B", True, False),
      ("connect status", "homes/home A's $literal", False, True),
      ("connect publish", "homes/home A's $literal", False, True),
      ("service status", "homes/service B's $literal", True, True),
    ]
    records = []
    for command, home, fresh_user, custom_launcher in calls:
        args = command.split() + ["--base-dir", home, "--log-level", "none"]
        child_env = dict(env)
        display = "t3"
        if custom_launcher:
            child_env["T3CODE_CLI_PATH"] = "./launcher's $t3"
            display = shlex.quote(child_env["T3CODE_CLI_PATH"])
        actual = ["./launcher's $t3"] + args if custom_launcher else [node, str(entry)] + args
        if fresh_user:
            child_env["HOME"] = pwd.getpwnam("t3proof31906").pw_dir
            child_env["XDG_RUNTIME_DIR"] = "/run/user/" + uid
            child_env["DBUS_SESSION_BUS_ADDRESS"] = "unix:path=/run/user/" + uid + "/bus"
            actual = ["sudo", "-n", "-u", "t3proof31906", "env"] + [k+"="+v for k,v in child_env.items()] + actual
        text += [("[fresh Linux user; systemd user manager running]" if fresh_user else "[isolated home; no credentials]")]
        text += ["$ " + display + " " + command + " --base-dir " + shlex.quote(home)]
        proc = subprocess.run(actual, cwd=cwd, env=child_env, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        text += [proc.stdout.rstrip(), "exit: " + str(proc.returncode), ""]
        records.append(dict(command=command, home=home, customLauncher=custom_launcher, exit=proc.returncode, output=proc.stdout))
    (run / (side+".txt")).write_text("\n".join(text))
    results[side] = records
(run / "commands.json").write_text(json.dumps(results, indent=2))
print(run)
