from pydantic import BaseModel, Field, field_validator
from typing import Optional, Any
from datetime import datetime as dt

class DateTime(BaseModel):
    """
    DateTime represents a date and time value in the system.
    It is a value object that encapsulates the date and time information.
    """

    value: Optional[str] = Field(None, description="Date and time value")

    @field_validator("value")
    def validate_datetime(cls, value: str, context: Optional[Any] = None) -> None:
        """
        Validar que el formato de la feha y hora se Y-m-d H:M:S. o vacio.
        """
        if value is None:
            return None

        try:
            dt.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ")
        except ValueError:
            raise ValueError("El formato de fecha y hora no es válido. Debe ser YYYY-MM-DDTHH:MM:SSZ.")

        return value

    @classmethod
    def now(cls) -> "DateTime":
        now_str = dt.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
        cls.value = now_str
        print(f"Fecha y hora actual: {now_str}")
        return cls(value=now_str)

    def to_native(self) -> dt:
        print(f"Convertir a datetime: {self.value}")
        if not self.value:
            return None
        return dt.strptime(self.value, "%Y-%m-%dT%H:%M:%S.%fZ")


    def __eq__(self, other: object) -> bool:
        return isinstance(other, DateTime) and self.value == other.value

    def __str__(self) -> str:
        return self.value or ""

    class Config:
        json_schema_extra = {
            "example": {
                "datetime": "2023-10-01 12:00:00"
            }
        }