from fastapi import APIRouter, Depends, Request
from ...core.permission import require_login
import httpx
from ...utils.request_utils import safe_json

router = APIRouter()


@router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def artifacts_proxy(
    path: str,
    request: Request,
    user: dict = Depends(require_login),
):
    from ...core.config import settings
    deerflow_base = settings.DEERFLOW_GATEWAY_URL

    body = None
    if request.method in ("POST", "PUT"):
        body = await safe_json(request)

    async with httpx.AsyncClient() as client:
        try:
            url = f"{deerflow_base}/api/artifacts/{path}"
            headers = {"Content-Type": "application/json"}
            res = await client.request(
                method=request.method,
                url=url,
                json=body,
                headers=headers,
                timeout=30.0,
            )
            return res.json()
        except Exception:
            return {"error": "服务不可用", "detail": "service unavailable"}


@router.get("/content")
async def get_artifacts_content(
    request: Request,
    user: dict = Depends(require_login),
):
    from ...core.config import settings
    deerflow_base = settings.DEERFLOW_GATEWAY_URL

    async with httpx.AsyncClient() as client:
        try:
            res = await client.get(f"{deerflow_base}/api/artifacts/content", timeout=10.0)
            return res.json()
        except Exception:
            return {"artifacts": []}
