"""Read-only final comparison; does not restart services or change policy."""
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
from datetime import datetime, timezone

ROOT = Path(__file__).resolve().parent
PROJECT = "ct-mroi-dual-20261013-r01"


def run(args, timeout=15):
    return subprocess.run(args, check=True, capture_output=True, text=True,
                          timeout=timeout).stdout


before = json.loads((ROOT / "private/operational-before.json").read_text())
names = list(before["containers"]) + ["/contextra-ai-gateway-1"]
rows = json.loads(run(["docker", "inspect", *names]))
containers = {}
for row in rows:
    expected = before["containers"].get(row["Name"])
    current = {"id": row["Id"], "image": row["Image"],
               "started": row["State"]["StartedAt"]}
    containers[row["Name"]] = {
        "state": row["State"]["Status"],
        "baseline_unchanged": current == expected if expected else None,
        "image": row["Image"],
    }
files = {path: hashlib.sha256(Path(path).read_bytes()).hexdigest() == sha
         for path, sha in before["files"].items()}
code = '''
import json, os, urllib.request
from pathlib import Path
token = Path(os.environ["CONTEXTRA_CONTROL_TOKEN_FILE"]).read_text().strip()
request = urllib.request.Request(
    "http://127.0.0.1:5000/internal/secure-control/runtime-status",
    headers={"Authorization": "Bearer " + token})
with urllib.request.urlopen(request, timeout=5) as response:
    state = json.load(response)
print(json.dumps({"status": state.get("status"), "streamCounts": state.get("streamCounts")}))
'''
runtime = json.loads(run(["docker", "exec", "contextra-analytics-1",
                          "python3", "-B", "-c", code]))
ids = run(["docker", "ps", "-aq", "--filter",
           "label=com.docker.compose.project=" + PROJECT]).split()
test = json.loads(run(["docker", "inspect", *ids])) if ids else []
trial = {r["Name"]: {"state": r["State"]["Status"],
                     "exit_code": r["State"]["ExitCode"]} for r in test}
leftovers = run(["docker", "ps", "--filter", "name=ct-mroi-", "--format", "{{.Names}}"]).split()
out = {
    "at": datetime.now(timezone.utc).isoformat(),
    "operational_containers": containers,
    "operational_file_hashes_unchanged": files,
    "operational_runtime": runtime,
    "policy_preserved": before["policy"] if all(files.values()) else None,
    "trial_containers": trial,
    "running_trial_containers": leftovers,
    "root_free_bytes": shutil.disk_usage("/").free,
    "data_free_bytes": shutil.disk_usage("/data").free,
}
out["preserved"] = (
    all(files.values())
    and all(c["baseline_unchanged"] is not False for c in containers.values())
    and all(c["state"] == "running" for c in containers.values())
    and runtime["streamCounts"] == {"running": 0, "starting": 0, "stopped": 36, "error": 0, "total": 36}
    and len(trial) == 4 and all(c["state"] == "exited" and c["exit_code"] == 0 for c in trial.values())
    and not leftovers and out["root_free_bytes"] >= 15 * 1024**3
)
(ROOT / "operational-preservation.json").write_text(json.dumps(out, indent=2) + "\n")
print(json.dumps(out, indent=2))
raise SystemExit(0 if out["preserved"] else 1)
