"""Backlink Marketplace resource for Agent Berlin SDK.

**IMPORTANT - Credit Cost Warning:**
This resource charges **2 credits per domain returned**.

Cost estimates:
- 100 domains = 200 credits
- 500 domains = 1,000 credits

Always check your credit balance before making large requests.
"""

from typing import List, Optional

from .._http import HTTPClient
from ..models.backlink_marketplace import BacklinkMarketplaceListDomainsResponse


class BacklinkMarketplaceResource:
    """Resource for finding guest posting and link building opportunities.

    **IMPORTANT - Credit Cost Warning:**
    This resource charges **2 credits per domain returned**.

    Cost estimates:
    - 100 domains = 200 credits
    - 500 domains = 1,000 credits

    Example:
        # Find high-DR domains for guest posting
        result = client.backlink_marketplace.list_domains(
            min_dr=30,
            max_price=100,
            limit=50,
        )

        for domain in result.domains:
            print(f"{domain.domain}: DR={domain.dr}, Price=${domain.min_price}")
    """

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

    def list_domains(
        self,
        *,
        # Pagination
        limit: Optional[int] = None,
        offset: Optional[int] = None,
        # Domain metrics filters
        min_dr: Optional[int] = None,
        max_dr: Optional[int] = None,
        min_da: Optional[int] = None,
        max_da: Optional[int] = None,
        # Traffic filters
        min_traffic: Optional[int] = None,
        max_traffic: Optional[int] = None,
        # Price filters
        min_price: Optional[float] = None,
        max_price: Optional[float] = None,
        # Content filters
        categories: Optional[List[str]] = None,
        languages: Optional[List[str]] = None,
        countries: Optional[List[str]] = None,
        # Link attributes
        link_types: Optional[List[str]] = None,
        # Sorting
        sort_by: Optional[str] = None,
        sort_order: Optional[str] = None,
    ) -> BacklinkMarketplaceListDomainsResponse:
        """List domains from the backlink marketplace.

        **Credit Cost:** 2 credits per domain returned.

        Find guest posting and link building opportunities by filtering
        domains based on SEO metrics, pricing, and content categories.

        Args:
            limit: Number of results (default: 100, max: 500).
            offset: Pagination offset (default: 0).
            min_dr: Minimum Domain Rating (0-100).
            max_dr: Maximum Domain Rating (0-100).
            min_da: Minimum Domain Authority (0-100).
            max_da: Maximum Domain Authority (0-100).
            min_traffic: Minimum monthly organic traffic.
            max_traffic: Maximum monthly organic traffic.
            min_price: Minimum price in USD.
            max_price: Maximum price in USD.
            categories: Filter by categories/niches (e.g., ["technology", "marketing"]).
            languages: Filter by language codes (e.g., ["en", "de"]).
            countries: Filter by country codes (e.g., ["us", "uk"]).
            link_types: Filter by link types (e.g., ["dofollow", "nofollow"]).
            sort_by: Field to sort by (e.g., "dr", "price", "traffic").
            sort_order: Sort order ("asc" or "desc").

        Returns:
            BacklinkMarketplaceListDomainsResponse containing:
            - domains: List of BacklinkMarketplaceDomain objects
            - total: Total number of matching domains
            - limit: Limit used
            - offset: Offset used
            - has_more: Whether more results are available

        Each BacklinkMarketplaceDomain has:
            - domain: Domain name
            - dr: Domain Rating (Ahrefs, 0-100)
            - da: Domain Authority (Moz, 0-100)
            - traffic: Monthly organic traffic
            - rd: Referring domains count
            - categories: List of niche categories
            - language: Primary language
            - country: Primary country
            - link_type: "dofollow" or "nofollow"
            - marketplaces: List of marketplace entries with prices
            - min_price: Minimum price across marketplaces
            - max_price: Maximum price across marketplaces
            - spam_score: Spam score (0-100)
            - trust_flow: Trust flow (Majestic)
            - citation_flow: Citation flow (Majestic)

        Example:
            # Find high-quality domains with dofollow links
            result = client.backlink_marketplace.list_domains(
                min_dr=40,
                min_traffic=5000,
                link_types=["dofollow"],
                max_price=200,
                sort_by="dr",
                sort_order="desc",
                limit=100,
            )

            # Cost: 100 domains * 2 credits = 200 credits

            for domain in result.domains:
                print(f"{domain.domain}: DR={domain.dr}, ${domain.min_price}")
        """
        payload: dict[str, object] = {}

        # Pagination
        if limit is not None:
            payload["limit"] = limit
        if offset is not None:
            payload["offset"] = offset

        # Domain metrics filters
        if min_dr is not None:
            payload["min_dr"] = min_dr
        if max_dr is not None:
            payload["max_dr"] = max_dr
        if min_da is not None:
            payload["min_da"] = min_da
        if max_da is not None:
            payload["max_da"] = max_da

        # Traffic filters
        if min_traffic is not None:
            payload["min_traffic"] = min_traffic
        if max_traffic is not None:
            payload["max_traffic"] = max_traffic

        # Price filters
        if min_price is not None:
            payload["min_price"] = min_price
        if max_price is not None:
            payload["max_price"] = max_price

        # Content filters
        if categories is not None:
            payload["categories"] = categories
        if languages is not None:
            payload["languages"] = languages
        if countries is not None:
            payload["countries"] = countries

        # Link attributes
        if link_types is not None:
            payload["link_types"] = link_types

        # Sorting
        if sort_by is not None:
            payload["sort_by"] = sort_by
        if sort_order is not None:
            payload["sort_order"] = sort_order

        data = self._http.post("/backlink-marketplace/domains/list", json=payload)
        return BacklinkMarketplaceListDomainsResponse.model_validate(data)
