"""
Jitsi Reverse Proxy

Leitet Anfragen an den internen Jitsi-Web Container weiter,
sodass Jitsi über Port 8000 erreichbar ist.
"""

import httpx
from fastapi import APIRouter, Request, Response
from fastapi.responses import StreamingResponse
import os

router = APIRouter()

JITSI_INTERNAL_URL = os.getenv("JITSI_INTERNAL_URL", "http://jitsi-web:80")

# HTTP Client mit längeren Timeouts für Streaming
client = httpx.AsyncClient(
    base_url=JITSI_INTERNAL_URL,
    timeout=httpx.Timeout(30.0, connect=10.0),
    follow_redirects=True
)


@router.api_route("/jitsi/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD"])
async def proxy_jitsi(request: Request, path: str):
    """
    Proxy all requests to Jitsi Web container.

    This allows accessing Jitsi through the main backend port (8000)
    instead of a separate port (8443).
    """
    # Build target URL
    url = f"/{path}"
    if request.query_params:
        url += f"?{request.query_params}"

    # Forward headers (except Host)
    headers = dict(request.headers)
    headers.pop("host", None)
    headers.pop("content-length", None)

    # Get request body if present
    body = await request.body() if request.method in ["POST", "PUT"] else None

    try:
        # Forward request to Jitsi
        response = await client.request(
            method=request.method,
            url=url,
            headers=headers,
            content=body
        )

        # Build response headers
        response_headers = dict(response.headers)
        # Remove headers that shouldn't be forwarded
        for header in ["content-encoding", "content-length", "transfer-encoding"]:
            response_headers.pop(header, None)

        return Response(
            content=response.content,
            status_code=response.status_code,
            headers=response_headers,
            media_type=response.headers.get("content-type")
        )

    except httpx.ConnectError:
        return Response(
            content="Jitsi service not available. Please start with: docker compose up -d jitsi-web",
            status_code=503,
            media_type="text/plain"
        )
    except Exception as e:
        return Response(
            content=f"Proxy error: {str(e)}",
            status_code=502,
            media_type="text/plain"
        )


@router.get("/jitsi-status")
async def jitsi_status():
    """Check if Jitsi is available."""
    try:
        response = await client.get("/")
        return {
            "status": "available",
            "internal_url": JITSI_INTERNAL_URL
        }
    except Exception as e:
        return {
            "status": "unavailable",
            "error": str(e),
            "internal_url": JITSI_INTERNAL_URL
        }
