"""EximFetch API client for Python (single file, depends only on `requests`).

    pip install requests
    from eximfetch import EximFetch

    ef = EximFetch("YOUR_API_KEY")
    ef.get("/customs-exchange-rates", currencyCode="USD")          # one page (dict)
    for row in ef.iterate("/pin-codes", state="Tamil Nadu"):      # every record, page by page
        ...
    ef.changes(since="2026-11-16T00:00:00Z", dataset="icegate-locations")
    ef.sb_watch("INMAA1", "1234567", "2026-11-10", label="PO 4471")
    ef.export("icegate-locations", "locations.csv")               # Premium: whole dataset

Docs: https://eximfetch.com/docs
"""
from __future__ import annotations

import time
from typing import Any, Dict, Iterator, Optional

import requests

__version__ = "0.1.0"
DEFAULT_BASE_URL = "https://api.eximfetch.com"


class EximFetchError(Exception):
    """An error answer from the API: .status (HTTP code), .message, .body (parsed JSON)."""

    def __init__(self, status: int, message: str, body: Any = None):
        super().__init__(f"{status}: {message}")
        self.status = status
        self.message = message
        self.body = body


class RateLimited(EximFetchError):
    """HTTP 429: the daily limit is reached (.reset_time) or too many requests."""

    def __init__(self, status: int, message: str, body: Any = None):
        super().__init__(status, message, body)
        self.reset_time = (body or {}).get("resetTime") if isinstance(body, dict) else None


class EximFetch:
    def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 60.0, retries: int = 2, session: Optional[requests.Session] = None):
        if not api_key:
            raise ValueError("api_key is required; find it under Settings, API key")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.retries = retries
        self.session = session or requests.Session()
        self.session.headers.update({"Authorization": f"Bearer {api_key}", "Accept": "application/json", "User-Agent": f"eximfetch-python/{__version__}"})
        self.last_rate_limit: Dict[str, Optional[int]] = {"limit": None, "remaining": None, "used": None}

    # ---- low level -------------------------------------------------------------------
    def request(self, method: str, path: str, params: Optional[Dict[str, Any]] = None, json: Any = None, stream: bool = False) -> requests.Response:
        url = f"{self.base_url}/{path.lstrip('/')}"
        attempt = 0
        while True:
            res = self.session.request(method, url, params=params or None, json=json, timeout=self.timeout, stream=stream)
            for h, k in (("X-RateLimit-Limit", "limit"), ("X-RateLimit-Remaining", "remaining"), ("X-RateLimit-Used", "used")):
                if h in res.headers:
                    try:
                        self.last_rate_limit[k] = int(res.headers[h])
                    except ValueError:
                        pass
            if res.status_code in (502, 503, 504) and attempt < self.retries:
                attempt += 1
                time.sleep(1.5 * attempt)
                continue
            if res.status_code >= 400:
                try:
                    body = res.json()
                except ValueError:
                    body = res.text
                message = body.get("message", res.reason) if isinstance(body, dict) else res.reason
                if res.status_code == 429:
                    raise RateLimited(res.status_code, message, body)
                raise EximFetchError(res.status_code, message, body)
            return res

    def get(self, path: str, **params: Any) -> Dict[str, Any]:
        """One request; returns the parsed JSON envelope (success, data, pagination)."""
        return self.request("GET", path, params=params).json()

    def post(self, path: str, body: Any = None) -> Dict[str, Any]:
        return self.request("POST", path, json=body).json()

    def delete(self, path: str) -> Dict[str, Any]:
        return self.request("DELETE", path).json()

    def iterate(self, path: str, limit: int = 500, **params: Any) -> Iterator[Dict[str, Any]]:
        """Yields every record, following the pagination. Each page is one API call."""
        page = 1
        while True:
            res = self.get(path, page=page, limit=limit, **params)
            for row in res.get("data", []):
                yield row
            pg = res.get("pagination") or {}
            if not pg.get("hasNextPage"):
                return
            page += 1

    # ---- sync helpers ----------------------------------------------------------------
    def updated_since(self, path: str, since: str, **params: Any) -> Iterator[Dict[str, Any]]:
        """Records whose content changed after `since` (ISO 8601)."""
        return self.iterate(path, updatedSince=since, **params)

    def changes(self, since: Optional[str] = None, dataset: Optional[str] = None, change: Optional[str] = None, limit: int = 500) -> Iterator[Dict[str, Any]]:
        """The change log: one row per record added, changed or removed."""
        params: Dict[str, Any] = {}
        if since:
            params["since"] = since
        if dataset:
            params["dataset"] = dataset
        if change:
            params["change"] = change
        return self.iterate("/changes", limit=limit, **params)

    def status(self) -> Dict[str, Any]:
        """Public dataset status (no key needed, but harmless with one)."""
        return self.get("/status")

    # ---- Shipping Bills --------------------------------------------------------------
    def sb_status(self, location: str, sb_no: str, sb_date: str, refresh: bool = False) -> Dict[str, Any]:
        params = {"location": location, "sbNo": sb_no, "sbDate": sb_date}
        if refresh:
            params["refresh"] = "1"
        return self.get("/sb-status", **params)

    def sb_watch(self, location: str, sb_no: str, sb_date: str, label: str = "") -> Dict[str, Any]:
        return self.post("/sb-watch", {"location": location, "sbNo": sb_no, "sbDate": sb_date, "label": label})

    def sb_watch_many(self, items: list) -> Dict[str, Any]:
        """items: list of dicts with location, sbNo, sbDate and optional label (up to 50)."""
        return self.post("/sb-watch", {"items": items})

    def sb_watches(self, status: str = "active", **params: Any) -> Iterator[Dict[str, Any]]:
        return self.iterate("/sb-watch", status=status, **params)

    def sb_watch_get(self, watch_id: str) -> Dict[str, Any]:
        return self.get(f"/sb-watch/{watch_id}")

    def sb_watch_check(self, watch_id: str) -> Dict[str, Any]:
        return self.post(f"/sb-watch/{watch_id}/check")

    def sb_watch_stop(self, watch_id: str) -> Dict[str, Any]:
        return self.delete(f"/sb-watch/{watch_id}")

    def sb_seats(self) -> Dict[str, Any]:
        return self.get("/sb-watch/seats")

    # ---- bulk download ---------------------------------------------------------------
    def export(self, dataset: str, path: str, fmt: str = "csv", updated_since: Optional[str] = None) -> str:
        """Downloads a whole dataset (Premium) to `path`. fmt: csv, json or ndjson."""
        params: Dict[str, Any] = {"format": fmt}
        if updated_since:
            params["updatedSince"] = updated_since
        res = self.request("GET", f"/export/{dataset}", params=params, stream=True)
        with open(path, "wb") as fh:
            for chunk in res.iter_content(chunk_size=1 << 16):
                fh.write(chunk)
        return path
