"""
Guard Dog multi-provider LLM gateway (reference implementation).

Scans inbound JSON for user-controlled text, then forwards the raw body upstream.

Routes:
  POST /v1/chat/completions  — OpenAI-compatible (OpenAI, OpenRouter, LiteLLM proxy, HF routers, etc.)
  POST /v1/messages        — Anthropic Messages API

Environment (see samples/config/proxy.env.example):
  UPSTREAM_OPENAI_BASE, OPENAI_API_KEY
  UPSTREAM_ANTHROPIC_BASE, ANTHROPIC_API_KEY
  ANTHROPIC_VERSION (optional, default 2023-06-01)
  LISTEN_HOST, PORT, GUARD_DOG_GATEWAY_RISK_THRESHOLD
  GATEWAY_MAX_BODY_BYTES (optional, default 1_000_000)
  GUARD_DOG_SCAN_PRESET — balanced | high_fidelity | strict | agent, or any
                          guard_dog breed (malinois ... labrador; default balanced)

Streaming: requests with \"stream\": true are rejected with 400 so prompts are not
forwarded without a full-body scan.

Run from repo root:
  pip install fastapi uvicorn httpx
  Install the supplied Guard Dog wheel; see README.txt.
  set UPSTREAM_OPENAI_BASE=https://api.openai.com/v1
  set OPENAI_API_KEY=sk-...
  python samples/proxy/gateway_multi_provider.py
"""
from __future__ import annotations

import json
import os
import sys
import uuid
from contextlib import asynccontextmanager
from typing import Dict, List, Optional, Tuple

# Include the bundle root for the local sample workflow.
_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
if _ROOT not in sys.path:
    sys.path.insert(0, _ROOT)

import httpx
from fastapi import FastAPI, Request, Response
from fastapi.responses import JSONResponse

from guard_dog.enforcement import (
    MessageRolePolicy,
    extract_user_texts_from_anthropic_messages,
    extract_user_texts_from_openai_messages,
    validate_anthropic_message_roles,
    validate_openai_message_roles,
)
from guard_dog.conversation_event import (
    ConversationEventContext,
    ConversationEventError,
    EVENT_TENANT_AUTHORITY_CONFLICT,
    build_conversation_turn_event_v3,
    build_event_context,
    canonical_tenant_id,
    canonical_workload_identity,
    conversation_event_topic_v3,
    event_publish_mode,
    validate_policy_bundle_version,
)
from guard_dog.kafka_producer import (
    configure_from_environment,
    publish_conversation_event_v3,
    verify_configured_kafka_topic,
)
from guard_dog.scanner import ScanConfig, scan
from guard_dog.stateless_telemetry import StatelessConversationEventPublisher

UPSTREAM_OPENAI = os.environ.get("UPSTREAM_OPENAI_BASE", "").rstrip("/")
OPENAI_KEY = os.environ.get("OPENAI_API_KEY", "")

UPSTREAM_ANTHROPIC = os.environ.get("UPSTREAM_ANTHROPIC_BASE", "https://api.anthropic.com").rstrip("/")
ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
ANTHROPIC_VERSION = os.environ.get("ANTHROPIC_VERSION", "2023-06-01")

RISK_THRESHOLD = float(os.environ.get("GUARD_DOG_GATEWAY_RISK_THRESHOLD", "0.5"))
MAX_BODY = int(os.environ.get("GATEWAY_MAX_BODY_BYTES", "1000000"))
ROLE_POLICY = MessageRolePolicy()
_event_producer_configured = False
_event_publisher: Optional[StatelessConversationEventPublisher] = None

# Legacy preset classmethod names still work; any guard_dog breed name
# (BREED_NAMES) resolves through guard_dog.breeds.resolve_breed.
_SCAN_PRESETS = {
    "balanced": ScanConfig.balanced,
    "high_fidelity": ScanConfig.high_fidelity,
    "strict": ScanConfig.strict,
    "agent": ScanConfig.agent,
}


def _scan_config_from_env() -> ScanConfig:
    raw = os.environ.get("GUARD_DOG_SCAN_PRESET", "balanced").strip().lower()
    factory = _SCAN_PRESETS.get(raw)
    if factory is not None:
        return factory()
    try:
        from guard_dog.breeds import resolve_breed

        return resolve_breed(raw)
    except ImportError:
        pass
    except ValueError:
        pass
    print(
        "Unknown GUARD_DOG_SCAN_PRESET={!r}; using balanced. "
        "(Valid: {} or any guard_dog breed)".format(
            raw, ", ".join(sorted(_SCAN_PRESETS))
        ),
        file=sys.stderr,
    )
    return ScanConfig.balanced()

