from __future__ import annotations

import httpx

from .models import (
    ScrapeRequestRequest,
    ScrapeResponse,
)


class SyncCrawlerCrawlerAPI:
    """Synchronous API endpoints for Crawler."""

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

    def scrape_create(self, data: ScrapeRequestRequest) -> ScrapeResponse:
        """
        Scrape a URL

        Scrape a URL and return its content as Markdown using Crawl4AI.
        """
        url = "/api/crawler/scrape/"
        response = 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 ScrapeResponse.model_validate(response.json())


