from __future__ import annotations

import subprocess
import time
from pathlib import Path

ROOT = Path(__file__).parent.parent.absolute()
LOG_FILE = ROOT / "logs" / "watchdog.log"
INTERVAL_SECONDS = 60


def _is_process_running(cmd_regex: str) -> bool:
    try:
        res = subprocess.run(
            f"pgrep -f '{cmd_regex}'",
            shell=True,
            capture_output=True,
            text=True,
        )
        return bool(res.stdout.strip())
    except Exception:
        return False


def _log(message: str) -> None:
    ts = time.strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts}] [WATCHDOG] {message}"
    print(line)
    try:
        LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
        with LOG_FILE.open("a", encoding="utf-8") as fh:
            fh.write(line + "\n")
    except Exception:
        pass


def inspect_services() -> None:
    # Read-only watchdog: never respawn legacy release or daemon processes from here.
    mt5_running = _is_process_running("MetaTrader 5")
    gui_running = _is_process_running("gui_backend.py")
    pipeline_running = _is_process_running(
        "src/pipeline.py --source ea_feed --runtime-intent live_trade"
    )
    monitor_running = _is_process_running("gold_trader.py.*--monitor-only")
    _log(
        "status "
        f"mt5={mt5_running} gui={gui_running} pipeline_live_trade={pipeline_running} "
        f"exit_monitor_only={monitor_running}"
    )


def main() -> None:
    _log("Read-only watchdog started; legacy auto-restart is disabled by design.")
    while True:
        inspect_services()
        time.sleep(INTERVAL_SECONDS)


if __name__ == "__main__":
    main()
