"""AfriFlux API client for Python 3.8+. Generated from https://api.afriflux.xyz/v1/openapi.json.

Docs: https://www.afriflux.xyz/api-docs

    from afriflux import AfriFlux
    afriflux = AfriFlux()  # reads AFRIFLUX_API_KEY
    answer = afriflux.freeze_check.freeze_lookup("0x...")

Every method returns the parsed JSON body. Credits used and remaining for the
last call are in afriflux.last_response.
"""

import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

__all__ = ["AfriFlux", "AfriFluxError"]

_RETRY_STATUS = {429, 500, 502, 503, 504}


def _quote(value):
    return urllib.parse.quote(str(value), safe="")


class AfriFluxError(Exception):
    """The API answered with an error. code is the API's error code, e.g. insufficient_credits."""

    def __init__(self, status, body, request_id=None):
        error = (body or {}).get("error") or {}
        super().__init__(error.get("message") or "AfriFlux API answered %s" % status)
        self.status = status
        self.code = error.get("code") or "http_error"
        self.request_id = (body or {}).get("request_id") or request_id
        self.body = body


class _WalletLabels:
    def __init__(self, client):
        self._client = client

    def label_lookup(self, chain, address, *, query=None, idempotency_key=None):
        """Look up one wallet label. GET /v1/labels/{chain}/{address}
        
        Returns who an address belongs to and what it is used for. Unmatched addresses are free; matches are charged by tier. Your balance must cover an operational match before the lookup runs."""
        return self._client.request("GET", f"/v1/labels/{_quote(chain)}/{_quote(address)}", query=query, body=None, idempotency_key=idempotency_key)

    def label_batch(self, body, *, query=None, idempotency_key=None):
        """Look up a batch of wallet labels. POST /v1/labels/batch
        
        Deduplicates identical chain/address pairs, then charges only for matches. meta.billed shows how many standard and operational matches you paid for."""
        return self._client.request("POST", f"/v1/labels/batch", query=query, body=body, idempotency_key=idempotency_key)

    def coverage(self, *, query=None, idempotency_key=None):
        """See what we cover. GET /v1/labels/coverage
        
        Lists every entity we label, its chains and the public roles we can return for it. Free. Use it to judge coverage before you spend credits."""
        return self._client.request("GET", f"/v1/labels/coverage", query=query, body=None, idempotency_key=idempotency_key)

    def usage(self, *, query=None, idempotency_key=None):
        """View account usage. GET /v1/usage
        
        Returns recent billable usage and month-to-date credit consumption. Paginate with limit and cursor; pass format=csv to download."""
        return self._client.request("GET", f"/v1/usage", query=query, body=None, idempotency_key=idempotency_key)

    def credits(self, *, query=None, idempotency_key=None):
        """View credit balance and expiry. GET /v1/credits
        
        Returns the unexpired balance and credit-lot expiry schedule."""
        return self._client.request("GET", f"/v1/credits", query=query, body=None, idempotency_key=idempotency_key)

    def health(self, *, query=None, idempotency_key=None):
        """Check API availability. GET /v1/health
        
        Confirms that the published API product and serving database are available."""
        return self._client.request("GET", f"/v1/health", query=query, body=None, idempotency_key=idempotency_key)


class _MarketData:
    def __init__(self, client):
        self._client = client

    def timeseries(self, symbol, metric, *, query=None, idempotency_key=None):
        """Query a token or universe time series. GET /v1/market-data/timeseries/{symbol}/{metric}
        
        Returns aligned period/value points from the daily snapshot pipeline. Use symbol=universe with a bare universe metric (transfer, dex, mints, burns, users) for cross-token series; otherwise metric uses the form dimension:measure where dimension is chain, dex_project, venue, mint_flow, or burn_flow. Ranges are capped per grain (daily 400, weekly 300, monthly 160, quarterly 80 most-recent points) and responses flag truncated separately from partial_last so incomplete final periods are never mistaken for complete ones.
        
        Query: grain, entity, from, to (pass as query={...})."""
        return self._client.request("GET", f"/v1/market-data/timeseries/{_quote(symbol)}/{_quote(metric)}", query=query, body=None, idempotency_key=idempotency_key)

    def token_snapshot(self, symbol, *, query=None, idempotency_key=None):
        """Latest snapshot for one token. GET /v1/market-data/tokens/{symbol}/snapshot
        
        Curated latest cut for a single token: supply, lifetime flows, holders, transfer and DEX totals, TVL, and corridor count, with as_of provenance. Accepts the manifest slug or symbol (cngn, cNGN_mento, cngn-mento)."""
        return self._client.request("GET", f"/v1/market-data/tokens/{_quote(symbol)}/snapshot", query=query, body=None, idempotency_key=idempotency_key)

    def universe_snapshot(self, *, query=None, idempotency_key=None):
        """Latest universe snapshot. GET /v1/market-data/universe/snapshot
        
        Headline KPIs, the token leaderboard, and per-chain totals for the whole tracked stablecoin universe in one call."""
        return self._client.request("GET", f"/v1/market-data/universe/snapshot", query=query, body=None, idempotency_key=idempotency_key)

    def rate_print(self, symbol, *, query=None, idempotency_key=None):
        """DEX-implied USD reference rate (preview). GET /v1/market-data/rates/{symbol}/usd
        
        Daily volume-weighted implied USD price per token across chains, floored by minimum per-chain daily volume to suppress thin-pool noise. Preview methodology: history depth follows the published DEX window and prints may restate once the canonical reference-rate pipeline ships.
        
        Query: from, to, min_day_volume_usd (pass as query={...})."""
        return self._client.request("GET", f"/v1/market-data/rates/{_quote(symbol)}/usd", query=query, body=None, idempotency_key=idempotency_key)

    def health(self, *, query=None, idempotency_key=None):
        """Check API availability. GET /v1/market-data/health
        
        Confirms that the published API product is available and identifies the serving environment."""
        return self._client.request("GET", f"/v1/market-data/health", query=query, body=None, idempotency_key=idempotency_key)


