# Python 3, standard library only. Run on your server; never log the API key.
import json
import os
import uuid
from urllib.parse import urlsplit, urlencode
from urllib.request import Request, build_opener, HTTPRedirectHandler
from urllib.error import HTTPError

class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

class MereuAPIError(Exception):
    def __init__(self, status, code, request_id=None, retry_after=None):
        super().__init__(code)
        self.status, self.code = status, code
        self.request_id, self.retry_after = request_id, retry_after

class MereuClient:
    def __init__(self, base_url, api_key):
        base = urlsplit(base_url)
        if (base.scheme != 'https' or base.username or base.password or base.query
                or base.fragment or not base.path.endswith('/api/v1')):
            raise ValueError('Use a clean HTTPS API base URL ending in /api/v1')
        if not api_key:
            raise ValueError('API key required')
        self.base, self.key = base_url.rstrip('/'), api_key
        self.opener = build_opener(NoRedirect())

    def request(self, method, path, body=None, operation_id=None, query=None):
        import re
        if not re.fullmatch(r'/[a-zA-Z0-9/{}_\-]+', path):
            raise ValueError('Use a relative API resource path')
        writes = method != 'GET' and path != '/cards/resolve'
        headers = {'Authorization': 'Bearer ' + self.key, 'Accept': 'application/json'}
        if writes:
            # Persist this UUID and the exact payload BEFORE sending; no automatic retry.
            headers['Idempotency-Key'] = str(uuid.UUID(operation_id))
        payload = None if body is None else json.dumps(body, separators=(',', ':')).encode()
        if payload is not None:
            headers['Content-Type'] = 'application/json'
        url = self.base + path + (('?' + urlencode(query)) if query else '')
        req = Request(url, data=payload, headers=headers, method=method)
        try:
            with self.opener.open(req, timeout=15) as response:
                return json.load(response)
        except HTTPError as error:
            try:
                code = json.load(error).get('error', {}).get('code', 'API_ERROR')
            except (ValueError, AttributeError):
                code = 'INVALID_RESPONSE'
            raise MereuAPIError(error.code, code, error.headers.get('X-Request-Id'),
                                error.headers.get('Retry-After')) from None

if __name__ == '__main__':
    api = MereuClient(os.environ['MEREU_API_URL'], os.environ['MEREU_API_KEY'])
    # Query example (do not print customer contact data):
    # page = api.request('GET', '/data/cards', query={'mode': 'snapshot', 'limit': 100})
    # changes = api.request('GET', '/data/cards', query={'mode': 'changes', 'cursor': saved_cursor})
    # Safe read only; customer data and credentials are not printed.
    account = api.request('GET', '/account')['data']
    print('Connected. Currency:', account['base_currency'])
