from pathlib import Path

from pydantic import BaseModel, Field


class TelegramContact(BaseModel):
    user_id: int = 0
    first_name: str = ""
    username: str = ""
    last_seen: str = ""
    authorized: bool = False
    pending_messages: list[str] = Field(default_factory=list)


class WhatsAppContact(BaseModel):
    jid: str = ""
    number: str = ""
    last_seen: str = ""
    authorized: bool = False
    pending_messages: list[str] = Field(default_factory=list)


class Contacts(BaseModel):
    telegram: dict[str, TelegramContact] = Field(default_factory=dict)
    whatsapp: dict[str, WhatsAppContact] = Field(default_factory=dict)

    @classmethod
    def load(cls, path: Path) -> "Contacts":
        return cls.model_validate_json(path.read_text(encoding="utf-8"))

    @classmethod
    def ensure(cls, path: Path) -> "Contacts":
        if not path.exists():
            contacts = cls()
            path.write_text(contacts.model_dump_json(indent=2), encoding="utf-8")
        return cls.load(path)

    def persist(self, path: Path) -> None:
        path.write_text(self.model_dump_json(indent=2), encoding="utf-8")

    @property
    def telegram_contacts(self) -> list[TelegramContact]:
        return list(self.telegram.values())

    @property
    def whatsapp_contacts(self) -> list[WhatsAppContact]:
        return list(self.whatsapp.values())

    def is_authorized_for_telegram(self, user_id: int) -> bool:
        return any(c.user_id == user_id and c.authorized for c in self.telegram_contacts)

    def is_authorized_for_whatsapp(self, jid: str) -> bool:
        return any(c.jid == jid and c.authorized for c in self.whatsapp_contacts)
