"""Shared boot-log module — single source of truth for logging path and function.

Replaces the _bl() + _DATA_DIR + _LOG_DIR + _LOG_PATH pattern
that was duplicated across 7 modules.
"""

import os
import time


def _compute_log_path() -> str:
    """Compute log file path from CORTEX_DATA_DIR env var."""
    data_dir = os.environ.get("CORTEX_DATA_DIR")
    if data_dir:
        return os.path.join(data_dir, "cortex_db", "neo-cortex.log")
    return os.path.join(os.getcwd(), "neo-cortex.log")


LOG_PATH = _compute_log_path()

MAX_LOG_SIZE = 10 * 1024 * 1024  # 10 MB


def _rotate_if_needed() -> None:
    """Rotate log file if it exceeds MAX_LOG_SIZE."""
    try:
        if os.path.exists(LOG_PATH) and os.path.getsize(LOG_PATH) > MAX_LOG_SIZE:
            backup = LOG_PATH + ".1"
            if os.path.exists(backup):
                os.remove(backup)
            os.rename(LOG_PATH, backup)
    except Exception:
        pass


def boot_log(tag: str, msg: str) -> None:
    """Write timestamped line to LOG_PATH. Exception-safe."""
    try:
        os.makedirs(os.path.dirname(LOG_PATH) or ".", exist_ok=True)
        with open(LOG_PATH, "a", encoding="utf-8") as f:
            f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} [{tag}] {msg}\n")
            f.flush()
    except Exception:
        pass


__all__ = ["LOG_PATH", "boot_log", "MAX_LOG_SIZE"]

# Rotate on import (boot)
_rotate_if_needed()
