"""
Logging checks - print statements and logger usage.

Tests:
    test_no_print_statements    Use logger, not print()
    test_no_logging_getlogger   Use get_logger(), not logging.getLogger()
"""

import ast
import re
from dataclasses import dataclass

from .base import CheckBase


@dataclass
class LoggingChecks(CheckBase):
    """Logging pattern validation."""

    def validate_print_statements(self) -> dict:
        """Check for print() usage in code."""
        result = {"valid": True, "violations": []}

        for py_file in self.get_python_files():
            rel_path = self.get_relative_path(py_file)
            content = py_file.read_text()
            tree = self.parse_ast(content)
            if not tree:
                continue

            for node in ast.walk(tree):
                if isinstance(node, ast.Call):
                    if isinstance(node.func, ast.Name) and node.func.id == "print":
                        result["violations"].append(f"{rel_path}:{node.lineno}")

        result["valid"] = len(result["violations"]) == 0
        return result

    def validate_logging_getlogger(self) -> dict:
        """Check for logging.getLogger() usage instead of get_logger()."""
        result = {"valid": True, "violations": []}

        for py_file in self.get_python_files():
            rel_path = self.get_relative_path(py_file)
            content = py_file.read_text()
            if re.search(r"logging\.getLogger\s*\(", content):
                result["violations"].append(rel_path)

        result["valid"] = len(result["violations"]) == 0
        return result

    def create_test_class(self):
        """Create pytest test class for logging checks."""
        checks = self

        class LoggingTests:
            """Logging pattern validation tests."""

            def test_no_print_statements(self):
                """Files should use logger instead of print()."""
                if "test_no_print_statements" in checks.skip_tests:
                    return

                result = checks.validate_print_statements()
                assert result["valid"], (
                    f"Files using print() instead of logger:\n"
                    f"  {chr(10).join(result['violations'])}\n\n"
                    f"Use logger instead."
                )

            def test_no_logging_getlogger(self):
                """Files should use centralized get_logger(), not logging.getLogger()."""
                if "test_no_logging_getlogger" in checks.skip_tests:
                    return

                result = checks.validate_logging_getlogger()
                assert result["valid"], (
                    f"Files using logging.getLogger() instead of get_logger():\n"
                    f"  {chr(10).join(result['violations'])}\n\n"
                    f"Use 'from infrastructure import get_logger' instead."
                )

        return LoggingTests
