from __future__ import annotations

import httpx

from .models import (
    LeadDetail,
    LeadList,
    LeadSubmitRequest,
    LeadSubmitResponse,
    PaginatedLeadListList,
    PatchedLeadUpdateRequest,
)


class LeadsLeadsAPI:
    """API endpoints for Leads."""

    def __init__(self, client: httpx.AsyncClient):
        """Initialize sub-client with shared httpx client."""
        self._client = client

    async def list(
        self,
        ordering: str | None = None,
        page: int | None = None,
        page_size: int | None = None,
        search: str | None = None,
    ) -> list[PaginatedLeadListList]:
        """
        List leads

        ViewSet for leads. - {project_slug}/submit/ — public, no auth,
        identified by project_slug in URL - list/retrieve/update — authenticated
        via API key
        """
        url = "/api/leads/"
        _params = {
            k: v for k, v in {
                "ordering": ordering,
                "page": page,
                "page_size": page_size,
                "search": search,
            }.items() if v is not None
        }
        response = await self._client.get(url, params=_params)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return PaginatedLeadListList.model_validate(response.json())


    async def create(self) -> LeadList:
        """
        ViewSet for leads. - {project_slug}/submit/ — public, no auth,
        identified by project_slug in URL - list/retrieve/update — authenticated
        via API key
        """
        url = "/api/leads/"
        response = await self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return LeadList.model_validate(response.json())


    async def retrieve(self, id: str) -> LeadDetail:
        """
        Lead detail

        ViewSet for leads. - {project_slug}/submit/ — public, no auth,
        identified by project_slug in URL - list/retrieve/update — authenticated
        via API key
        """
        url = f"/api/leads/{id}/"
        response = await self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return LeadDetail.model_validate(response.json())


    async def partial_update(
        self,
        id: str,
        data: PatchedLeadUpdateRequest | None = None,
    ) -> LeadDetail:
        """
        Update lead status/notes

        ViewSet for leads. - {project_slug}/submit/ — public, no auth,
        identified by project_slug in URL - list/retrieve/update — authenticated
        via API key
        """
        url = f"/api/leads/{id}/"
        _json = data.model_dump(mode="json", exclude_unset=True, exclude_none=True) if data else None
        response = await self._client.patch(url, json=_json)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return LeadDetail.model_validate(response.json())


    async def submit_create(
        self,
        project_slug: str,
        data: LeadSubmitRequest,
    ) -> LeadSubmitResponse:
        """
        Submit a lead (public, no auth)

        Public endpoint for submitting a lead form. No authentication required.
        Project is identified by project_slug in the URL.
        """
        url = f"/api/leads/submit/{project_slug}/"
        response = await self._client.post(url, json=data.model_dump(mode="json", exclude_unset=True, exclude_none=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            msg = f"{response.status_code}: {error_body}"
            raise httpx.HTTPStatusError(
                msg, request=response.request, response=response
            )
        return LeadSubmitResponse.model_validate(response.json())


