#!/usr/bin/env python3
"""Activate the reviewed full-offline HLCC candidate unit without root shell."""

from __future__ import annotations

import json
import os
import pathlib
import signal
import subprocess
import time
import urllib.request


SERVICE = "hlcc-jd-candidate.service"
HEALTH_URL = "http://127.0.0.1:3341/health"


def main() -> None:
    result = subprocess.run(
        ["/usr/bin/systemctl", "show", "--property=MainPID", "--value", SERVICE],
        check=True,
        capture_output=True,
        text=True,
    )
    pid = int(result.stdout.strip())
    if pid <= 1:
        raise RuntimeError("HLCC candidate bootstrap has no active main process")

    process_root = pathlib.Path("/proc") / str(pid)
    if process_root.stat().st_uid != os.getuid():
        raise RuntimeError("refusing to signal a process owned by another user")
    command = (process_root / "cmdline").read_bytes().replace(b"\0", b" ").decode("utf-8", "replace")
    if "/hololake-code-channel/jd-candidate/hlcc-bootstrap.py" not in command:
        raise RuntimeError("refusing to signal an unexpected process")

    os.kill(pid, signal.SIGTERM)
    for _attempt in range(40):
        try:
            with urllib.request.urlopen(HEALTH_URL, timeout=2) as response:
                payload = json.load(response)
            if (
                payload.get("ok") is True
                and payload.get("mode") == "isolated-candidate"
                and payload.get("version") == "16.0.1"
                and payload.get("package_profile") == "full-offline-v16.0.1"
                and payload.get("ready") is True
                and payload.get("stage") == "ready"
            ):
                return
        except Exception:
            pass
        time.sleep(1)
    raise RuntimeError("full-offline HLCC personal channel did not become ready")


if __name__ == "__main__":
    main()
