from fastapi import Request
from fastapi.responses import JSONResponse
from uaal.evidence import record_decision
from uaal.policy import get_policy
import json

async def uaal_gate(request: Request, call_next):
    if request.url.path.startswith("/agent/act"):
        body_bytes = await request.body()
        body = json.loads(body_bytes or "{}")

        policy_version = body.get("policy_version")
        if not policy_version:
            return JSONResponse(
                status_code=403,
                content={"detail": "UAAL BLOCKED: policy_version required"}
            )

        policy = get_policy(policy_version)
        if not policy:
            return JSONResponse(
                status_code=403,
                content={"detail": "UAAL BLOCKED: unknown policy version"}
            )

        inputs = body.get("inputs", {})

        if inputs.get("score", 0) < policy["min_score"]:
            outcome = "rejected"
        elif inputs.get("util", 1) > policy["max_util"]:
            outcome = "rejected"
        else:
            outcome = "approved"

        try:
            record_decision(
                inputs=inputs,
                outcome=outcome,
                confidence=body.get("confidence", 0.0)
            )
        except Exception as e:
            return JSONResponse(
                status_code=403,
                content={"detail": f"UAAL BLOCKED ACTION: {str(e)}"}
            )

        async def receive():
            return {"type": "http.request", "body": body_bytes}

        request._receive = receive

    return await call_next(request)
