from datetime import datetime
from typing import Optional, Any, Dict
from pydantic import BaseModel, field_validator
import json


class UserData(BaseModel):
    name: Optional[str] = None
    phone: Optional[str] = None
    email: Optional[str] = None
    address: Optional[str] = None
    city: Optional[str] = None
    problem_summary: Optional[str] = None
    preferences: Optional[str] = None


class User(BaseModel):
    id: int
    unit_id: int
    external_id: str
    content: UserData
    timestamp: datetime

    @field_validator("content", mode="before")
    @classmethod
    def decode_json(cls, v: Any) -> UserData:
        if isinstance(v, UserData):
            return v

        if isinstance(v, str):
            try:
                parsed_data = json.loads(v)
                return UserData(**parsed_data)
            except json.JSONDecodeError:
                return UserData()

        if isinstance(v, dict):
            return UserData(**v)

        return UserData()


class MessageResponse(BaseModel):
    response: str
    user: User


class Message(BaseModel):
    id: int
    user_id: Optional[int] = None
    content: Dict[str, Any]
    timestamp: datetime

    @field_validator("content", mode="before")
    @classmethod
    def decode_json(cls, v) -> Dict[str, Any]:
        if isinstance(v, str):
            try:
                return json.loads(v)
            except json.JSONDecodeError:
                return {}
        return v
