#!/opt/agent/hindsight/bin/python3
"""Run pg0 and Hindsight API in one supervisor-owned foreground process."""

from __future__ import annotations

import os
import signal
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

from pg0 import Pg0, Pg0AlreadyRunningError


def main() -> int:
    port = int(os.environ["HINDSIGHT_PORT"])
    state = Path("/home/agent/.hindsight")
    pg = Pg0(
        name="agent-memory",
        username="hindsight",
        password="hindsight",
        database="hindsight",
        data_dir=str(state / "pg0"),
        config={
            "shared_buffers": "64MB",
            "work_mem": "4MB",
            "maintenance_work_mem": "32MB",
            "max_connections": "32",
        },
    )
    try:
        try:
            info = pg.start()
        except Pg0AlreadyRunningError:
            info = pg.info()
        env = os.environ.copy()
        env.update(
            {
                "HOME": str(state),
                "HINDSIGHT_API_DATABASE_URL": info.uri,
                "HINDSIGHT_API_HOST": "127.0.0.1",
                "HINDSIGHT_API_PORT": str(port),
            }
        )
        api = subprocess.Popen(
            ["/opt/agent/hindsight/bin/hindsight-api", "--host", "127.0.0.1", "--port", str(port)],
            env=env,
        )

        def stop(signum: int, _frame: object) -> None:
            if api.poll() is None:
                api.send_signal(signum)

        signal.signal(signal.SIGTERM, stop)
        signal.signal(signal.SIGINT, stop)

        health = f"http://127.0.0.1:{port}/health"
        for _ in range(180):
            if api.poll() is not None:
                return api.returncode or 1
            try:
                with urllib.request.urlopen(health, timeout=1) as response:
                    if response.status < 400:
                        break
            except OSError:
                pass
            time.sleep(1)
        else:
            api.terminate()
            return 1

        profile = Path("/config/hindsight.json")
        if profile.is_file():
            subprocess.run(
                ["/opt/agent/bin/apply-memory-profile.py", str(profile)],
                env=env,
                check=False,
            )
        return api.wait()
    finally:
        pg.stop()


if __name__ == "__main__":
    sys.exit(main())
