#!/usr/bin/env python3
"""좀비 태스크 감지 워치독 (orphan-watchdog.py)

running 상태('started' 또는 'running')이면서 ZOMBIE_THRESHOLD_MINUTES 이상
경과한 태스크를 감지해 JSON으로 stdout에 출력한다.

종료 코드:
    0 - 좀비 없음
    1 - 좀비 1개 이상 발견
"""

import json
import os
import sys
from datetime import datetime
from pathlib import Path

WORKSPACE = Path(os.environ.get("WORKSPACE_ROOT", "/home/jay/workspace"))
TIMER_FILE = WORKSPACE / "memory" / "task-timers.json"
ZOMBIE_THRESHOLD_MINUTES = 60


def detect_zombies(
    timer_file: Path = TIMER_FILE,
    threshold_minutes: int = ZOMBIE_THRESHOLD_MINUTES,
) -> dict:
    """running 상태이고 threshold_minutes 이상 경과한 태스크를 찾는다.

    Args:
        timer_file: task-timers.json 경로
        threshold_minutes: 좀비로 판정하는 최소 경과 시간(분)

    Returns:
        {
            "zombies": [...],
            "checked_at": "ISO8601",
            "total": int
        }
    """
    now = datetime.now()
    result: dict = {
        "zombies": [],
        "checked_at": now.strftime("%Y-%m-%dT%H:%M:%S"),
        "total": 0,
    }

    if not timer_file.exists():
        return result

    with open(timer_file, "r", encoding="utf-8") as f:
        data = json.load(f)

    tasks: dict = data.get("tasks", {})
    for task_id, task in tasks.items():
        status = task.get("status", "")
        if status not in ("started", "running"):
            continue

        start_time_str: str = task.get("start_time", "")
        if not start_time_str:
            continue

        try:
            start_time = datetime.fromisoformat(start_time_str)
        except ValueError:
            continue

        elapsed = (now - start_time).total_seconds() / 60
        if elapsed >= threshold_minutes:
            result["zombies"].append(
                {
                    "task_id": task_id,
                    "start_time": start_time_str,
                    "elapsed_minutes": round(elapsed),
                    "team_id": task.get("team_id", "unknown"),
                }
            )

    result["total"] = len(result["zombies"])
    return result


def main() -> int:
    result = detect_zombies()
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result["total"] == 0 else 1


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