"""Web scraping tool using generated Crawler API client."""

import logging

from .._config import SDKConfig
from .._api.client import (
    BaseResource,
    AsyncBaseResource,
    SyncCrawlerCrawlerAPI,
    CrawlerCrawlerAPI,
)
from .._api.generated.crawler.crawler__api__crawler.models import (
    ScrapeRequestRequest,
    ScrapeResponse,
    Links,
)

logger = logging.getLogger(__name__)


class CrawlerResource(BaseResource):
    """Web scraping tool (sync).

    Uses generated SyncCrawlerCrawlerAPI client.

    Example:
        ```python
        from sdkrouter import SDKRouter

        client = SDKRouter(api_key="your-api-key")

        # Scrape a URL → Markdown
        result = client.crawler.scrape("https://example.com")
        if result.success:
            print(result.markdown)
        ```
    """

    def __init__(self, config: SDKConfig):
        super().__init__(config)
        self._api = SyncCrawlerCrawlerAPI(self._http_client)

    def scrape(
        self,
        url: str,
        *,
        cache: bool | None = None,
        stealth: bool | None = None,
        remove_overlays: bool | None = None,
        wait_for_images: bool | None = None,
        screenshot: bool | None = None,
        css_selector: str | None = None,
    ) -> ScrapeResponse:
        """
        Scrape a URL and return its content as Markdown.

        Args:
            url: URL to scrape (must be http/https)
            cache: Use cached result if available
            stealth: Enable stealth mode to bypass anti-bot protection
            remove_overlays: Remove popups and overlay elements
            wait_for_images: Wait for images to load before extracting
            screenshot: Take a screenshot of the page
            css_selector: CSS selector to extract specific content

        Returns:
            ScrapeResponse with markdown, links, metadata, and status info
        """
        logger.debug("Scraping URL: %s", url)
        request = ScrapeRequestRequest(
            url=url,
            cache=cache,
            stealth=stealth,
            remove_overlays=remove_overlays,
            wait_for_images=wait_for_images,
            screenshot=screenshot,
            css_selector=css_selector,
        )
        result = self._api.scrape_create(request)
        logger.info("Scrape %s: success=%s, duration=%sms", url, result.success, result.duration_ms)
        return result


class AsyncCrawlerResource(AsyncBaseResource):
    """Web scraping tool (async).

    Uses generated CrawlerCrawlerAPI client.

    Example:
        ```python
        from sdkrouter import AsyncSDKRouter

        client = AsyncSDKRouter(api_key="your-api-key")

        result = await client.crawler.scrape("https://example.com")
        if result.success:
            print(result.markdown)
        ```
    """

    def __init__(self, config: SDKConfig):
        super().__init__(config)
        self._api = CrawlerCrawlerAPI(self._http_client)

    async def scrape(
        self,
        url: str,
        *,
        cache: bool | None = None,
        stealth: bool | None = None,
        remove_overlays: bool | None = None,
        wait_for_images: bool | None = None,
        screenshot: bool | None = None,
        css_selector: str | None = None,
    ) -> ScrapeResponse:
        """
        Scrape a URL and return its content as Markdown.

        Args:
            url: URL to scrape (must be http/https)
            cache: Use cached result if available
            stealth: Enable stealth mode to bypass anti-bot protection
            remove_overlays: Remove popups and overlay elements
            wait_for_images: Wait for images to load before extracting
            screenshot: Take a screenshot of the page
            css_selector: CSS selector to extract specific content

        Returns:
            ScrapeResponse with markdown, links, metadata, and status info
        """
        logger.debug("Scraping URL: %s", url)
        request = ScrapeRequestRequest(
            url=url,
            cache=cache,
            stealth=stealth,
            remove_overlays=remove_overlays,
            wait_for_images=wait_for_images,
            screenshot=screenshot,
            css_selector=css_selector,
        )
        result = await self._api.scrape_create(request)
        logger.info("Scrape %s: success=%s, duration=%sms", url, result.success, result.duration_ms)
        return result


__all__ = [
    "CrawlerResource",
    "AsyncCrawlerResource",
    "ScrapeRequestRequest",
    "ScrapeResponse",
    "Links",
]
