"""
Semantil - Company Intelligence API

Official Python SDK for Semantil API.
Find similar companies, enrich company data, and build lookalike audiences.

Usage:
    from semantil import Semantil

    client = Semantil("your-api-key")
    similar = client.find_similar("stripe.com", limit=10)
"""

__version__ = "0.1.0"

import requests
from typing import Optional


class SemantilError(Exception):
    """Base exception for Semantil API errors."""
    pass


class Semantil:
    """Semantil API client."""

    def __init__(self, api_key: str, base_url: str = "https://api.semantil.com/v1"):
        """
        Initialize Semantil client.

        Args:
            api_key: Your Semantil API key
            base_url: API base URL (default: https://api.semantil.com/v1)
        """
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self._session = requests.Session()
        self._session.headers.update({
            "Authorization": f"Bearer {api_key}",
            "User-Agent": f"semantil-python/{__version__}"
        })

    def find_similar(self, domain: str, limit: int = 10) -> dict:
        """
        Find companies similar to the given domain.

        Args:
            domain: Target company domain (e.g., "stripe.com")
            limit: Maximum number of results (default: 10)

        Returns:
            Dict with similar companies and metadata
        """
        resp = self._session.get(
            f"{self.base_url}/similar",
            params={"domain": domain, "limit": limit}
        )
        self._handle_response(resp)
        return resp.json()

    def lookup(self, domain: str) -> dict:
        """
        Get company information by domain.

        Args:
            domain: Company domain (e.g., "stripe.com")

        Returns:
            Dict with company data
        """
        resp = self._session.get(
            f"{self.base_url}/lookup",
            params={"domain": domain}
        )
        self._handle_response(resp)
        return resp.json()

    def search(self, query: str, limit: int = 10, filters: Optional[dict] = None) -> dict:
        """
        Semantic search for companies.

        Args:
            query: Natural language search query
            limit: Maximum number of results (default: 10)
            filters: Optional filters (country, industry, etc.)

        Returns:
            Dict with search results
        """
        params = {"q": query, "limit": limit}
        if filters:
            params.update(filters)

        resp = self._session.get(f"{self.base_url}/search", params=params)
        self._handle_response(resp)
        return resp.json()

    def _handle_response(self, resp: requests.Response) -> None:
        """Handle API response and raise appropriate errors."""
        if resp.status_code == 401:
            raise SemantilError("Invalid API key")
        if resp.status_code == 429:
            raise SemantilError("Rate limit exceeded")
        if not resp.ok:
            raise SemantilError(f"API error: {resp.status_code} - {resp.text}")
