"""Durable first-run / setup log writer (backend runtime side).

Mirrors the Swift ``SetupLog`` (PythonBackend.swift) and ``backend/bootstrap.py``
so that every phase of installation/onboarding lands in a single, user-readable
file: ``~/.mugi/logs/setup.log``.

The recommended-setup wizard (model download, MLX install, server start) drives
backend routes that historically returned ``str(exc)`` to the UI but logged
*nothing* server-side. On a clean machine a transient remote 500 (HuggingFace,
PyPI) left the user staring at "HTTP Error 500: Internal Server Error" with no
trace to diagnose. These helpers close that gap: route handlers tee their
failures (with full traceback) here so a stuck first-run is recoverable.
"""

from __future__ import annotations

import os
import traceback
from datetime import datetime, timezone

from persistence import MUGI_LOGS_DIR

SETUP_LOG_PATH = os.path.join(MUGI_LOGS_DIR, "setup.log")


def setup_log_write(text: str) -> None:
    """Append a timestamped line to ``~/.mugi/logs/setup.log`` (best-effort)."""
    try:
        os.makedirs(MUGI_LOGS_DIR, exist_ok=True)
        stamp = datetime.now(timezone.utc).isoformat()
        with open(SETUP_LOG_PATH, "a", encoding="utf-8") as f:
            f.write(f"[{stamp}] {text}\n")
    except OSError:
        # Logging must never break setup; swallow filesystem errors.
        pass


def setup_log_exception(context: str, exc: BaseException) -> None:
    """Record a failed setup step with its exception type, message, and traceback."""
    setup_log_write(f"FAILED: {context}: {type(exc).__name__}: {exc}")
    try:
        tb = "".join(
            traceback.format_exception(type(exc), exc, exc.__traceback__)
        ).strip()
    except Exception:
        tb = ""
    if tb:
        setup_log_write("Traceback:\n" + tb)
