"""
Schema checks - database schema validation against SQLAlchemy models.

Tests:
    test_schema_matches_models    SQLAlchemy models match database schema
"""

import importlib
from dataclasses import dataclass, field

from .base import CheckBase


@dataclass
class SchemaChecks(CheckBase):
    """Database schema validation."""

    # SQLAlchemy models to validate (import paths like "myapp.models.User")
    sqlalchemy_models: list[str] = field(default_factory=list)

    def validate_schema(self) -> dict:
        """Check that SQLAlchemy models can be loaded and have valid table config.

        Validates model import paths and basic table metadata. Does not
        connect to a database — use project-level integration tests for that.
        """
        result = {"valid": True, "violations": [], "error": None}

        if not self.sqlalchemy_models:
            return result

        for model_path in self.sqlalchemy_models:
            try:
                module_path, class_name = model_path.rsplit(".", 1)
                module = importlib.import_module(module_path)
                model_class = getattr(module, class_name)

                if not hasattr(model_class, "__tablename__"):
                    result["violations"].append(
                        f"{model_path}: missing __tablename__"
                    )
            except Exception as e:
                result["violations"].append(f"Failed to load {model_path}: {e}")

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

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

        class SchemaTests:
            """Database schema validation tests."""

            def test_schema_matches_models(self):
                """Database schema must match SQLAlchemy models."""
                if "test_schema_matches_models" in checks.skip_tests:
                    return
                if not checks.sqlalchemy_models:
                    return

                result = checks.validate_schema()

                if result["error"]:
                    assert False, result["error"]

                assert result["valid"], (
                    f"Schema validation failed:\n"
                    f"  {chr(10).join(result['violations'])}"
                )

        return SchemaTests
