"""
One-line Finault wrapper for OpenAI.

Usage:
    from finault.observe import observe_finault
    openai = observe_finault(OpenAI(), finault_key="flt_...")
"""

import functools
import hashlib
import json
import threading
import time
from typing import Optional

import httpx


def observe_finault(
    client,
    finault_key: Optional[str] = None,
    gateway_url: str = "https://api.finault.ai",
    chains: Optional[list] = None,
    customer_id: Optional[str] = None,
):
    """
    Wrap any OpenAI-compatible client with Finault sealing.
    One line. Every call gets a sealed receipt.

    Usage:
        from openai import OpenAI
        from finault.observe import observe_finault

        client = observe_finault(OpenAI(), finault_key="flt_...")
        # Every call now generates a sealed AIEI receipt
    """
    original_create = client.chat.completions.create

    @functools.wraps(original_create)
    def wrapped_create(*args, **kwargs):
        start = time.time()
        response = original_create(*args, **kwargs)
        end = time.time()

        # Fire seal asynchronously — never block the response
        threading.Thread(
            target=_seal_call,
            args=(response, kwargs, start, end, finault_key, gateway_url, chains, customer_id),
            daemon=True,
        ).start()

        return response

    client.chat.completions.create = wrapped_create
    return client


def _seal_call(response, kwargs, start, end, finault_key, gateway_url, chains, customer_id):
    try:
        usage = getattr(response, 'usage', None)
        model = getattr(response, 'model', kwargs.get('model', 'unknown'))

        seal_data = {
            "who": {
                "customerId": customer_id,
                "source": "observe_finault",
            },
            "what": {
                "model": model,
                "inputTokens": getattr(usage, 'prompt_tokens', 0) if usage else 0,
                "outputTokens": getattr(usage, 'completion_tokens', 0) if usage else 0,
                "latencyMs": int((end - start) * 1000),
            },
            "worth": {
                "revenueUsd": kwargs.get('finault_revenue_usd'),
            },
            "chains": chains or [],
        }

        headers = {"Content-Type": "application/json"}
        if finault_key:
            headers["Authorization"] = f"Bearer {finault_key}"
        if chains:
            headers["X-Finault-Chains"] = ",".join(chains)

        httpx.post(
            f"{gateway_url.rstrip('/')}/v1/seal/ingest",
            json=seal_data,
            headers=headers,
            timeout=5.0,
        )
    except Exception:
        pass  # Never block