@asynccontextmanager
async def _lifespan(_app):
    if event_publish_mode() != "disabled":
        _ensure_event_producer_configured()
    yield


app = FastAPI(
    title="Guard Dog Multi-Provider Gateway", version="1.1.0", lifespan=_lifespan
)

try:
    from guard_dog import __version__ as GUARD_DOG_VERSION
except Exception:
    GUARD_DOG_VERSION = "unknown"


def _scan_metadata_from_request(request: Request) -> Dict[str, str]:
    """Headers for multi-turn scan metadata (Kafka optional)."""
    meta: Dict[str, str] = {}
    conversation_id = (
        request.headers.get("X-Guard-Dog-Conversation-Id")
        or request.headers.get("X-Conversation-Id")
        or ""
    ).strip()
    trace_id = (request.headers.get("X-Guard-Dog-Trace-Id") or "").strip()
    if conversation_id:
        meta["conversation_id"] = conversation_id
    if trace_id:
        meta["trace_id"] = trace_id
    return meta


@app.get("/health")
async def health():
    telemetry = (
        _event_publisher.status()
        if _event_publisher is not None
        else {
            "mode": event_publish_mode(),
            "started": event_publish_mode() == "disabled",
            "ready": event_publish_mode() == "disabled",
            "degraded": False,
            "disk_spool": False,
        }
    )
    payload = {
        "status": "ok" if telemetry["ready"] else "degraded",
        "guard_dog_version": GUARD_DOG_VERSION,
        "telemetry": telemetry,
    }
    status_code = (
        503
        if telemetry.get("mode") == "required" and not telemetry["ready"]
        else 200
    )
    return JSONResponse(payload, status_code=status_code)


def _reject_streaming(payload: dict) -> Optional[Response]:
    if payload.get("stream") is True:
        return Response(
            content=json.dumps(
                {
                    "error": "streaming_not_supported",
                    "detail": "Set stream=false for gateway scanning; streamed bodies are not scanned per chunk.",
                }
            ),
            status_code=400,
            media_type="application/json",
        )
    return None


def _ensure_event_producer_configured() -> None:
    global _event_producer_configured, _event_publisher
    if _event_producer_configured:
        return
    mode = event_publish_mode()
    _event_publisher = StatelessConversationEventPublisher(
        mode,
        topic=conversation_event_topic_v3(),
        publish=lambda event, *, authoritative_tenant_id: publish_conversation_event_v3(
            event, authoritative_tenant_id=authoritative_tenant_id
        ),
        configure=lambda: configure_from_environment(background_sender=False),
        probe=verify_configured_kafka_topic,
    )
    _event_publisher.startup()
    _event_producer_configured = True