class _WalletScreening:
    def __init__(self, client):
        self._client = client

    def screen_lookup(self, chain, address, *, query=None, idempotency_key=None):
        """Screen one address. GET /v1/screen/{chain}/{address}
        
        Returns the wallet label and the freeze record for one address. Each part has its own matched flag, and you pay only for the parts that matched. A label you already paid for stays free until its valid_until."""
        return self._client.request("GET", f"/v1/screen/{_quote(chain)}/{_quote(address)}", query=query, body=None, idempotency_key=idempotency_key)

    def screen_batch(self, body, *, query=None, idempotency_key=None):
        """Screen a batch of addresses. POST /v1/screen/batch
        
        Screens many addresses at once. Duplicates count once, and you pay only for the parts that matched. Your plan sets the largest batch."""
        return self._client.request("POST", f"/v1/screen/batch", query=query, body=body, idempotency_key=idempotency_key)

    def health(self, *, query=None, idempotency_key=None):
        """Check API availability. GET /v1/screen/health
        
        Confirms the API is available and which environment answered."""
        return self._client.request("GET", f"/v1/screen/health", query=query, body=None, idempotency_key=idempotency_key)


class _Reference:
    def __init__(self, client):
        self._client = client

    def status(self, *, query=None, idempotency_key=None):
        """Reference catalog status. GET /v1/reference/status
        
        Entity counts, coverage-matrix symbols, and the as_of provenance stamp for the current snapshot."""
        return self._client.request("GET", f"/v1/reference/status", query=query, body=None, idempotency_key=idempotency_key)

    def tokens(self, *, query=None, idempotency_key=None):
        """List tracked tokens. GET /v1/reference/tokens
        
        The token master: slug (canonical join key), symbol, issuer, country, currency, status, launch date, and chains. Filterable by status, chain, or country."""
        return self._client.request("GET", f"/v1/reference/tokens", query=query, body=None, idempotency_key=idempotency_key)

    def token_detail(self, symbol, *, query=None, idempotency_key=None):
        """Resolve one token plus its coverage matrix. GET /v1/reference/tokens/{symbol}
        
        A single token master row joined with its per-section coverage states, so clients can learn which datasets exist for the token before querying other products. Accepts slug or symbol in any hyphen/underscore form."""
        return self._client.request("GET", f"/v1/reference/tokens/{_quote(symbol)}", query=query, body=None, idempotency_key=idempotency_key)

    def chains(self, *, query=None, idempotency_key=None):
        """List supported chains. GET /v1/reference/chains
        
        Chain slugs and display names usable as entity filters across all products."""
        return self._client.request("GET", f"/v1/reference/chains", query=query, body=None, idempotency_key=idempotency_key)

    def venues(self, *, query=None, idempotency_key=None):
        """List tracked venues. GET /v1/reference/venues
        
        The venue master: roles, chain and token presence, first/last active day, and lifetime USD flow. Filterable by chain or role."""
        return self._client.request("GET", f"/v1/reference/venues", query=query, body=None, idempotency_key=idempotency_key)

    def corridors(self, *, query=None, idempotency_key=None):
        """List tracked corridors. GET /v1/reference/corridors
        
        The corridor master: base/quote token pairs per chain and project with lifetime trade counts. The enumeration for corridor analytics."""
        return self._client.request("GET", f"/v1/reference/corridors", query=query, body=None, idempotency_key=idempotency_key)

    def countries(self, *, query=None, idempotency_key=None):
        """List covered countries. GET /v1/reference/countries
        
        Country slugs, names, and the tokens mapped to each currency area."""
        return self._client.request("GET", f"/v1/reference/countries", query=query, body=None, idempotency_key=idempotency_key)

    def coverage(self, *, query=None, idempotency_key=None):
        """Dataset coverage matrix. GET /v1/reference/coverage
        
        Per-token, per-section dataset availability (live, in_progress, no_coverage_yet, not_applicable). Query this before consuming any metric to avoid silent gaps."""
        return self._client.request("GET", f"/v1/reference/coverage", query=query, body=None, idempotency_key=idempotency_key)

    def health(self, *, query=None, idempotency_key=None):
        """Check API availability. GET /v1/reference/health
        
        Confirms that the published API product is available and identifies the serving environment."""
        return self._client.request("GET", f"/v1/reference/health", query=query, body=None, idempotency_key=idempotency_key)


