"""ShaarAI SDK Client for Python.

Requires: pip install httpx
"""

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


@dataclass
class TokenUsage:
    """AI request token usage for cost tracking."""
    input_tokens: int = 0
    output_tokens: int = 0
    cached_tokens: int = 0
    reasoning_tokens: int = 0


@dataclass
class Offer:
    """Product offer from ShaarAI."""
    id: str
    name: str
    description: str
    headline: Optional[str]
    features: List[str]
    cta_text: Optional[str]
    tracking_url: str
    terms_url: Optional[str]


class ShaarClient:
    """ShaarAI SDK Client.

    Usage:
        from shaarai import ShaarClient, TokenUsage

        client = ShaarClient(api_key="shaar_...")
        offers = client.get_offers(
            ai_vendor="openai",
            category="saas",
            model="gpt-4-turbo",
            usage=TokenUsage(input_tokens=1200, output_tokens=500)
        )
    """

    def __init__(
        self,
        api_key: str,
        base_url: str = "https://web-production-7218.up.railway.app",
    ):
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.client = httpx.Client(
            headers={"X-API-Key": api_key},
            timeout=30.0,
        )

    def get_offers(
        self,
        ai_vendor: str,
        category: str,
        model: Optional[str] = None,
        features: Optional[List[str]] = None,
        keywords: Optional[str] = None,
        region: Optional[str] = None,
        session_id: Optional[str] = None,
        limit: int = 3,
        usage: Optional[TokenUsage] = None,
        latency_ms: Optional[int] = None,
    ) -> List[Offer]:
        """Get product offers for AI to recommend.

        Args:
            ai_vendor: AI platform ("openai", "anthropic", "gemini")
            category: Product category to search
            model: Model name for cost tracking (e.g., "gpt-4-turbo")
            features: List of desired features
            keywords: Search keywords
            region: User's region (ISO country code)
            session_id: Session ID for attribution tracking
            limit: Max offers to return (1-10)
            usage: Token usage from AI request (for cost tracking)
            latency_ms: Request latency in ms

        Returns:
            List of Offer objects with tracking URLs
        """
        query = {"category": category}
        if features:
            query["features"] = features
        if keywords:
            query["keywords"] = keywords

        context = {}
        if region:
            context["region"] = region
        if session_id:
            context["session_id"] = session_id

        payload = {
            "ai_vendor": ai_vendor,
            "query": query,
            "context": context if context else None,
            "limit": limit,
            "model": model,
        }

        if usage:
            payload["usage"] = {
                "input_tokens": usage.input_tokens,
                "output_tokens": usage.output_tokens,
                "cached_tokens": usage.cached_tokens,
                "reasoning_tokens": usage.reasoning_tokens,
            }

        if latency_ms:
            payload["latency_ms"] = latency_ms

        response = self.client.post(
            f"{self.base_url}/api/v1/ai/query",
            json=payload,
        )
        response.raise_for_status()
        data = response.json()

        return [
            Offer(
                id=o["id"],
                name=o["name"],
                description=o["description"],
                headline=o.get("headline"),
                features=o.get("features", []),
                cta_text=o.get("cta_text"),
                tracking_url=o["tracking_url"],
                terms_url=o.get("terms_url"),
            )
            for o in data["offers"]
        ]

    def get_tool_schema(self, vendor: str = "openai") -> Dict[str, Any]:
        """Get the tool/function schema for your AI configuration."""
        response = self.client.get(
            f"{self.base_url}/api/v1/ai/tool-schema/{vendor}"
        )
        response.raise_for_status()
        return response.json()["schema"]

    def report_conversion(
        self,
        token: str,
        conversion_type: str,
        value: Optional[float] = None,
        currency: str = "USD",
        metadata: Optional[Dict] = None,
    ) -> bool:
        """Report a conversion when a user completes an action.

        Args:
            token: The shaar_token from tracking URL
            conversion_type: Type (purchase, signup, upgrade, trial, lead, etc.)
            value: Conversion value in currency
            currency: Currency code (default: USD)
            metadata: Additional conversion data
        """
        response = self.client.post(
            f"{self.base_url}/api/v1/attribution/convert",
            json={
                "token": token,
                "conversion_type": conversion_type,
                "conversion_value": value,
                "currency": currency,
                "metadata": metadata or {},
            },
        )
        return response.status_code == 200