def _gateway_event_contexts(
    request: Request,
    count: int,
    scan_direction: str,
) -> Tuple[str, List[ConversationEventContext], Optional[Dict[str, str]]]:
    mode = event_publish_mode()
    if mode == "disabled" or count == 0:
        return mode, [], None

    tenant_id = (os.environ.get("GUARD_DOG_AUTH_TENANT_ID") or "").strip()
    workload_id = (os.environ.get("GUARD_DOG_AUTH_WORKLOAD_ID") or "").strip()
    workload_type = (
        os.environ.get("GUARD_DOG_AUTH_WORKLOAD_TYPE") or ""
    ).strip()
    policy_version = (
        os.environ.get("GUARD_DOG_POLICY_BUNDLE_VERSION") or ""
    ).strip()
    if not tenant_id or not workload_id or not workload_type or not policy_version:
        raise ConversationEventError(
            "CONVERSATION_EVENT_CONTEXT_INVALID",
            "gateway event authority is not configured",
        )
    authoritative_tenant = canonical_tenant_id(tenant_id)
    workload = canonical_workload_identity(workload_type, workload_id)
    policy_version = validate_policy_bundle_version(policy_version)
    reported_tenant = (request.headers.get("X-Guard-Dog-Tenant") or "").strip()
    if reported_tenant:
        try:
            if canonical_tenant_id(reported_tenant) != authoritative_tenant:
                raise ConversationEventError(EVENT_TENANT_AUTHORITY_CONFLICT)
        except ConversationEventError as exc:
            raise ConversationEventError(
                EVENT_TENANT_AUTHORITY_CONFLICT
            ) from exc

    base_event_id = request.headers.get("X-Guard-Dog-Event-Id")
    conversation_id = request.headers.get("X-Guard-Dog-Conversation-Id")
    trace_id = request.headers.get("X-Guard-Dog-Trace-Id")
    raw_turn = request.headers.get("X-Guard-Dog-Turn-Index")
    if not base_event_id or not conversation_id or not trace_id or raw_turn is None:
        raise ConversationEventError(
            "CONVERSATION_EVENT_CONTEXT_INVALID",
            "gateway event headers are required",
        )
    try:
        base_uuid = uuid.UUID(base_event_id)
        base_turn = int(raw_turn)
    except (TypeError, ValueError, OverflowError) as exc:
        raise ConversationEventError(
            "CONVERSATION_EVENT_CONTEXT_INVALID",
            "gateway event headers are invalid",
        ) from exc

    contexts: List[ConversationEventContext] = []
    for index in range(count):
        item_event_id = (
            base_uuid
            if count == 1
            else uuid.uuid5(base_uuid, "guard-dog-boundary-item:{}".format(index))
        )
        contexts.append(
            build_event_context(
                event_id=item_event_id,
                conversation_id=conversation_id,
                trace_id=trace_id,
                turn_index=base_turn + index,
                role="user",
                scan_direction=scan_direction,
            )
        )
    return mode, contexts, {
        "tenant_id": authoritative_tenant,
        "workload_id": workload["id"],
        "workload_type": workload["type"],
        "policy_bundle_version": policy_version,
    }


def _emission_summary(emissions: List[Dict[str, str]]) -> str:
    if not emissions:
        return "disabled"
    states = {item.get("state", "failed") for item in emissions}
    return next(iter(states)) if len(states) == 1 else "mixed"


def _scan_chunks(
    chunks: tuple,
    cfg: ScanConfig,
    request: Request,
) -> Tuple[Optional[Response], List[Dict[str, str]]]:
    try:
        mode, contexts, authority = _gateway_event_contexts(
            request, len(chunks), "input"
        )
    except ConversationEventError as exc:
        status = 409 if exc.reason_code == EVENT_TENANT_AUTHORITY_CONFLICT else 400
        if exc.reason_code == "CONVERSATION_EVENT_CONFIG_INVALID":
            status = 503
        return (
            Response(
                content=json.dumps({"error": exc.reason_code}),
                status_code=status,
                media_type="application/json",
            ),
            [],
        )

    emissions: List[Dict[str, str]] = []
    scan_meta = _scan_metadata_from_request(request)
    for index, chunk in enumerate(chunks):
        r = scan(chunk, metadata=scan_meta, config=cfg)
        if contexts:
            try:
                event = build_conversation_turn_event_v3(
                    context=contexts[index],
                    authoritative_tenant_id=authority["tenant_id"],
                    workload_type=authority["workload_type"],
                    workload_id=authority["workload_id"],
                    content=chunk,
                    scan_result=r,
                    config=cfg,
                    policy_bundle_version=authority["policy_bundle_version"],
                )
                _ensure_event_producer_configured()
                publish_result = (
                    _event_publisher.publish(
                        event,
                        authoritative_tenant_id=authority["tenant_id"],
                    )
                    if _event_publisher is not None
                    else publish_conversation_event_v3(
                        event,
                        authoritative_tenant_id=authority["tenant_id"],
                    )
                )
                emission = publish_result.to_dict()
            except (ConversationEventError, RuntimeError):
                emission = {
                    "state": "failed",
                    "event_id": contexts[index].event_id,
                    "reason_code": "EVENT_PUBLISH_FAILED",
                }
            emissions.append(emission)
            if mode == "required" and emission["state"] != "published":
                return (
                    Response(
                        content=json.dumps(
                            {
                                "error": emission.get("reason_code")
                                or "EVENT_PUBLISH_FAILED",
                                "event_emission": emission,
                            }
                        ),
                        status_code=503,
                        media_type="application/json",
                    ),
                    emissions,
                )

        if r.risk_score >= RISK_THRESHOLD or not r.is_clean:
            return (
                Response(
                    content=json.dumps(
                        {
                            "error": "guard_dog_blocked",
                            "risk_score": r.risk_score,
                            "issues": r.issues[:20],
                            "event_emission": (
                                emissions[-1]
                                if emissions
                                else {"state": "disabled"}
                            ),
                        }
                    ),
                    status_code=422,
                    media_type="application/json",
                ),
                emissions,
            )
    return None, emissions


