"""Watchdog: monitors daemon health and hard-restarts on crash or sustained high CPU."""

from __future__ import annotations

import os
import sys
import time
from pathlib import Path

META          = Path.home() / ".ai-interview.meta.json"
PID_FILE      = Path.home() / ".ai-interview.pid"
WATCHDOG_PID  = Path.home() / ".ai-interview-watchdog.pid"

CPU_THRESHOLD  = 80.0  # % — restart if daemon process exceeds this
CPU_STRIKE_MAX = 2     # consecutive readings above threshold before restart (~40s sustained)


def _read_pid() -> int | None:
    try:
        return int(PID_FILE.read_text().strip()) if PID_FILE.exists() else None
    except Exception:
        return None


def _is_running(pid: int) -> bool:
    try:
        os.kill(pid, 0)
        return True
    except (OSError, ProcessLookupError):
        return False


def _hard_restart() -> None:
    """SIGKILL the daemon then spawn ai-interview restart."""
    import signal
    import subprocess
    pid = _read_pid()
    if pid:
        try:
            os.kill(pid, signal.SIGKILL)
        except Exception:
            pass
    subprocess.Popen(
        [sys.executable, "-m", "ai_interview", "restart"],
        start_new_session=True,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        stdin=subprocess.DEVNULL,
    )


def run_watchdog() -> None:
    """Main watchdog loop. Runs until meta.json disappears (clean stop/idle shutdown)."""
    WATCHDOG_PID.write_text(str(os.getpid()))
    cpu_strikes = 0

    try:
        while True:
            time.sleep(20)

            # Clean stop or idle shutdown — exit without restarting
            if not META.exists():
                break

            pid = _read_pid()

            # Crash check: meta exists but process is gone
            if pid is None or not _is_running(pid):
                _hard_restart()
                cpu_strikes = 0
                time.sleep(15)  # give new daemon time to write PID file
                continue

            # High-CPU check: disabled — uncomment to re-enable
            # try:
            #     import psutil
            #     proc_cpu = psutil.Process(pid).cpu_percent(interval=2)
            #     if proc_cpu > CPU_THRESHOLD:
            #         cpu_strikes += 1
            #         if cpu_strikes >= CPU_STRIKE_MAX:
            #             _hard_restart()
            #             cpu_strikes = 0
            #             time.sleep(15)
            #             continue
            #     else:
            #         cpu_strikes = 0
            # except Exception:
            #     cpu_strikes = 0

    finally:
        WATCHDOG_PID.unlink(missing_ok=True)
