"""
Hugging Face Inference: scan user text, then call the Inference API.

This sample uses the text-generation style `inputs` field (common for many models).
If your deployment exposes an **OpenAI-compatible** `/v1/chat/completions` endpoint,
use integrations/openai_chat.py instead and point the proxy upstream at that URL.

Prerequisites:
  Install the supplied Guard Dog wheel; see README.txt.
  pip install huggingface_hub httpx

Environment:
  HF_TOKEN — Hugging Face access token with inference rights
  HF_MODEL — model id, default meta-llama/Llama-3.2-1B-Instruct (change to a model you can run)

Run:
  set HF_TOKEN=hf_...
  python samples/integrations/huggingface_inference.py
"""
from __future__ import annotations

import os
import sys

_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if _ROOT not in sys.path:
    sys.path.insert(0, _ROOT)

from guard_dog.scanner import ScanConfig, scan


def main() -> None:
    import httpx

    token = os.environ.get("HF_TOKEN", "")
    if not token:
        print("Set HF_TOKEN.")
        sys.exit(1)

    model = os.environ.get("HF_MODEL", "meta-llama/Llama-3.2-1B-Instruct")
    user_text = os.environ.get("HF_INPUT", "What is 2+2? One sentence.")

    cfg = ScanConfig.high_fidelity()
    s = scan(user_text, config=cfg)
    if s.risk_score >= float(os.environ.get("GUARD_DOG_GATEWAY_RISK_THRESHOLD", "0.5")) or not s.is_clean:
        print("Blocked locally by scan:", s.risk_score, s.issues[:5])
        sys.exit(2)

    # Router API (serverless inference) — endpoint shape may vary by model/provider
    url = f"https://router.huggingface.co/hf-inference/models/{model}"
    headers = {"Authorization": f"Bearer {token}"}
    with httpx.Client(timeout=120.0) as client:
        r = client.post(url, json={"inputs": user_text, "parameters": {"max_new_tokens": 64}}, headers=headers)
    print("status", r.status_code)
    print(r.text[:2000])


if __name__ == "__main__":
    main()
