"""Pages resource for Agent Berlin SDK."""

from typing import Optional

from .._http import HTTPClient
from ..models.search import PageDetailResponse, PageListResponse, PageSearchResponse
from ..utils import get_project_domain


class PagesResource:
    """Resource for page operations.

    Example:
        # Search for similar pages by query
        results = client.pages.search(query="SEO best practices")

        # Find similar pages to an indexed page
        results = client.pages.search(url="https://example.com/blog/seo-guide")

        # Get page details with similarity analysis
        page = client.pages.get(url="https://example.com/blog/seo-tips", detailed=True)
    """

    def __init__(self, http: HTTPClient) -> None:
        self._http = http

    def search(
        self,
        *,
        query: Optional[str] = None,
        url: Optional[str] = None,
        content: Optional[str] = None,
        count: Optional[int] = None,
        offset: Optional[int] = None,
        similarity_threshold: Optional[float] = None,
        domain: Optional[str] = None,
        own_only: bool = False,
        status_code: Optional[str] = None,
        topic: Optional[str] = None,
        page_type: Optional[str] = None,
    ) -> PageSearchResponse:
        """Search for similar pages with multiple input modes.

        This unified method supports three input modes (exactly one required):
        - query: Simple text query for semantic search across all pages
        - url: Find similar pages to an existing indexed page
        - content: Find similar pages to provided raw content

        Note: For chunk-level analysis (deep search), use pages.get(url, detailed=True) instead.

        The project domain is automatically populated.

        Args:
            query: Text query for semantic search (mutually exclusive with url/content).
            url: URL of an indexed page to find similar pages for (mutually exclusive with query/content).
            content: Raw content string to find similar pages for (mutually exclusive with query/url).
            count: Maximum recommendations to return (default: 10, max: 50).
            offset: Pagination offset (default: 0).
            similarity_threshold: Minimum similarity score 0-1 (default: 0.60).
            domain: Filter by domain (e.g., "competitor.com").
            own_only: If True, filter to only your own pages (excludes competitors).
            status_code: Filter by HTTP status code ("200", "404", "error", "redirect", "success").
            topic: Filter by topic name.
            page_type: Filter by page type ("pillar" or "landing").

        Returns:
            PageSearchResponse with similar_pages (always includes evidence and topic_info).

        Raises:
            AgentBerlinValidationError: If input validation fails (e.g., multiple inputs provided).

        Example:
            # Query mode
            results = client.pages.search(query="SEO tips")

            # URL mode
            results = client.pages.search(url="https://example.com/blog/guide")

            # Content mode
            results = client.pages.search(content="This is my page content...")

            # Query mode with filters
            results = client.pages.search(
                query="SEO guide",
                domain="example.com",
                status_code="200",
                page_type="pillar"
            )
        """
        payload: dict[str, object] = {
            "project_domain": get_project_domain(),
        }
        if query is not None:
            payload["query"] = query
        if url is not None:
            payload["url"] = url
        if content is not None:
            payload["content"] = content
        if count is not None:
            payload["count"] = count
        if offset is not None:
            payload["offset"] = offset
        if similarity_threshold is not None:
            payload["similarity_threshold"] = similarity_threshold
        if domain is not None:
            payload["domain"] = domain
        if own_only:
            payload["own_only"] = own_only
        if status_code is not None:
            payload["status_code"] = status_code
        if topic is not None:
            payload["topic"] = topic
        if page_type is not None:
            payload["page_type"] = page_type

        data = self._http.post("/pages/advanced-search", json=payload)
        return PageSearchResponse.model_validate(data)

    def get(
        self,
        url: str,
        *,
        content_length: Optional[int] = None,
        detailed: bool = False,
    ) -> PageDetailResponse:
        """Get detailed information about a specific page.

        The project domain is automatically populated.

        Args:
            url: The page URL to look up.
            content_length: Max characters of content to return (default: 0).
            detailed: If True, compute and return similar_pages and similar_chunks (expensive, 1-10s).

        Returns:
            PageDetailResponse with page metadata, links, topic info.
            When detailed=True, also includes similar_pages and similar_chunks.
        """
        payload: dict[str, object] = {
            "project_domain": get_project_domain(),
            "url": url,
        }
        if content_length is not None:
            payload["content_length"] = content_length
        if detailed:
            payload["detailed"] = detailed

        data = self._http.post("/pages/get", json=payload)
        return PageDetailResponse.model_validate(data)

    def list(
        self,
        *,
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        domain: Optional[str] = None,
        own_only: bool = False,
    ) -> PageListResponse:
        """List pages with pagination and optional filtering.

        Returns a paginated list of all indexed pages.

        Args:
            limit: Max pages to return (default: 100, max: 1000).
            offset: Pagination offset (default: 0).
            domain: Filter by domain (e.g., "competitor.com").
            own_only: If True, only return your own pages.

        Returns:
            PageListResponse with pages list and pagination info.

        Example:
            result = client.pages.list(limit=50)
            for page in result.pages:
                print(page.url, page.title)
        """
        payload: dict[str, object] = {
            "project_domain": get_project_domain(),
        }
        if limit is not None:
            payload["limit"] = limit
        if offset is not None:
            payload["offset"] = offset
        if domain is not None:
            payload["domain"] = domain
        if own_only:
            payload["own_only"] = own_only

        data = self._http.post("/pages/list", json=payload)
        return PageListResponse.model_validate(data)
