"""Tests for the shared boot-log module."""

import os
from unittest.mock import patch

import pytest

from neo_cortex._log import _compute_log_path, boot_log, _rotate_if_needed, MAX_LOG_SIZE


class TestBootLog:
    def test_log_path_from_env(self, monkeypatch):
        monkeypatch.setenv("CORTEX_DATA_DIR", "/tmp/test-cortex")
        assert _compute_log_path() == "/tmp/test-cortex/cortex_db/neo-cortex.log"

    def test_log_path_default(self, monkeypatch):
        monkeypatch.delenv("CORTEX_DATA_DIR", raising=False)
        assert _compute_log_path() == os.path.join(os.getcwd(), "neo-cortex.log")

    def test_bl_writes_to_file(self, tmp_path):
        log_file = tmp_path / "neo-cortex.log"
        with patch("neo_cortex._log.LOG_PATH", str(log_file)):
            boot_log("TEST", "hello")
        content = log_file.read_text()
        assert "[TEST] hello" in content

    def test_bl_creates_dir(self, tmp_path):
        log_file = tmp_path / "subdir" / "neo-cortex.log"
        with patch("neo_cortex._log.LOG_PATH", str(log_file)):
            boot_log("TEST", "create dir")
        assert log_file.exists()

    def test_bl_exception_safe(self):
        with patch("neo_cortex._log.LOG_PATH", "/proc/nonexistent/neo-cortex.log"):
            boot_log("TEST", "unwritable")  # must not raise


class TestLogRotation:
    def test_log_rotation_at_size(self, tmp_path):
        log_file = tmp_path / "neo-cortex.log"
        log_file.write_bytes(b"x" * (MAX_LOG_SIZE + 1))
        with patch("neo_cortex._log.LOG_PATH", str(log_file)):
            _rotate_if_needed()
        backup = tmp_path / "neo-cortex.log.1"
        assert backup.exists()
        assert not log_file.exists()

    def test_log_keeps_backup(self, tmp_path):
        log_file = tmp_path / "neo-cortex.log"
        log_file.write_bytes(b"x" * (MAX_LOG_SIZE + 1))
        with patch("neo_cortex._log.LOG_PATH", str(log_file)):
            _rotate_if_needed()
        backup = tmp_path / "neo-cortex.log.1"
        assert backup.stat().st_size == MAX_LOG_SIZE + 1
