"""Validation handler for request validation in handler chain."""

import datetime
from typing import Any

from pydantic import BaseModel

from .base import BaseHandler


class ValidationHandler(BaseHandler):
    def __init__(self) -> None:
        super().__init__()
        self._request_name: str = "Basic"
        self._display_name: str = "ValidationHandler"

    async def handle(self, request: BaseModel, context: dict[str, Any] | None = None) -> Any:
        if request and self._request_name == "Basic":
            self._request_name = request.name
        if self._request_name not in self._display_name:
            self._display_name = f"ValidationHandler{self._request_name}"
        if context is None:
            context = {}
        required_attrs: list[str] = list(type(request).model_fields.keys())
        missing_attrs: list[str] = []
        for attr in required_attrs:
            value = getattr(request, attr, None)
            if value is None:
                missing_attrs.append(f"{attr} (missing)")
            elif isinstance(value, str) and not value.strip():
                missing_attrs.append(f"{attr} (whitespace only)")
            elif isinstance(value, dict) and len(value) == 0:
                missing_attrs.append(f"{attr} (empty dict)")
        if missing_attrs:
            error_message = (
                f"{self._display_name}: Invalid request - issues with attributes: {', '.join(missing_attrs)}"
            )
            print(error_message)
            return error_message
        context[f"{self._request_name}_validation_passed"] = True
        context[f"{self._request_name}_validated_at"] = datetime.datetime.now().isoformat()
        context[f"{self._request_name}_validated_attributes"] = required_attrs

        self._print_field_validation_status(request=request)

        print(f"{self._display_name}: Request validation successful")
        return await super().handle(request=request, context=context)

    def _print_field_validation_status(self, request: BaseModel) -> None:
        """Print validation status for all fields on the request model."""
        request_class = type(request)
        if not hasattr(request_class, "get_field_validation_status"):
            return

        status_map = request_class.get_field_validation_status()
        print(f"{self._display_name}: Field validation status:")
        for field_name, status in status_map.items():
            print(f"  {field_name}: {status}")

    def __repr__(self) -> str:
        next_handler_name = type(self._next_handler).__name__ if self._next_handler else "None"
        return f"{self._display_name}(next_handler={next_handler_name})"
