"""Tests for error pattern detector."""

import json
import tempfile
from pathlib import Path

import pytest

from oclawma.self_improvement.error_pattern_detector import (
    ErrorPattern,
    ErrorPatternDetector,
)


class TestErrorPattern:
    """Tests for ErrorPattern dataclass."""

    def test_pattern_creation(self):
        """Test creating an error pattern."""
        pattern = ErrorPattern(
            name="test_error",
            regex=r"test error",
            category="test",
            severity="medium",
            suggestion="Fix it",
        )
        assert pattern.name == "test_error"
        assert pattern.category == "test"
        assert pattern.compiled_regex is not None

    def test_pattern_matching(self):
        """Test pattern regex matching."""
        pattern = ErrorPattern(
            name="file_not_found",
            regex=r"ENOENT|no such file",
            category="file",
            severity="high",
            suggestion="Check path",
        )
        assert pattern.compiled_regex.search("ENOENT: no such file")
        assert not pattern.compiled_regex.search("success")


class TestErrorPatternDetector:
    """Tests for ErrorPatternDetector."""

    @pytest.fixture
    def temp_dir(self):
        """Create temporary directory for tests."""
        with tempfile.TemporaryDirectory() as tmp:
            yield Path(tmp)

    @pytest.fixture
    def detector(self, temp_dir):
        """Create detector with temp paths."""
        return ErrorPatternDetector(
            session_log_dir=str(temp_dir / "logs"),
            patterns_file=str(temp_dir / "patterns.json"),
            rules_file=str(temp_dir / "AGENTS.md"),
        )

    def test_init_patterns_file(self, detector, temp_dir):
        """Test initialization of patterns file."""
        detector._init_patterns_file()
        assert detector.patterns_file.exists()
        data = json.loads(detector.patterns_file.read_text())
        assert "patterns" in data
        assert "totalErrors" in data

    def test_load_save_patterns(self, detector, temp_dir):
        """Test loading and saving patterns."""
        detector._init_patterns_file()

        data = detector._load_patterns()
        data["patterns"]["test"] = {"count": 5}
        detector._save_patterns(data)

        loaded = detector._load_patterns()
        assert loaded["patterns"]["test"]["count"] == 5

    def test_extract_timestamp(self, detector):
        """Test timestamp extraction."""
        line = "[2024-01-15 10:30:00] Error occurred"
        ts = detector._extract_timestamp(line)
        assert ts == "2024-01-15 10:30:00"

        line = "[2024-01-15T10:30:00] Error occurred"
        ts = detector._extract_timestamp(line)
        assert ts == "2024-01-15T10:30:00"

        line = "No timestamp here"
        ts = detector._extract_timestamp(line)
        assert ts is None

    def test_analyze_log_file(self, detector, temp_dir):
        """Test analyzing a log file."""
        log_dir = temp_dir / "logs"
        log_dir.mkdir()

        log_file = log_dir / "test.log"
        log_file.write_text(
            """
[INFO] Starting up
[ERROR] ENOENT: no such file or directory
[INFO] Continuing
[ERROR] SyntaxError: Unexpected token
"""
        )

        errors = detector._analyze_log_file(log_file)
        assert len(errors) == 2
        assert errors[0].pattern == "file_not_found"
        assert errors[1].pattern == "syntax_error"

    def test_generate_rule(self, detector):
        """Test rule generation."""
        pattern = {"name": "file_not_found", "suggestion": "Check path"}
        rule = detector._generate_rule(pattern)
        assert "verify file existence" in rule.lower()

        pattern = {"name": "unknown_error", "suggestion": "Be careful"}
        rule = detector._generate_rule(pattern)
        assert rule == "Be careful"

    def test_default_patterns(self):
        """Test default patterns are loaded."""
        detector = ErrorPatternDetector()
        assert len(detector.patterns) > 0

        pattern_names = [p.name for p in detector.patterns]
        assert "file_not_found" in pattern_names
        assert "permission_denied" in pattern_names
        assert "syntax_error" in pattern_names