def _reject_role_violations(issues: list) -> Optional[Response]:
    if not issues:
        return None
    return Response(
        content=json.dumps({
            "error": "guard_dog_role_policy",
            "issues": issues[:ROLE_POLICY.max_violations],
        }),
        status_code=422,
        media_type="application/json",
    )


@app.post("/v1/chat/completions")
async def proxy_openai_chat(request: Request):
    if not UPSTREAM_OPENAI or not OPENAI_KEY:
        return Response(
            content=json.dumps(
                {"error": "UPSTREAM_OPENAI_BASE and OPENAI_API_KEY are required for this route"}
            ),
            status_code=500,
            media_type="application/json",
        )
    body = await request.body()
    if len(body) > MAX_BODY:
        return Response(content=json.dumps({"error": "payload too large"}), status_code=413, media_type="application/json")
    try:
        payload = json.loads(body.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        return Response(content=json.dumps({"error": "invalid json"}), status_code=400, media_type="application/json")

    bad = _reject_streaming(payload)
    if bad:
        return bad

    bad = _reject_role_violations(
        validate_openai_message_roles(payload, ROLE_POLICY)
    )
    if bad:
        return bad

    cfg = _scan_config_from_env()
    blocked, event_emissions = _scan_chunks(
        extract_user_texts_from_openai_messages(payload), cfg, request
    )
    if blocked:
        return blocked

    async with httpx.AsyncClient(timeout=120.0) as client:
        resp = await client.post(
            f"{UPSTREAM_OPENAI}/chat/completions",
            content=body,
            headers={
                "Authorization": f"Bearer {OPENAI_KEY}",
                "Content-Type": request.headers.get("content-type", "application/json"),
            },
        )
    response = Response(
        content=resp.content,
        status_code=resp.status_code,
        media_type=resp.headers.get("content-type", "application/json"),
    )
    response.headers["X-Guard-Dog-Event-Emission"] = _emission_summary(
        event_emissions
    )
    return response


@app.post("/v1/messages")
async def proxy_anthropic_messages(request: Request):
    if not ANTHROPIC_KEY:
        return Response(
            content=json.dumps({"error": "ANTHROPIC_API_KEY is required for this route"}),
            status_code=500,
            media_type="application/json",
        )
    body = await request.body()
    if len(body) > MAX_BODY:
        return Response(content=json.dumps({"error": "payload too large"}), status_code=413, media_type="application/json")
    try:
        payload = json.loads(body.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        return Response(content=json.dumps({"error": "invalid json"}), status_code=400, media_type="application/json")

    bad = _reject_streaming(payload)
    if bad:
        return bad

    bad = _reject_role_violations(
        validate_anthropic_message_roles(payload, ROLE_POLICY)
    )
    if bad:
        return bad

    cfg = _scan_config_from_env()
    blocked, event_emissions = _scan_chunks(
        extract_user_texts_from_anthropic_messages(payload), cfg, request
    )
    if blocked:
        return blocked

    # Forward client anthropic-version if present, else env default
    anthropic_ver = request.headers.get("anthropic-version") or ANTHROPIC_VERSION

    async with httpx.AsyncClient(timeout=120.0) as client:
        resp = await client.post(
            f"{UPSTREAM_ANTHROPIC}/v1/messages",
            content=body,
            headers={
                "x-api-key": ANTHROPIC_KEY,
                "anthropic-version": anthropic_ver,
                "Content-Type": request.headers.get("content-type", "application/json"),
            },
        )
    response = Response(
        content=resp.content,
        status_code=resp.status_code,
        media_type=resp.headers.get("content-type", "application/json"),
    )
    response.headers["X-Guard-Dog-Event-Emission"] = _emission_summary(
        event_emissions
    )
    return response


if __name__ == "__main__":
    import uvicorn

    host = os.environ.get("LISTEN_HOST", "127.0.0.1")
    port = int(os.environ.get("PORT", "8090"))
    uvicorn.run(app, host=host, port=port)
