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

router = APIRouter()


@router.get("/models")
async def get_deerflow_models(
    request: Request,
    user: dict = Depends(require_login),
):
    async with httpx.AsyncClient() as client:
        try:
            res = await client.get(f"{settings.DEERFLOW_GATEWAY_URL}/api/models", timeout=10.0)
            return res.json()
        except Exception:
            return {"models": []}


@router.post("/threads")
async def create_deerflow_thread(
    request: Request,
    user: dict = Depends(require_login),
):
    body = await safe_json(request) if request.method == "POST" else {}
    async with httpx.AsyncClient() as client:
        try:
            res = await client.post(
                f"{settings.DEERFLOW_LANGGRAPH_URL}/threads",
                json=body,
                timeout=10.0,
            )
            return res.json()
        except Exception:
            return {"error": "创建线程失败", "detail": "DeerFlow service unavailable"}


@router.get("/threads/{thread_id}/state")
async def get_deerflow_thread_state(
    thread_id: str,
    request: Request,
    user: dict = Depends(require_login),
):
    async with httpx.AsyncClient() as client:
        try:
            res = await client.get(f"{settings.DEERFLOW_LANGGRAPH_URL}/threads/{thread_id}/state", timeout=10.0)
            return res.json()
        except Exception:
            return {"error": "获取线程状态失败", "detail": "DeerFlow service unavailable"}


@router.post("/threads/{thread_id}/runs")
async def create_deerflow_run(
    thread_id: str,
    request: Request,
    user: dict = Depends(require_login),
):
    body = await safe_json(request)
    if "assistant_id" not in body:
        body["assistant_id"] = "lead_agent"

    if "config" not in body:
        body["config"] = {}
    if "configurable" not in body["config"]:
        body["config"]["configurable"] = {}
    if "scene_key" not in body["config"]["configurable"]:
        body["config"]["configurable"]["scene_key"] = "user_chat"

    async with httpx.AsyncClient(timeout=httpx.Timeout(120.0)) as client:
        try:
            res = await client.post(
                f"{settings.DEERFLOW_LANGGRAPH_URL}/threads/{thread_id}/runs",
                json=body,
                timeout=120.0,
            )
            return res.json()
        except Exception:
            return {"error": "创建运行失败", "detail": "DeerFlow service unavailable"}
