#!/usr/bin/env python3
from __future__ import annotations

import atexit
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from types import TracebackType
from typing import Any


SCRIPT_DIR = Path(__file__).resolve().parent
SKILL_DIR = SCRIPT_DIR.parent
INTERNAL_SCRIPT_NAMES = {
    "bootstrap.py",
    "monitor_guard.py",
    "send_heartbeat.py",
    "run_skill_with_monitor.py",
    "monitor_config.py",
    "get_sso_token.py",
    "get_sso_token_browser.py",
    "browser_login.py",
    "get_me_token.py",
}

_state: dict[str, Any] = {
    "started": False,
    "failed": False,
    "error": "",
    "thread": None,
    "stop": None,
    "start_ts": 0.0,
}


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


def _load_monitor_config() -> dict[str, Any]:
    try:
        sys.path.insert(0, str(SCRIPT_DIR))
        from monitor_config import load_config  # type: ignore

        return load_config(SKILL_DIR)
    except Exception:
        return {}
    finally:
        try:
            sys.path.remove(str(SCRIPT_DIR))
        except ValueError:
            pass


def _current_script_path() -> Path:
    try:
        return Path(sys.argv[0]).resolve()
    except OSError:
        return Path(sys.argv[0])


def _should_skip_autoload() -> bool:
    if not _truthy(os.environ.get("MONITOR_ENABLED", "1")):
        return True
    if os.environ.get("SKILL_MONITOR_GUARD_ACTIVE") == "1":
        return True
    script_path = _current_script_path()
    if script_path.name in INTERNAL_SCRIPT_NAMES:
        return True
    try:
        if script_path.is_relative_to(SCRIPT_DIR):
            return True
    except ValueError:
        pass
    return False


def _send_heartbeat(
    *,
    status: str,
    event: str,
    phase: str,
    summary: str,
    error: str = "",
    final: bool = False,
    heartbeat_seq: int = 0,
    elapsed_seconds: int = 0,
) -> None:
    command = [
        sys.executable,
        str(SCRIPT_DIR / "send_heartbeat.py"),
        "--status",
        status,
        "--event",
        event,
        "--phase",
        phase,
        "--summary",
        summary,
    ]
    if error:
        command.extend(["--error", error])
    if final:
        command.append("--final")

    env = os.environ.copy()
    env["SKILL_DIR"] = str(SKILL_DIR)
    env["HEARTBEAT_SEQ"] = str(heartbeat_seq)
    env["ELAPSED_SECONDS"] = str(elapsed_seconds)
    try:
        subprocess.run(command, cwd=str(SKILL_DIR), env=env, timeout=60, check=False)
    except Exception:
        pass


def _heartbeat_loop(stop_event: threading.Event, interval: int) -> None:
    seq = 1
    while not stop_event.wait(interval):
        elapsed = int(time.time() - float(_state.get("start_ts") or time.time()))
        _send_heartbeat(
            status="started",
            event="heartbeat",
            phase="autoload",
            summary=f"Skill自动监控运行中 (seq={seq}, elapsed={elapsed}s)",
            heartbeat_seq=seq,
            elapsed_seconds=elapsed,
        )
        seq += 1


def _mark_failed(error: str) -> None:
    _state["failed"] = True
    _state["error"] = error[:1000]


def _install_exit_hooks() -> None:
    original_excepthook = sys.excepthook
    original_exit = sys.exit

    def guarded_excepthook(
        exc_type: type[BaseException],
        exc_value: BaseException,
        traceback: TracebackType | None,
    ) -> None:
        _mark_failed(f"{exc_type.__name__}: {exc_value}")
        original_excepthook(exc_type, exc_value, traceback)

    def guarded_exit(code: object = 0) -> None:
        exit_code = 0
        if isinstance(code, int):
            exit_code = code
        elif code not in (None, ""):
            exit_code = 1
        if exit_code != 0:
            _mark_failed(f"SystemExit: {code}")
        original_exit(code)

    sys.excepthook = guarded_excepthook
    sys.exit = guarded_exit


def _finalize() -> None:
    if not _state.get("started"):
        return
    stop_event = _state.get("stop")
    if isinstance(stop_event, threading.Event):
        stop_event.set()
    thread = _state.get("thread")
    if isinstance(thread, threading.Thread):
        thread.join(timeout=5)

    failed = bool(_state.get("failed"))
    _send_heartbeat(
        status="failed" if failed else "success",
        event="skill_failed" if failed else "skill_success",
        phase="finish",
        summary="Skill自动监控捕获失败" if failed else "Skill自动监控捕获成功",
        error=str(_state.get("error") or "") if failed else "",
        final=True,
    )


def autoload() -> None:
    if _should_skip_autoload():
        return

    os.environ["SKILL_MONITOR_GUARD_ACTIVE"] = "1"
    _state["started"] = True
    _state["start_ts"] = time.time()
    _install_exit_hooks()

    _send_heartbeat(
        status="started",
        event="skill_autoloaded",
        phase="autoload",
        summary="Skill运行端已自动加载心跳监控",
    )

    config = _load_monitor_config()
    try:
        interval = max(5, int(config.get("heartbeatIntervalSec", 15)))
    except (TypeError, ValueError):
        interval = 15
    stop_event = threading.Event()
    thread = threading.Thread(
        target=_heartbeat_loop,
        args=(stop_event, interval),
        name="skill-monitor-autoload",
        daemon=True,
    )
    _state["stop"] = stop_event
    _state["thread"] = thread
    thread.start()
    atexit.register(_finalize)
