"""
Tests for SpeechBridge Logging System
======================================

Tests for rotating log system with overwrite functionality
"""

import pytest
import sys
import tempfile
import shutil
from pathlib import Path
import logging

sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from speechbridge.utils.logging import SpeechBridgeLogger, setup_logging


class TestSpeechBridgeLogger:
    """Tests for SpeechBridgeLogger"""

    def setup_method(self):
        """Setup test environment"""
        # Create temporary directory for logs
        self.temp_dir = tempfile.mkdtemp()
        self.log_dir = Path(self.temp_dir) / "test_logs"

    def teardown_method(self):
        """Cleanup test environment"""
        # Remove temporary directory
        if Path(self.temp_dir).exists():
            shutil.rmtree(self.temp_dir)

    def test_logger_creation(self):
        """Test logger creation"""
        logger_system = SpeechBridgeLogger(log_dir=str(self.log_dir))

        assert logger_system is not None
        assert self.log_dir.exists()
        assert logger_system.current_log.exists()
        assert logger_system.archive_log.exists()

    def test_logger_directory_creation(self):
        """Test automatic directory creation"""
        # Directory should be created automatically
        assert not self.log_dir.exists()

        logger_system = SpeechBridgeLogger(log_dir=str(self.log_dir))

        assert self.log_dir.exists()
        assert self.log_dir.is_dir()

    def test_current_log_overwrite(self):
        """Test current log overwrites on each run"""
        # First run
        logger1 = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        log1 = logger1.get_logger('test')
        log1.info("First run message")

        current_content1 = logger1.read_current_log()
        assert "First run message" in current_content1

        # Second run - should overwrite
        logger2 = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        log2 = logger2.get_logger('test')
        log2.info("Second run message")

        current_content2 = logger2.read_current_log()
        assert "Second run message" in current_content2
        assert "First run message" not in current_content2

    def test_archive_log_append(self):
        """Test archive log appends history"""
        # First run
        logger1 = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        log1 = logger1.get_logger('test')
        log1.info("First run message")

        # Second run
        logger2 = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        log2 = logger2.get_logger('test')
        log2.info("Second run message")

        # Archive should contain both
        archive_content = logger2.read_archive_log()
        assert "First run message" in archive_content
        assert "Second run message" in archive_content

    def test_utf8_encoding(self):
        """Test UTF-8 encoding for multilingual text"""
        logger_system = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        logger = logger_system.get_logger('test')

        # Write Russian text
        russian_text = "Привет, мир! Тест UTF-8"
        logger.info(russian_text)

        # Write Chinese text
        chinese_text = "你好世界"
        logger.info(chinese_text)

        # Read and verify
        log_content = logger_system.read_current_log()
        assert russian_text in log_content
        assert chinese_text in log_content

    def test_log_levels(self):
        """Test different log levels"""
        logger_system = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            log_level=logging.DEBUG,
            console_output=False
        )
        logger = logger_system.get_logger('test')

        logger.debug("Debug message")
        logger.info("Info message")
        logger.warning("Warning message")
        logger.error("Error message")
        logger.critical("Critical message")

        log_content = logger_system.read_current_log()
        assert "Debug message" in log_content
        assert "Info message" in log_content
        assert "Warning message" in log_content
        assert "Error message" in log_content
        assert "Critical message" in log_content

    def test_get_logger(self):
        """Test getting logger instance"""
        logger_system = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )

        logger = logger_system.get_logger('custom_module')
        assert logger is not None
        assert isinstance(logger, logging.Logger)
        assert 'custom_module' in logger.name

    def test_log_file_paths(self):
        """Test log file path getters"""
        logger_system = SpeechBridgeLogger(log_dir=str(self.log_dir))

        current_path = logger_system.get_current_log_path()
        archive_path = logger_system.get_archive_log_path()

        assert current_path.name == "speechbridge_current.log"
        assert archive_path.name == "speechbridge_archive.log"
        assert current_path.parent == self.log_dir
        assert archive_path.parent == self.log_dir

    def test_read_archive_last_lines(self):
        """Test reading last N lines from archive"""
        logger_system = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )
        logger = logger_system.get_logger('test')

        # Write multiple lines
        for i in range(10):
            logger.info(f"Line {i}")

        # Read last 3 lines
        last_lines = logger_system.read_archive_log(lines=3)
        assert "Line 7" in last_lines or "Line 8" in last_lines or "Line 9" in last_lines
        assert "Line 0" not in last_lines

    def test_setup_logging_function(self):
        """Test quick setup function"""
        logger_system = setup_logging(
            log_dir=str(self.log_dir),
            console_output=False
        )

        assert logger_system is not None
        assert isinstance(logger_system, SpeechBridgeLogger)

        logger = logger_system.get_logger('test')
        logger.info("Test message")

        assert "Test message" in logger_system.read_current_log()

    def test_session_markers(self):
        """Test session start markers in archive"""
        logger_system = SpeechBridgeLogger(
            log_dir=str(self.log_dir),
            console_output=False
        )

        archive_content = logger_system.read_archive_log()

        # Should contain session markers
        assert "SpeechBridge session started" in archive_content
        assert "=" * 80 in archive_content


if __name__ == "__main__":
    pytest.main([__file__, "-v", "--tb=short"])
