from __future__ import annotations

import httpx

from .models import *


class SyncCleanerCleanerAPI:
    """Synchronous API endpoints for Cleaner."""

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

    def list(self, page: int | None = None, page_size: int | None = None) -> list[PaginatedCleaningRequestListList]:
        """
        List cleaning requests

        List user's cleaning requests.
        """
        url = "/api/cleaner/"
        response = self._client.get(url, params={"page": page if page is not None else None, "page_size": page_size if page_size is not None else None})
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return PaginatedCleaningRequestListList.model_validate(response.json())


    def retrieve(self, uuid: str) -> CleaningRequestDetail:
        """
        Get cleaning request details

        Get cleaning request details.
        """
        url = f"/api/cleaner/{uuid}/"
        response = self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return CleaningRequestDetail.model_validate(response.json())


    def cancel_create(self, uuid: str) -> None:
        """
        Cancel async cleaning job

        Cancel a queued or running cleaning job.
        """
        url = f"/api/cleaner/{uuid}/cancel/"
        response = self._client.post(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)


    def patterns_retrieve(self, uuid: str) -> PatternsResponse:
        """
        Get extraction patterns

        Get reusable extraction patterns from completed job.
        """
        url = f"/api/cleaner/{uuid}/patterns/"
        response = self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return PatternsResponse.model_validate(response.json())


    def status_retrieve(self, uuid: str) -> JobStatus:
        """
        Get job status

        Get status of async cleaning job.
        """
        url = f"/api/cleaner/{uuid}/status/"
        response = self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return JobStatus.model_validate(response.json())


    def clean_create(self, data: CleanRequestRequest) -> CleanResponse:
        """
        Clean HTML file

        Clean HTML file. Accepts multipart/form-data with HTML file. Returns
        cleaned HTML with statistics.
        """
        url = "/api/cleaner/clean/"
        response = self._client.post(url, json=data.model_dump(exclude_unset=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return CleanResponse.model_validate(response.json())


    def clean_async_create(self, data: CleanAsyncRequestRequest) -> CleanAsyncResponse:
        """
        Clean HTML async (agent)

        Queue HTML cleaning using agent service. Returns job ID for status
        polling.
        """
        url = "/api/cleaner/clean-async/"
        response = self._client.post(url, json=data.model_dump(exclude_unset=True))
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return CleanAsyncResponse.model_validate(response.json())


    def stats_retrieve(self) -> CleaningStats:
        """
        Get cleaning statistics

        Get cleaning statistics for the current API key.
        """
        url = "/api/cleaner/stats/"
        response = self._client.get(url)
        if not response.is_success:
            try:
                error_body = response.json()
            except Exception:
                error_body = response.text
            raise httpx.HTTPStatusError(f"{response.status_code}: {error_body}", request=response.request, response=response)
        return CleaningStats.model_validate(response.json())


