"""Shared runtime paths for the installed Superpitch app."""

from __future__ import annotations

import os
from datetime import datetime
from pathlib import Path

APP_NAME = "Superpitch"
APP_SLUG = "superpitch"
APP_HOME_ENV = "SUPERPITCH_HOME"

PACKAGE_ROOT = Path(__file__).resolve().parent
SPECIALIST_DIR = PACKAGE_ROOT / "specialist"


def app_home() -> Path:
    override = os.environ.get(APP_HOME_ENV, "").strip()
    if override:
        return Path(override).expanduser()
    return Path.home() / f".{APP_SLUG}"


APP_HOME = app_home()
DATA_DIR = APP_HOME / "data"

HISTORY_FILE = DATA_DIR / "history.jsonl"
CONFIG_FILE = APP_HOME / "config.json"
SYNC_LOG_FILE = APP_HOME / "sync.log"


def ensure_app_dirs() -> None:
    for path in (APP_HOME, DATA_DIR):
        path.mkdir(parents=True, exist_ok=True)


def log_sync_error(context: str, exc: Exception) -> None:
    """Append a timestamped error to sync.log. Never raises."""
    try:
        ensure_app_dirs()
        with open(SYNC_LOG_FILE, "a") as f:
            f.write(f"{datetime.now().isoformat()} [{context}] {type(exc).__name__}: {exc}\n")
    except Exception:
        pass


def bootstrap_user_files() -> None:
    ensure_app_dirs()
