"""
Onbrix CRM Python SDK

A lightweight client for the Onbrix CRM REST API.
Requires Python 3.8+ and the ``requests`` library.

Version: 1.0.0
License: MIT
Documentation: https://docs.onbrix.com/api

Example usage::

    from onbrix_sdk import OnbrixClient

    client = OnbrixClient("crm_your_api_key", "https://your-instance.onbrix.com")
    contacts = client.records.list("contacts", page=1, page_size=10)
    print(contacts["data"])
"""

from __future__ import annotations

import hashlib
import hmac
import json
import time
from typing import (
    Any,
    Dict,
    Generator,
    Iterator,
    List,
    Optional,
    Union,
)
from urllib.parse import quote

import requests


# ---------------------------------------------------------------------------
# Error classes
# ---------------------------------------------------------------------------


class OnbrixError(Exception):
    """Base exception for all Onbrix API errors."""

    def __init__(
        self,
        message: str,
        status: int = 0,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
    ) -> None:
        super().__init__(message)
        self.message = message
        self.status = status
        self.code = code
        self.response = response

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(message={self.message!r}, status={self.status}, code={self.code!r})"


class AuthenticationError(OnbrixError):
    """Raised when the API key is missing or invalid (HTTP 401)."""

    def __init__(
        self,
        message: str,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
    ) -> None:
        super().__init__(message, status=401, code=code, response=response)


class ForbiddenError(OnbrixError):
    """Raised when the API key lacks permission for the requested action (HTTP 403)."""

    def __init__(
        self,
        message: str,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
    ) -> None:
        super().__init__(message, status=403, code=code, response=response)


class NotFoundError(OnbrixError):
    """Raised when the requested resource does not exist (HTTP 404)."""

    def __init__(
        self,
        message: str,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
    ) -> None:
        super().__init__(message, status=404, code=code, response=response)


class ValidationError(OnbrixError):
    """Raised when the request body fails validation (HTTP 400/422)."""

    def __init__(
        self,
        message: str,
        status: int = 422,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
    ) -> None:
        super().__init__(message, status=status, code=code, response=response)


class RateLimitError(OnbrixError):
    """Raised when the rate limit has been exceeded (HTTP 429).

    The ``retry_after`` attribute indicates how many seconds to wait before
    retrying the request.
    """

    def __init__(
        self,
        message: str,
        code: Optional[str] = None,
        response: Optional[Dict[str, Any]] = None,
        retry_after: Optional[float] = None,
    ) -> None:
        super().__init__(message, status=429, code=code, response=response)
        self.retry_after = retry_after


# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------


def _build_error(
    status: int,
    body: Optional[Dict[str, Any]],
    headers: Optional[Dict[str, str]] = None,
) -> OnbrixError:
    """Map an HTTP status code to the appropriate error class."""
    message = (body or {}).get("error", f"API request failed with status {status}")
    code = (body or {}).get("code")

    if status == 401:
        return AuthenticationError(message, code=code, response=body)
    if status == 403:
        return ForbiddenError(message, code=code, response=body)
    if status == 404:
        return NotFoundError(message, code=code, response=body)
    if status in (400, 422):
        return ValidationError(message, status=status, code=code, response=body)
    if status == 429:
        retry_after: Optional[float] = None
        if headers:
            reset_value = headers.get("X-RateLimit-Reset")
            if reset_value is not None:
                try:
                    reset_epoch = float(reset_value)
                    retry_after = max(0.0, reset_epoch - time.time())
                except (ValueError, TypeError):
                    pass
        return RateLimitError(message, code=code, response=body, retry_after=retry_after)

    return OnbrixError(message, status=status, code=code, response=body)


# ---------------------------------------------------------------------------
# Resource namespaces
# ---------------------------------------------------------------------------


class _ModulesResource:
    """Namespace for module-level operations."""

    def __init__(self, client: "OnbrixClient") -> None:
        self._client = client

    def list(self) -> List[Dict[str, Any]]:
        """List all modules accessible to the authenticated API key.

        Returns:
            A list of module dictionaries.

        Example::

            modules = client.modules.list()
            for mod in modules:
                print(mod["name"], mod["slug"])
        """
        result = self._client._request("GET", "/modules")
        return result["data"]


