"""litellm to Asqav bridge: sign every proxied model call with a compliance receipt.

Runnable end to end. Install both packages, set your Asqav key, then run it:

    pip install litellm asqav
    ASQAV_API_KEY=sk_test_... python litellm-bridge-example.py

Use a sk_test_ key while you experiment. The example uses litellm's mock_response
so it completes without a provider key; swap the mock for a real model and the
receipt still lands on your Asqav dashboard. The two Asqav calls are the bridge:
preflight gates the call in the decision phase, sign records it in the execution
phase. Wire the same two calls into a litellm proxy CustomLogger (see the page)
to govern every request that flows through your gateway.
"""

import os

import asqav
import litellm

ACTION_TYPE = "api:llm:chat"

agent = asqav.govern(
    api_key=os.environ["ASQAV_API_KEY"],
    agent_name="litellm-bridge",
)


def governed_completion(model, messages, **kwargs):
    """Run a litellm completion wrapped in an Asqav preflight and signature."""
    # Decision phase: preflight checks agent status and org policy, fail closed.
    check = agent.preflight(ACTION_TYPE)
    if not check.cleared:
        raise PermissionError(check.explanation)

    response = litellm.completion(model=model, messages=messages, **kwargs)

    # Execution phase: sign the completed call, binding the provider response id.
    receipt = agent.sign(
        ACTION_TYPE,
        {"model": model, "provider_response_id": response.id},
        model_name=model,
        tool_name="litellm",
    )
    return response, receipt


if __name__ == "__main__":
    response, receipt = governed_completion(
        "gpt-4o-mini",
        [{"role": "user", "content": "Summarise this quarter's churn drivers."}],
        mock_response="Churn rose on onboarding friction and a pricing-tier gap.",
    )
    print("model output:", response.choices[0].message.content)
    print("receipt id:", receipt.signature_id)
    print("verify at:", receipt.verification_url)
