import httpx
from app.core import config
from app.core.localizer import localizer
from app.core.models.chat_models import (
    PrivateChatListResponse, PrivateChatListData, 
    PrivateChatHistoryResponse, PrivateChatHistoryData,
    PrivateMessageSendRequest, PrivateMessageSendResponse
)
from uuid import UUID
from app.core.http_client import get_client, authorized_get, authorized_post


async def get_private_chats(login: str, token: str, offset: int = 0, limit: int = 20):
    """
    Получить список приватных чатов.

    :param token: Bearer токен
    :param offset: Смещение
    :param limit: Количество
    :return: tuple (ok: bool, data: PrivateChatListData | str)
    """
    url = f"{config.BASE_URL}/v1/chat/private/list"
    headers = {"Authorization": f"Bearer {token}"}
    params = {"offset": offset, "limit": limit}

    try:
        response = await authorized_get(url, login=login, access_token=token, headers=headers, params=params)
        if response.status_code == 200:
            data = response.json()
            if data.get("status") == "fine":
                response_model = PrivateChatListResponse(**data)
                return True, response_model.data
            return False, data.get("detail", localizer.translate("Неизвестная ошибка"))

        if response.status_code in [401, 403]:
            error_data = response.json()
            return False, error_data.get("detail", localizer.translate("Недостаточно прав или неавторизован"))

        if response.status_code == 422:
            return False, localizer.translate("Некорректные параметры запроса")

        return False, f"{localizer.translate('Ошибка сервера')}: {response.status_code}"

    except httpx.RequestError as e:
        return False, f"{localizer.translate('Сетевая ошибка')}: {e}"
    except Exception as e:
        return False, f"{localizer.translate('Произошла ошибка')}: {e}"


async def get_chat_history(login: str, token: str, chat_id: UUID, before_message_id: int = None, limit: int = 30):
    """
    История сообщений приватного чата.
    """
    url = f"{config.BASE_URL}/v1/chat/private/history"
    headers = {"Authorization": f"Bearer {token}"}
    params = {"chat_id": str(chat_id), "limit": limit}
    if before_message_id:
        params["before_message_id"] = before_message_id

    try:
        response = await authorized_get(url, login=login, access_token=token, headers=headers, params=params)

        if response.status_code == 200:
            data = response.json()
            if data.get("status") == "fine":
                response_model = PrivateChatHistoryResponse(**data)
                return True, response_model.data
            return False, data.get("detail", localizer.translate("Неизвестная ошибка"))

        if response.status_code in [401, 403]:
            error_data = response.json()
            return False, error_data.get("detail", localizer.translate("Недостаточно прав или неавторизован"))
        
        if response.status_code == 422:
            return False, localizer.translate("Некорректные параметры запроса")
        
        return False, f"{localizer.translate('Ошибка сервера')}: {response.status_code}"

    except httpx.RequestError as e:
        return False, f"{localizer.translate('Сетевая ошибка')}: {e}"
    except Exception as e:
        return False, f"{localizer.translate('Произошла ошибка')}: {e}"


async def send_private_message(login: str, token: str, payload: "PrivateMessageSendRequest"):
    """
    Отправка приватного сообщения.
    """
    url = f"{config.BASE_URL}/v1/chat/private/send"
    headers = {"Authorization": f"Bearer {token}"}
    
    try:
        response = await authorized_post(url, login=login, access_token=token, headers=headers, json=payload.model_dump(mode='json'))

        if response.status_code == 200:
            data = response.json()
            if data.get("status") == "fine":
                response_model = PrivateMessageSendResponse(**data)
                return True, response_model.data
            return False, data.get("detail", localizer.translate("Неизвестная ошибка"))

        if response.status_code in [401, 403, 404]:
            error_data = response.json()
            return False, error_data.get("detail", localizer.translate("Недостаточно прав или ресурс не найден"))
        
        if response.status_code == 422:
            error_data = response.json()
            detail = error_data.get("detail")
            if isinstance(detail, list):
                return False, ", ".join([e.get("msg", localizer.translate("Некорректные параметры")) for e in detail])
            return False, detail or localizer.translate("Некорректный запрос")
        
        return False, f"{localizer.translate('Ошибка сервера')}: {response.status_code}"

    except httpx.RequestError as e:
        return False, f"{localizer.translate('Сетевая ошибка')}: {e}"
    except Exception as e:
        return False, f"{localizer.translate('Произошла ошибка')}: {e}"