class _RecordsResource:
    """Namespace for record-level CRUD operations."""

    def __init__(self, client: "OnbrixClient") -> None:
        self._client = client

    def list(
        self,
        module_slug: str,
        *,
        page: int = 1,
        page_size: int = 25,
        sort_by: Optional[str] = None,
        sort_dir: Optional[str] = None,
        search: Optional[str] = None,
        filters: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """List records for a module with optional filtering, sorting, and pagination.

        Args:
            module_slug: The module's URL-friendly slug (e.g. ``"contacts"``).
            page: Page number (1-indexed). Defaults to ``1``.
            page_size: Number of records per page. Defaults to ``25``.
            sort_by: Field name to sort by.
            sort_dir: Sort direction (``"asc"`` or ``"desc"``).
            search: Full-text search query.
            filters: Field-level filters as ``{field_name: value}`` pairs.

        Returns:
            A dict with ``data`` (list of records) and ``meta`` (pagination info).

        Example::

            result = client.records.list("contacts", page=1, page_size=10, search="Acme")
            for record in result["data"]:
                print(record["id"])
        """
        params: Dict[str, str] = {
            "page": str(page),
            "page_size": str(page_size),
        }
        if sort_by is not None:
            params["sort_by"] = sort_by
        if sort_dir is not None:
            params["sort_dir"] = sort_dir
        if search is not None:
            params["search"] = search
        if filters:
            for field, value in filters.items():
                params[f"filter[{field}]"] = str(value)

        path = f"/{quote(module_slug, safe='')}"
        return self._client._request("GET", path, params=params)

    def get(self, module_slug: str, record_id: str) -> Dict[str, Any]:
        """Retrieve a single record by ID.

        Args:
            module_slug: The module's slug.
            record_id: The record's UUID.

        Returns:
            The record dictionary.

        Example::

            contact = client.records.get("contacts", "uuid-here")
            print(contact["data"]["email"])
        """
        path = f"/{quote(module_slug, safe='')}/{quote(record_id, safe='')}"
        result = self._client._request("GET", path)
        return result["data"]

    def create(self, module_slug: str, data: Dict[str, Any]) -> Dict[str, Any]:
        """Create a new record in the specified module.

        Args:
            module_slug: The module's slug.
            data: Field values for the new record.

        Returns:
            The created record dictionary.

        Example::

            contact = client.records.create("contacts", {
                "first_name": "Jane",
                "last_name": "Doe",
                "email": "jane@example.com",
            })
        """
        path = f"/{quote(module_slug, safe='')}"
        result = self._client._request("POST", path, json_body={"data": data})
        return result["data"]

    def update(
        self, module_slug: str, record_id: str, data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Update an existing record.

        Args:
            module_slug: The module's slug.
            record_id: The record's UUID.
            data: Field values to update (partial update).

        Returns:
            The updated record dictionary.

        Example::

            updated = client.records.update("contacts", "uuid-here", {
                "email": "new@example.com",
            })
        """
        path = f"/{quote(module_slug, safe='')}/{quote(record_id, safe='')}"
        result = self._client._request("PUT", path, json_body={"data": data})
        return result["data"]

    def delete(self, module_slug: str, record_id: str) -> Dict[str, Any]:
        """Delete a record.

        Args:
            module_slug: The module's slug.
            record_id: The record's UUID.

        Returns:
            A dict with ``id`` and ``deleted: True``.

        Example::

            result = client.records.delete("contacts", "uuid-here")
            # {"id": "uuid-here", "deleted": True}
        """
        path = f"/{quote(module_slug, safe='')}/{quote(record_id, safe='')}"
        result = self._client._request("DELETE", path)
        return result["data"]

    def list_all(
        self,
        module_slug: str,
        *,
        page_size: int = 100,
        sort_by: Optional[str] = None,
        sort_dir: Optional[str] = None,
        search: Optional[str] = None,
        filters: Optional[Dict[str, str]] = None,
    ) -> Generator[Dict[str, Any], None, None]:
        """Generator that automatically paginates through all records.

        Yields one record at a time. Uses the same query parameters as
        :meth:`list` except ``page``, which is managed internally.

        Args:
            module_slug: The module's slug.
            page_size: Records per page (higher = fewer HTTP requests). Defaults to ``100``.
            sort_by: Field name to sort by.
            sort_dir: Sort direction.
            search: Full-text search query.
            filters: Field-level filters.

        Yields:
            Individual record dictionaries.

        Example::

            for contact in client.records.list_all("contacts", page_size=50):
                print(contact["data"]["email"])
        """
        page = 1
        while True:
            result = self.list(
                module_slug,
                page=page,
                page_size=page_size,
                sort_by=sort_by,
                sort_dir=sort_dir,
                search=search,
                filters=filters,
            )
            for record in result["data"]:
                yield record

            if page >= result["meta"]["total_pages"]:
                break
            page += 1


# ---------------------------------------------------------------------------
# Main client
# ---------------------------------------------------------------------------


class OnbrixClient:
    """Onbrix CRM API client.

    Args:
        api_key: Your API key (must start with ``crm_``).
        base_url: The base URL of your Onbrix instance (no trailing slash).
        max_retries: Maximum number of retries on 429 responses. Defaults to ``3``.
        timeout: Request timeout in seconds. Defaults to ``30``.

    Example::

        from onbrix_sdk import OnbrixClient

        client = OnbrixClient("crm_your_key", "https://app.onbrix.com")

        # List contacts
        result = client.records.list("contacts")
        print(result["data"])

        # Auto-paginate through all deals
        for deal in client.records.list_all("deals"):
            print(deal)

        # Verify a webhook signature
        is_valid = OnbrixClient.verify_webhook_signature(body, sig, secret)
    """

    def __init__(
        self,
        api_key: str,
        base_url: str,
        *,
        max_retries: int = 3,
        timeout: int = 30,
    ) -> None:
        if not api_key or not isinstance(api_key, str):
            raise ValueError("OnbrixClient: api_key is required and must be a non-empty string.")
        if not base_url or not isinstance(base_url, str):
            raise ValueError("OnbrixClient: base_url is required and must be a non-empty string.")

        self._api_key = api_key
        self._base_url = base_url.rstrip("/") + "/api/v1"
        self._max_retries = max_retries
        self._timeout = timeout
        self._session = requests.Session()
        self._session.headers.update(
            {
                "X-API-Key": self._api_key,
                "Accept": "application/json",
            }
        )

        self.modules = _ModulesResource(self)
        self.records = _RecordsResource(self)

    def _request(
        self,
        method: str,
        path: str,
        *,
        params: Optional[Dict[str, str]] = None,
        json_body: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Send an authenticated request to the Onbrix API.

        Handles rate-limit retries with exponential backoff automatically.

        Args:
            method: HTTP method (GET, POST, PUT, DELETE).
            path: Path relative to ``/api/v1`` (must start with ``/``).
            params: Query string parameters.
            json_body: Request body (will be JSON-serialized).

        Returns:
            Parsed JSON response as a dictionary.

        Raises:
            OnbrixError: On any non-2xx response after retries are exhausted.
        """
        url = self._base_url + path
        last_error: Optional[OnbrixError] = None

        for attempt in range(self._max_retries + 1):
            try:
                response = self._session.request(
                    method,
                    url,
                    params=params,
                    json=json_body,
                    timeout=self._timeout,
                )
            except requests.exceptions.Timeout:
                raise OnbrixError(
                    f"Request timed out after {self._timeout}s",
                    status=0,
                    code="TIMEOUT",
                )
            except requests.exceptions.ConnectionError as exc:
                raise OnbrixError(
                    f"Network error: {exc}",
                    status=0,
                    code="NETWORK_ERROR",
                )

            # Successful response
            if response.ok:
                return response.json()

            # Parse error body
            try:
                error_body = response.json()
            except (ValueError, json.JSONDecodeError):
                error_body = None

            # Rate limit -- retry with backoff
            if response.status_code == 429 and attempt < self._max_retries:
                wait_seconds: Optional[float] = None
                reset_value = response.headers.get("X-RateLimit-Reset")
                if reset_value is not None:
                    try:
                        reset_epoch = float(reset_value)
                        wait_seconds = max(0.0, reset_epoch - time.time())
                    except (ValueError, TypeError):
                        pass

                # Fallback to exponential backoff: 1s, 2s, 4s ...
                if wait_seconds is None or wait_seconds <= 0:
                    wait_seconds = (2 ** attempt) * 1.0

                # Cap wait time at 60 seconds
                wait_seconds = min(wait_seconds, 60.0)

                time.sleep(wait_seconds)
                last_error = _build_error(
                    response.status_code, error_body, dict(response.headers)
                )
                continue

            # Non-retryable error
            raise _build_error(
                response.status_code, error_body, dict(response.headers)
            )

        # All retries exhausted for 429
        if last_error is not None:
            raise last_error
        raise RateLimitError("Rate limit exceeded after all retries", code="RATE_LIMITED")

    @staticmethod
    def verify_webhook_signature(
        payload: Union[str, bytes],
        signature: str,
        secret: str,
    ) -> bool:
        """Verify the HMAC-SHA256 signature of an incoming webhook payload.

        Args:
            payload: The raw request body as a string or bytes.
            signature: The value of the ``X-Webhook-Signature`` header
                       (e.g. ``sha256=abcdef...``).
            secret: The webhook endpoint's signing secret.

        Returns:
            ``True`` if the signature is valid, ``False`` otherwise.

        Example::

            is_valid = OnbrixClient.verify_webhook_signature(
                request.body,
                request.headers["X-Webhook-Signature"],
                os.environ["WEBHOOK_SECRET"],
            )
        """
        if not payload or not signature or not secret:
            return False

        prefix = "sha256="
        if not signature.startswith(prefix):
            return False

        received_hex = signature[len(prefix):]

        if isinstance(payload, str):
            payload_bytes = payload.encode("utf-8")
        else:
            payload_bytes = payload

        expected_hex = hmac.new(
            secret.encode("utf-8"),
            payload_bytes,
            hashlib.sha256,
        ).hexdigest()

        return hmac.compare_digest(received_hex, expected_hex)

    def close(self) -> None:
        """Close the underlying HTTP session.

        It is good practice to call this method when you are done using the
        client, or use the client as a context manager instead.

        Example::

            client = OnbrixClient("crm_key", "https://app.onbrix.com")
            try:
                # ... use client ...
            finally:
                client.close()
        """
        self._session.close()

    def __enter__(self) -> "OnbrixClient":
        return self

    def __exit__(self, *args: Any) -> None:
        self.close()

    def __repr__(self) -> str:
        return f"OnbrixClient(base_url={self._base_url!r})"
