"""
Auth middleware: request logging (ASCII-safe for Windows cp1252).
Auth dependency: Bearer token guard.
"""

import time
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from app.utils.jwt import verify_token
from app.utils.logger import log

_bearer = HTTPBearer()


def require_auth(creds: HTTPAuthorizationCredentials = Depends(_bearer)) -> str:
    """FastAPI dependency — inject into any protected route."""
    return verify_token(creds.credentials)


class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        t    = time.time()
        resp = await call_next(request)
        ms   = int((time.time() - t) * 1000)
        # Use ASCII arrow '->' instead of Unicode '->' to avoid Windows cp1252 crash
        log.info("%s %s -> %s (%dms)", request.method, request.url.path, resp.status_code, ms)

        # Prevent the browser from serving stale HTML/JS/CSS after an update.
        path = request.url.path
        if path == "/" or path.endswith((".html", ".js", ".css")) or path.startswith("/static"):
            resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            resp.headers["Pragma"] = "no-cache"
            resp.headers["Expires"] = "0"
        return resp
