#!/usr/bin/env python3
"""
Cross-platform heartbeat wrapper.
Wraps monitor_callback.sh / .ps1 with a unified CLI interface.

Usage:
  python skill_monitor/send_heartbeat.py --status started --event heartbeat --phase load --summary "loaded"
  python skill_monitor/send_heartbeat.py --status success --phase finish --summary "done" --files data/result.txt --final
"""
import argparse
import os
import platform
import random
import subprocess
import sys
import time
from datetime import datetime
from pathlib import Path


DEFAULT_SESSION_TTL_SECONDS = 8 * 60 * 60
BOM_CHAR = "\ufeff"


def normalize_runtime_value(value: str) -> str:
    return str(value or "").replace(BOM_CHAR, "").strip()


def read_runtime_value(file_path: Path) -> str:
    try:
        return normalize_runtime_value(file_path.read_text(encoding="utf-8-sig"))
    except OSError:
        return ""


def write_runtime_value(file_path: Path, value: str) -> None:
    try:
        file_path.parent.mkdir(parents=True, exist_ok=True)
        file_path.write_text(normalize_runtime_value(value), encoding="utf-8")
    except OSError:
        pass


def remove_runtime_value(file_path: Path) -> None:
    try:
        file_path.unlink(missing_ok=True)
    except OSError:
        pass


def truthy(value: str) -> bool:
    return str(value or "").strip().lower() in {"1", "true", "yes", "on"}


def session_ttl_seconds(env: dict[str, str]) -> int:
    raw_value = (
        env.get("MONITOR_SESSION_TTL_SECONDS", "").strip()
        or env.get("SESSION_TTL_SECONDS", "").strip()
    )
    try:
        value = int(raw_value) if raw_value else DEFAULT_SESSION_TTL_SECONDS
    except ValueError:
        return DEFAULT_SESSION_TTL_SECONDS
    return value if value > 0 else DEFAULT_SESSION_TTL_SECONDS


def read_fresh_session_value(file_path: Path, env: dict[str, str]) -> str:
    if truthy(env.get("MONITOR_RESET_SESSION", "")) or truthy(env.get("JOYCLAW_RESET_SESSION", "")):
        remove_runtime_value(file_path)
        return ""
    try:
        stat_result = file_path.stat()
    except OSError:
        return ""
    ttl_seconds = session_ttl_seconds(env)
    if time.time() - stat_result.st_mtime > ttl_seconds:
        remove_runtime_value(file_path)
        return ""
    return read_runtime_value(file_path)


def main():
    parser = argparse.ArgumentParser(description="Cross-platform heartbeat sender")
    parser.add_argument("--status", required=True, choices=["started", "success", "failed"])
    parser.add_argument(
        "--event",
        default="heartbeat",
        help="EVENT_TYPE: skill_loaded, heartbeat, phase_started, skill_success, skill_failed",
    )
    parser.add_argument("--phase", required=True)
    parser.add_argument("--summary", required=True)
    parser.add_argument("--error", default="", help="ERROR_MESSAGE, required when status=failed")
    parser.add_argument("--extra", nargs="*", default=[], help="Extra env vars, format KEY=VALUE")
    parser.add_argument("--files", nargs="*", default=[], help="Optional result file paths")
    parser.add_argument("--final", action="store_true", help="Terminal callback")
    args = parser.parse_args()

    script_dir = Path(__file__).resolve().parent
    skill_dir = script_dir.parent
    runtime_dir = skill_dir / ".runtime"
    current_run_file = runtime_dir / "current_run_id"
    current_session_file = runtime_dir / "current_session_id"

    env = os.environ.copy()
    env["SKILL_DIR"] = str(skill_dir)

    run_id = normalize_runtime_value(env.get("RUN_ID", "")) or read_runtime_value(current_run_file)
    if not run_id:
        now = datetime.now().strftime("%Y%m%d%H%M%S")
        suffix = "final" if args.final else str(random.randint(0, 9999))
        run_id = f"joyclaw-run-{now}-{suffix}"
    env["RUN_ID"] = run_id

    session_id = normalize_runtime_value(env.get("SESSION_ID", "")) or read_fresh_session_value(current_session_file, env)
    if not session_id:
        now = datetime.now().strftime("%Y%m%d%H%M%S")
        session_id = f"joyclaw-session-{now}-{random.randint(0, 9999)}"
    env["SESSION_ID"] = session_id
    env["TASK_ID"] = normalize_runtime_value(env.get("TASK_ID", "")) or session_id

    env["STATUS"] = args.status
    env["EVENT_TYPE"] = args.event
    env["PHASE"] = args.phase
    env["SUMMARY"] = args.summary
    if args.error:
        env["ERROR_MESSAGE"] = args.error

    for item in args.extra:
        if "=" in item:
            key, value = item.split("=", 1)
            env[key] = value

    if args.files:
        resolved = []
        for file_name in args.files:
            file_path = Path(file_name)
            if not file_path.is_absolute():
                file_path = Path.cwd() / file_path
            resolved.append(str(file_path))
        env["RESULT_FILES"] = "\n".join(resolved)

    if platform.system() == "Windows":
        script_path = script_dir / "monitor_callback.ps1"
        command = ["powershell.exe", "-ExecutionPolicy", "Bypass", "-File", str(script_path)]
    else:
        script_path = script_dir / "monitor_callback.sh"
        command = ["bash", str(script_path)]

    if args.status == "started":
        write_runtime_value(current_run_file, run_id)
        write_runtime_value(current_session_file, session_id)

    result = subprocess.run(command, env=env, cwd=str(skill_dir), capture_output=False)
    if args.final or args.status in {"success", "failed"}:
        remove_runtime_value(current_run_file)
    sys.exit(result.returncode)


if __name__ == "__main__":
    main()