class _FreezeCheck:
    def __init__(self, client):
        self._client = client

    def freeze_lookup(self, address, *, query=None, idempotency_key=None):
        """Check one address. GET /v1/freeze/addresses/{address}
        
        Says whether the address is on an issuer's freeze list, how many venues we track it dealt with, and whether a venue paid it after the freeze. Venues are counted, never named. Free when we hold no record. Needs a paid account."""
        return self._client.request("GET", f"/v1/freeze/addresses/{_quote(address)}", query=query, body=None, idempotency_key=idempotency_key)

    def freeze_batch(self, body, *, query=None, idempotency_key=None):
        """Check a batch of addresses. POST /v1/freeze/batch
        
        Checks many addresses at once. Duplicates count once, and you pay only for addresses we hold a record on. Your plan sets the largest batch."""
        return self._client.request("POST", f"/v1/freeze/batch", query=query, body=body, idempotency_key=idempotency_key)

    def coverage(self, *, query=None, idempotency_key=None):
        """See what we cover. GET /v1/freeze/coverage
        
        How many venues we track, on which chains, and how many frozen addresses have dealt with them. Free."""
        return self._client.request("GET", f"/v1/freeze/coverage", query=query, body=None, idempotency_key=idempotency_key)

    def health(self, *, query=None, idempotency_key=None):
        """Check API availability. GET /v1/freeze/health
        
        Confirms the API is available and which environment answered."""
        return self._client.request("GET", f"/v1/freeze/health", query=query, body=None, idempotency_key=idempotency_key)


class AfriFlux:
    def __init__(self, api_key=None, base_url="https://api.afriflux.xyz", max_retries=2, timeout=30):
        self.api_key = api_key or os.environ.get("AFRIFLUX_API_KEY")
        if not self.api_key:
            raise ValueError("Pass api_key or set AFRIFLUX_API_KEY. Test keys (af_test_...) are free.")
        self.base_url = base_url.rstrip("/")
        self.max_retries = max_retries
        self.timeout = timeout
        self.last_response = None
        self.wallet_labels = _WalletLabels(self)
        self.market_data = _MarketData(self)
        self.wallet_screening = _WalletScreening(self)
        self.reference = _Reference(self)
        self.freeze_check = _FreezeCheck(self)

    def request(self, method, path, query=None, body=None, idempotency_key=None):
        url = self.base_url + path
        params = {k: v for k, v in (query or {}).items() if v is not None}
        if params:
            url += "?" + urllib.parse.urlencode(params)
        headers = {"Authorization": "Bearer " + self.api_key, "Accept": "application/json", "User-Agent": "afriflux-python"}
        data = None
        if body is not None:
            data = json.dumps(body).encode("utf-8")
            headers["Content-Type"] = "application/json"
        # One key for every attempt, so a retried POST is charged once.
        if method == "POST":
            headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
        attempt = 0
        while True:
            request = urllib.request.Request(url, data=data, headers=headers, method=method)
            try:
                with urllib.request.urlopen(request, timeout=self.timeout) as response:
                    return self._finish(response.status, response.headers, response.read())
            except urllib.error.HTTPError as error:
                status, response_headers, raw = error.code, error.headers, error.read()
            except (urllib.error.URLError, TimeoutError):
                if attempt < self.max_retries:
                    time.sleep(0.5 * 2 ** attempt)
                    attempt += 1
                    continue
                raise
            if status in _RETRY_STATUS and attempt < self.max_retries:
                retry_after = response_headers.get("Retry-After")
                time.sleep(float(retry_after) if retry_after and retry_after.replace(".", "", 1).isdigit() else 0.5 * 2 ** attempt)
                attempt += 1
                continue
            self._finish(status, response_headers, raw)

    def _finish(self, status, headers, raw):
        try:
            body = json.loads(raw.decode("utf-8")) if raw else None
        except ValueError:
            body = {"error": {"code": "invalid_response", "message": raw[:200].decode("utf-8", "replace")}}

        def number(name):
            value = headers.get(name)
            return None if value is None else int(float(value))

        self.last_response = {
            "status": status,
            "request_id": (body or {}).get("request_id") if isinstance(body, dict) else None,
            "credits_used": number("X-AfriFlux-Credits-Used"),
            "credits_remaining": number("X-AfriFlux-Credits-Remaining"),
        }
        if 200 <= status < 300:
            return body
        raise AfriFluxError(status, body if isinstance(body, dict) else None, self.last_response["request_id"])
