"""
Centralised logger — Windows-safe (UTF-8, no special Unicode chars in console).
"""

import logging
import os
import sys
from logging.handlers import RotatingFileHandler

# ── Resolve log directory relative to this file (always correct on Windows) ──
_HERE    = os.path.dirname(os.path.abspath(__file__))          # app/utils/
_BACKEND = os.path.dirname(os.path.dirname(_HERE))             # backend/
_LOG_DIR = os.path.join(_BACKEND, "logs")
os.makedirs(_LOG_DIR, exist_ok=True)

# ── Format (ASCII only — no arrows that break cp1252 console) ────────────────
_fmt = logging.Formatter(
    "%(asctime)s | %(levelname)-8s | %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

log = logging.getLogger("gols")
log.setLevel(logging.DEBUG)

# ── Console handler — force UTF-8 on Windows ─────────────────────────────────
if sys.platform == "win32":
    # Reconfigure stdout/stderr to UTF-8 so special chars don't crash
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except AttributeError:
        pass  # older Python — ignore

_ch = logging.StreamHandler(sys.stdout)
_ch.setLevel(logging.INFO)
_ch.setFormatter(_fmt)
log.addHandler(_ch)

# ── File handler — always UTF-8 ───────────────────────────────────────────────
_fh = RotatingFileHandler(
    os.path.join(_LOG_DIR, "app.log"),
    maxBytes=5_000_000,
    backupCount=3,
    encoding="utf-8",
)
_fh.setLevel(logging.DEBUG)
_fh.setFormatter(_fmt)
log.addHandler(_fh)

# ── Errors-only file — quick place to see ONLY what failed ───────────────────
_err_fmt = logging.Formatter(
    "%(asctime)s | %(levelname)-8s | %(message)s\n"
    "    (logger: %(name)s, %(pathname)s:%(lineno)d)",
    datefmt="%Y-%m-%d %H:%M:%S",
)
_efh = RotatingFileHandler(
    os.path.join(_LOG_DIR, "errors.log"),
    maxBytes=2_000_000,
    backupCount=3,
    encoding="utf-8",
)
_efh.setLevel(logging.WARNING)   # only WARNING / ERROR / CRITICAL land here
_efh.setFormatter(_err_fmt)
log.addHandler(_efh)

log.info("Logger ready — full log: logs/app.log | failures only: logs/errors.log")
