"""Pixwell SDK type definitions."""

from dataclasses import dataclass
from typing import Any, Dict, List, Literal, Optional


@dataclass
class ScreenshotOptions:
    """Screenshot request parameters."""

    url: str
    """URL to capture."""

    width: int = 1280
    """Viewport width in pixels."""

    height: int = 720
    """Viewport height in pixels."""

    full_page: bool = False
    """Capture full scrollable page."""

    format: Literal["png", "jpeg", "webp"] = "png"
    """Image format."""

    quality: int = 80
    """Image quality 1-100, applies to jpeg/webp."""

    mobile: bool = False
    """Emulate mobile device."""

    dark_mode: bool = False
    """Enable dark mode."""

    delay: int = 0
    """Wait time in ms before capture (max: 10000)."""

    selector: Optional[str] = None
    """CSS selector to capture specific element."""

    cache_ttl: int = 0
    """Cache TTL in seconds (max: 3600)."""

    def to_dict(self) -> Dict[str, Any]:
        """Convert to API request format."""
        data: Dict[str, Any] = {
            "url": self.url,
            "width": self.width,
            "height": self.height,
            "format": self.format,
            "quality": self.quality,
        }
        if self.full_page:
            data["fullPage"] = True
        if self.mobile:
            data["mobile"] = True
        if self.dark_mode:
            data["darkMode"] = True
        if self.delay > 0:
            data["delay"] = self.delay
        if self.selector:
            data["selector"] = self.selector
        if self.cache_ttl > 0:
            data["cacheTtl"] = self.cache_ttl
        return data


@dataclass
class ScreenshotResponse:
    """Screenshot response."""

    data: bytes
    """Screenshot image data."""

    content_type: str
    """Content type (e.g., 'image/png')."""

    size: int
    """Image size in bytes."""

    duration_ms: int
    """Capture duration in milliseconds."""

    cached: bool
    """Whether the result was served from cache."""


@dataclass
class BatchResultItem:
    """Single result in batch response."""

    url: str
    """Original URL."""

    success: bool
    """Whether capture succeeded."""

    data: Optional[str] = None
    """Base64 encoded image data (if success)."""

    content_type: Optional[str] = None
    """Content type (if success)."""

    size: Optional[int] = None
    """Image size in bytes (if success)."""

    duration_ms: Optional[int] = None
    """Capture duration in ms (if success)."""

    error_code: Optional[str] = None
    """Error code (if failed)."""

    error_message: Optional[str] = None
    """Error message (if failed)."""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BatchResultItem":
        """Create from API response."""
        error = data.get("error", {})
        return cls(
            url=data["url"],
            success=data["success"],
            data=data.get("data"),
            content_type=data.get("contentType"),
            size=data.get("size"),
            duration_ms=data.get("durationMs"),
            error_code=error.get("code"),
            error_message=error.get("message"),
        )


@dataclass
class BatchSummary:
    """Batch response summary."""

    total: int
    succeeded: int
    failed: int
    total_duration_ms: int


@dataclass
class BatchResponse:
    """Batch screenshot response."""

    results: List[BatchResultItem]
    """Results for each URL."""

    summary: BatchSummary
    """Summary statistics."""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "BatchResponse":
        """Create from API response."""
        summary_data = data["summary"]
        return cls(
            results=[BatchResultItem.from_dict(r) for r in data["results"]],
            summary=BatchSummary(
                total=summary_data["total"],
                succeeded=summary_data["succeeded"],
                failed=summary_data["failed"],
                total_duration_ms=summary_data["totalDurationMs"],
            ),
        )


@dataclass
class BatchOptions:
    """Batch screenshot request."""

    urls: List[str]
    """URLs to capture (max 10)."""

    width: int = 1280
    height: int = 720
    full_page: bool = False
    format: Literal["png", "jpeg", "webp"] = "png"
    quality: int = 80
    mobile: bool = False
    dark_mode: bool = False
    delay: int = 0

    def to_dict(self) -> Dict[str, Any]:
        """Convert to API request format."""
        options: Dict[str, Any] = {
            "width": self.width,
            "height": self.height,
            "format": self.format,
            "quality": self.quality,
        }
        if self.full_page:
            options["fullPage"] = True
        if self.mobile:
            options["mobile"] = True
        if self.dark_mode:
            options["darkMode"] = True
        if self.delay > 0:
            options["delay"] = self.delay

        return {"urls": self.urls, "options": options}


@dataclass
class UsageTier:
    """Usage statistics for a time period."""

    used: int
    limit: int
    remaining: int


@dataclass
class PlanInfo:
    """Plan information."""

    name: str
    max_width: int
    max_height: int


@dataclass
class UsageResponse:
    """Usage statistics response."""

    daily: UsageTier
    monthly: UsageTier
    plan: PlanInfo

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "UsageResponse":
        """Create from API response."""
        return cls(
            daily=UsageTier(**data["daily"]),
            monthly=UsageTier(**data["monthly"]),
            plan=PlanInfo(
                name=data["plan"]["name"],
                max_width=data["plan"]["maxWidth"],
                max_height=data["plan"]["maxHeight"],
            ),
        )
