"""
DSMS Gateway — shared FastAPI dependencies and IPFS helper coroutines.
"""

from typing import Optional

import httpx
from fastapi import Header, HTTPException

from config import IPFS_API_URL


async def verify_token(authorization: Optional[str] = Header(None)) -> dict:
    """Verifiziert JWT Token (vereinfacht für MVP)"""
    if not authorization:
        raise HTTPException(status_code=401, detail="Authorization header fehlt")

    # In Produktion: JWT validieren
    # Für MVP: Einfache Token-Prüfung
    if not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Ungültiges Token-Format")

    return {"valid": True}


async def ipfs_add(content: bytes, pin: bool = True) -> dict:
    """Fügt Inhalt zu IPFS hinzu"""
    async with httpx.AsyncClient(timeout=60.0) as client:
        files = {"file": ("document", content)}
        params = {"pin": str(pin).lower()}

        response = await client.post(
            f"{IPFS_API_URL}/api/v0/add",
            files=files,
            params=params
        )

        if response.status_code != 200:
            raise HTTPException(
                status_code=502,
                detail=f"IPFS Fehler: {response.text}"
            )

        return response.json()


async def ipfs_cat(cid: str) -> bytes:
    """Liest Inhalt von IPFS"""
    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(
            f"{IPFS_API_URL}/api/v0/cat",
            params={"arg": cid}
        )

        if response.status_code != 200:
            raise HTTPException(
                status_code=404,
                detail=f"Dokument nicht gefunden: {cid}"
            )

        return response.content


async def ipfs_pin_ls() -> list:
    """Listet alle gepinnten Objekte"""
    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.post(
            f"{IPFS_API_URL}/api/v0/pin/ls",
            params={"type": "recursive"}
        )

        if response.status_code != 200:
            return []

        data = response.json()
        return list(data.get("Keys", {}).keys())
