"""GTM Router Python SDK — official client for the GTM Router API."""

from __future__ import annotations

import os
from typing import Any

from .client import HttpClient
from .errors import (
    AuthenticationError,
    InsufficientBalanceError,
    GTMRouterError,
    PollTimeoutError,
    RateLimitError,
    ValidationError,
)
from .resources import AccountResource, BulkResource, EmailResource, PhoneResource

__version__ = "1.0.0"
__all__ = [
    "GTMRouter",
    "GTMRouterError",
    "AuthenticationError",
    "RateLimitError",
    "InsufficientBalanceError",
    "ValidationError",
    "PollTimeoutError",
]

_DEFAULT_BASE_URL = "http://localhost:3000/api/v1"


class GTMRouter:
    """
    Main entry point for the GTM Router Python SDK.

    Usage::

        from gtm_router import GTMRouter

        client = GTMRouter()                          # reads GTM_ROUTER_API_KEY from env
        client = GTMRouter(api_key="sk_live_xxx")     # explicit key
        client = GTMRouter(base_url="https://...")     # custom endpoint

    Resources:
        client.email    — single-record email find / verify
        client.phone    — single-record phone find
        client.bulk     — bulk operations with auto-polling
        client.account  — account balance and info
    """

    def __init__(
        self,
        api_key: str | None = None,
        base_url: str | None = None,
        timeout: int = 30,
        max_retries: int = 2,
        retry_delay: float = 1.0,
        poll_interval: float = 3.0,
        poll_timeout: float = 300.0,
    ):
        resolved_key = api_key or os.environ.get("GTM_ROUTER_API_KEY", "")
        if not resolved_key:
            raise AuthenticationError(
                "No API key provided. Pass api_key= or set GTM_ROUTER_API_KEY env var.",
                status_code=0,
                code="MISSING_API_KEY",
            )

        resolved_url = base_url or os.environ.get("GTM_ROUTER_API_URL", _DEFAULT_BASE_URL)

        self._client = HttpClient(
            api_key=resolved_key,
            base_url=resolved_url,
            timeout=timeout,
            max_retries=max_retries,
            retry_delay=retry_delay,
            poll_interval=poll_interval,
            poll_timeout=poll_timeout,
        )

        self.email = EmailResource(self._client)
        self.phone = PhoneResource(self._client)
        self.bulk = BulkResource(self._client)
        self.account = AccountResource(self._client)
