import asyncio
import os
from pathlib import Path
import subprocess

pid = subprocess.check_output(
    ["systemctl", "--user", "show", "device-gateway.service", "--property=MainPID", "--value"],
    text=True,
).strip()
allowed = {"GATEWAY_NODE_BIN", "PI_SDK_MODULE", "GATEWAY_PROJECTS_FILE", "GATEWAY_PORT"}
for pair in Path("/proc", pid, "environ").read_bytes().split(b"\0"):
    if b"=" not in pair:
        continue
    name, value = pair.split(b"=", 1)
    if name.decode() in allowed:
        os.environ[name.decode()] = value.decode()

from device_gateway.control.pi import PiAdapter
from device_gateway.control.projects import ProjectRegistry
from device_gateway.integrations.pi import PiSessionRegistry


async def main():
    projects = ProjectRegistry(os.environ.get(
        "GATEWAY_PROJECTS_FILE", "/home/lighthouse/.config/esp32-device-gateway/projects.json"))
    adapter = PiAdapter(projects, PiSessionRegistry())
    try:
        messages = await adapter.read_history("01a10c48-a5a7-74f8-bf7e-e816c6b1a203")
        print("Read-only selected Pi history:", len(messages), "messages; roles=",
              sorted({message["role"] for message in messages}))
    finally:
        await adapter.close()


asyncio.run(main())
