"""
Safety checks - bare except and other dangerous patterns.

Tests:
    test_no_bare_except    No bare except: clauses
"""

import ast
from dataclasses import dataclass

from .base import CheckBase


@dataclass
class SafetyChecks(CheckBase):
    """Code safety validation."""

    def validate_bare_except(self) -> dict:
        """Check for bare except: clauses."""
        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.ExceptHandler):
                    if node.type is None:
                        result["violations"].append(f"{rel_path}:{node.lineno}")

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

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

        class SafetyTests:
            """Code safety validation tests."""

            def test_no_bare_except(self):
                """No bare except: clauses - always specify exception type."""
                if "test_no_bare_except" in checks.skip_tests:
                    return

                result = checks.validate_bare_except()
                assert result["valid"], (
                    f"Bare except: clauses (specify exception type):\n"
                    f"  {chr(10).join(result['violations'])}\n\n"
                    f"Use 'except Exception:' or a more specific exception type."
                )

        return SafetyTests
