"""Delfica Python SDK (basico).

Uso:
    from delfica_sdk import DelficaClient

    client = DelficaClient(
        base_url="https://api.delfica.com.br/v1",
        token="seu_token_aqui",
    )

    # Listar faturas
    invoices = client.invoices.list(limit=10)

    # Criar cliente
    customer = client.customers.create({
        "name": "Acme Corp",
        "cnpj_cpf": "12345678000100",
        "email": "contato@acme.com",
    })
"""

from __future__ import annotations

import urllib.parse as _urlparse

import httpx


class DelficaError(Exception):
    pass


class _Resource:
    def __init__(self, client: "DelficaClient", path: str):
        self.client = client
        self.path = path

    def list(self, **params) -> dict:
        return self.client._request("GET", self.path, params=params)

    def get(self, item_id: int) -> dict:
        return self.client._request("GET", f"{self.path}/{item_id}")

    def create(self, payload: dict) -> dict:
        return self.client._request("POST", self.path, json=payload)

    def update(self, item_id: int, payload: dict) -> dict:
        return self.client._request(
            "PUT", f"{self.path}/{item_id}", json=payload,
        )


class DelficaClient:
    """Cliente Python para a API REST da Delfica."""

    def __init__(
        self,
        base_url: str,
        token: str,
        *,
        timeout: float = 30.0,
    ):
        self.base_url = base_url.rstrip("/")
        self.token = token
        self.timeout = timeout
        self._session = httpx.Client(
            timeout=timeout,
            headers={"Authorization": f"Bearer {token}"},
        )
        # Resource accessors
        self.invoices = _Resource(self, "/invoices")
        self.customers = _Resource(self, "/customers")
        self.products = _Resource(self, "/products")

    def _request(self, method: str, path: str, **kwargs) -> dict:
        url = f"{self.base_url}{path}"
        try:
            resp = self._session.request(method, url, **kwargs)
            resp.raise_for_status()
            return resp.json() if resp.content else {}
        except httpx.HTTPStatusError as exc:
            raise DelficaError(
                f"HTTP {exc.response.status_code}: "
                f"{exc.response.text[:200]}",
            ) from exc

    def close(self):
        self._session.close()
