import os
from fastapi import Request
from .client import Gatekeeper

class StanleyFastAPIMiddleware:
    def __init__(self, app, client_id: str, secret: str, bunker_url: str):
        self.app = app
        self.gk = Gatekeeper(bunker_url=bunker_url, secret=secret)
        # We store it in an instance variable rather than just os.environ
        # to prevent collision if multiple apps run on one server
        self.client_id = client_id 

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        request = Request(scope, receive)
        
        # Capture IP properly (handling Proxies/Load Balancers)
        forwarded = request.headers.get("x-forwarded-for")
        client_ip = forwarded.split(",")[0] if forwarded else (request.client.host if request.client else "127.0.0.1")

        context = {
            "ip": client_ip,
            "userAgent": request.headers.get("user-agent", "unknown"),
            "path": request.url.path,
            "method": request.method
        }
        
        # Add to scope state so it survives throughout the request lifecycle
        if "state" not in scope:
            scope["state"] = {}
            
        scope["state"]["stanley"] = self.gk
        scope["state"]["stanley_context"] = context
        scope["state"]["stanley_client_id"] = self.client_id
        
        await self.app(scope, receive, send)