from __future__ import annotations

import os
import time

import entropic_core


def main() -> int:
    try:
        from openai import OpenAI
    except Exception as e:
        print("Missing dependency: openai. Install with: pip install 'entropic-core[openrouter]'")
        print(str(e))
        return 2

    api_key = os.getenv("OPENROUTER_API_KEY")
    model = os.getenv("OPENROUTER_MODEL")
    if not api_key or not model:
        print("Missing env vars. Set OPENROUTER_API_KEY and OPENROUTER_MODEL.")
        return 2

    default_headers = {}
    if os.getenv("OPENROUTER_HTTP_REFERER"):
        default_headers["HTTP-Referer"] = os.getenv("OPENROUTER_HTTP_REFERER")
    if os.getenv("OPENROUTER_APP_TITLE"):
        default_headers["X-Title"] = os.getenv("OPENROUTER_APP_TITLE")

    client = OpenAI(
        api_key=api_key,
        base_url="https://openrouter.ai/api/v1",
        default_headers=default_headers or None,
    )

    # Create a middleware instance so we can read stats/call_history later.
    mw = entropic_core.create_middleware()

    # Wrap in-place (OpenRouter is OpenAI-compatible).
    entropic_core.wrap(client, provider="openrouter", middleware=mw)

    t0 = time.time()
    resp = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": "You are a concise assistant."},
            {
                "role": "user",
                "content": "Give a 1-sentence summary of what Entropic Core does for agent systems.",
            },
        ],
        temperature=0.6,
    )
    dt = (time.time() - t0) * 1000.0

    text = ""
    try:
        text = resp.choices[0].message.content or ""
    except Exception:
        text = str(resp)

    print(text.strip())
    print(f"latency_ms={dt:.1f}")
    print(mw.get_stats())
    if mw.call_history:
        print("last_interventions=" + ",".join(mw.call_history[-1].interventions_applied or []))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
