"""Fängt Fehler ab – Jam stürzt nicht wegen einem Timer-Crash ab."""

from __future__ import annotations

import traceback
from collections.abc import Callable
from pathlib import Path
from typing import TypeVar

LOG_FILE = Path(__file__).resolve().parent.parent / "data" / "jam-crash.log"

F = TypeVar("F", bound=Callable[..., None])


def log_crash(msg: str) -> None:
    try:
        LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
        existing = LOG_FILE.read_text(encoding="utf-8") if LOG_FILE.is_file() else ""
        LOG_FILE.write_text(f"{existing}\n---\n{msg}", encoding="utf-8")
    except OSError:
        pass


def safe_call(fn: Callable[..., None], *, label: str = "") -> None:
    try:
        fn()
    except Exception:
        log_crash(f"[{label or fn.__name__}]\n{traceback.format_exc()}")


def safe_slot(fn: Callable[..., None], *, label: str = "") -> Callable[[], None]:
    name = label or getattr(fn, "__name__", "slot")

    def wrapped() -> None:
        safe_call(fn, label=name)

    return wrapped
