"""
Affiliate Aggregator — Python integration helper (sample).

API key + HMAC-SHA256 signing. Uses FAKE credentials from environment variables —
never hard-code your real secret.

    export AFF_BASE_URL="http://localhost:4100/api"
    export AFF_API_KEY="ak_test_xxx"
    export AFF_API_SECRET="sk_test_xxx"   # shown ONCE at key creation

Standard library only (urllib). Python 3.8+.
"""
import hashlib
import hmac
import json
import os
import time
import uuid
import urllib.error
import urllib.request

BASE_URL = os.environ.get("AFF_BASE_URL", "http://localhost:4100/api")
API_KEY = os.environ.get("AFF_API_KEY", "ak_test_example")
API_SECRET = os.environ.get("AFF_API_SECRET", "sk_test_example_secret")


def sign(secret: str, timestamp: str, raw_body: str) -> str:
    """Signing string is f'{timestamp}.{raw_body}'. Returns lowercase hex HMAC-SHA256."""
    return hmac.new(
        secret.encode(), f"{timestamp}.{raw_body}".encode(), hashlib.sha256
    ).hexdigest()


def signed_request(method: str, path: str, body: dict | None = None, extra_headers: dict | None = None) -> dict:
    raw = "" if body is None else json.dumps(body, separators=(",", ":"))
    ts = str(int(time.time()))
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": API_KEY,
        "X-Timestamp": ts,
        "X-Signature": sign(API_SECRET, ts, raw),
        "X-Request-ID": str(uuid.uuid4()),
    }
    if extra_headers:
        headers.update(extra_headers)

    req = urllib.request.Request(
        f"{BASE_URL}{path}",
        data=None if raw == "" else raw.encode(),
        headers=headers,
        method=method,
    )
    try:
        with urllib.request.urlopen(req) as resp:
            text = resp.read().decode()
            return json.loads(text) if text else {}
    except urllib.error.HTTPError as e:
        detail = e.read().decode()
        # 4xx/5xx — inspect the message + your API logs (errorCode) to debug.
        raise RuntimeError(f"API {e.code}: {detail}") from None


# ── Examples ──────────────────────────────────────────────────────────────────

def import_products() -> dict:
    return signed_request(
        "POST",
        "/v1/products/import",
        {
            "products": [
                {
                    "externalProductId": "SKU-100",
                    "name": "Wireless Earbuds",
                    "productUrl": "https://merchant-store.com/p/sku-100",
                    "price": "2999.00",
                    "currency": "NPR",
                    "commissionType": "PERCENTAGE",
                    "commissionValue": "10",
                }
            ]
        },
        {"X-Idempotency-Key": "import-sku-100-2026-06-14"},
    )


def report_conversion(click_id: str) -> dict:
    return signed_request(
        "POST",
        "/v1/conversions",
        {
            "clickId": click_id,
            "externalOrderId": "ORD-1001",
            "externalProductId": "SKU-100",
            "orderAmount": "2999.00",
            "currency": "NPR",
            "orderStatus": "confirmed",
        },
        {"X-Idempotency-Key": "ORD-1001-conversion"},
    )


def send_order_created_webhook() -> dict:
    # X-External-Event-Id is REQUIRED on webhooks and is the dedup anchor.
    return signed_request(
        "POST",
        "/v1/webhooks/order-created",
        {
            "click_id": "CLK_example123",
            "external_order_id": "ORD-1001",
            "order_amount": "2999.00",
            "currency": "NPR",
        },
        {"X-External-Event-Id": "evt-ORD-1001-created"},
    )


if __name__ == "__main__":
    print(report_conversion("CLK_example123"))
