from fastapi import APIRouter, Depends, Request
from ...core.database import get_db
from ...core.permission import require_login
from ...core.config import settings
import os

router = APIRouter()


@router.get("")
async def get_chat_capabilities(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_db),
):
    """获取当前用户对话场景的模型能力配置

    返回模型是否支持视觉能力，前端据此决定允许上传的文件类型。
    """
    conn, cur = db

    # 1. 检查 system_config 中的 model_selection_source
    await cur.execute(
        "SELECT config_value FROM system_configs WHERE config_key = 'model_selection_source'"
    )
    row = await cur.fetchone()
    source = row["config_value"] if row else "config_yaml"

    supports_vision = False
    model_name = ""
    provider_name = ""

    # 优先检查 vision_model 场景是否配置了可用模型
    await cur.execute(
        "SELECT config_value FROM system_configs WHERE config_key = 'ai_scene_vision_model'"
    )
    vision_row = await cur.fetchone()
    if vision_row:
        try:
            import json
            vision_config = json.loads(vision_row["config_value"])
            vision_enabled = vision_config.get("enabled", False)
            vision_api_base = vision_config.get("api_base", "")
            vision_api_key = vision_config.get("api_key", "")
            vision_model_val = vision_config.get("model", "")
            if vision_enabled and vision_api_base and vision_model_val:
                # api_key 可能为空（某些本地模型不需要）
                supports_vision = True
                model_name = vision_model_val
                provider_name = vision_config.get("provider", "")
        except Exception:
            pass

    # 如果 vision_model 未配置，回退检查 user_chat 场景的模型是否支持视觉
    if not supports_vision and source == "bff_api":
        # 从 BFF API 动态配置中查询 user_chat 场景的模型
        await cur.execute(
            """SELECT m.model_name, m.display_name, m.provider_name, m.supports_vision
               FROM ai_scene_model_configs sc
               JOIN ai_models m ON sc.model_id = m.id
               WHERE sc.scene_key = 'user_chat' AND m.enabled = 1
               ORDER BY sc.priority ASC
               LIMIT 1"""
        )
        model_row = await cur.fetchone()
        if model_row:
            supports_vision = bool(model_row["supports_vision"])
            mr = dict(model_row)
            model_name = mr.get("display_name") or mr["model_name"]
            provider_name = model_row["provider_name"]
        else:
            # 没有配置 user_chat 场景，尝试查询 default 场景
            await cur.execute(
                """SELECT m.model_name, m.display_name, m.provider_name, m.supports_vision
                   FROM ai_scene_model_configs sc
                   JOIN ai_models m ON sc.model_id = m.id
                   WHERE sc.scene_key = 'default' AND m.enabled = 1
                   ORDER BY sc.priority ASC
                   LIMIT 1"""
            )
            model_row = await cur.fetchone()
            if model_row:
                supports_vision = bool(model_row["supports_vision"])
                mr = dict(model_row)
                model_name = mr.get("display_name") or mr["model_name"]
                provider_name = model_row["provider_name"]
    else:
        # 从 config.yaml 静态配置中读取
        # 尝试读取 DeerFlow 的 config.yaml
        try:
            import yaml
            deerflow_config_path = os.environ.get(
                "DEERFLOW_CONFIG_PATH",
                os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))),
                             "deer-flow", "config.yaml")
            )
            if os.path.exists(deerflow_config_path):
                with open(deerflow_config_path, "r", encoding="utf-8") as f:
                    config = yaml.safe_load(f) or {}
                models = config.get("models", [])
                if models:
                    first_model = models[0]
                    supports_vision = bool(first_model.get("supports_vision", False))
                    model_name = first_model.get("display_name") or first_model.get("name", "")
        except Exception:
            pass

    # 定义允许上传的文件类型
    if supports_vision:
        # 支持视觉：文档 + 图片 + PDF
        allowed_extensions = [
            ".doc", ".docx", ".md", ".txt", ".xls", ".xlsx", ".csv",
            ".pdf",
            ".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".tif"
        ]
        allowed_types = {
            "documents": ["doc", "docx", "md", "txt", "xls", "xlsx", "csv"],
            "images": ["jpg", "jpeg", "png", "gif", "bmp", "webp", "tiff", "tif"],
            "pdf": ["pdf"]
        }
        upload_tip = "支持上传：Word、Markdown、TXT、Excel、PDF、图片"
    else:
        # 仅 LLM：文档（不含 PDF 和图片）
        allowed_extensions = [
            ".doc", ".docx", ".md", ".txt", ".xls", ".xlsx", ".csv"
        ]
        allowed_types = {
            "documents": ["doc", "docx", "md", "txt", "xls", "xlsx", "csv"],
            "images": [],
            "pdf": []
        }
        upload_tip = "支持上传：Word、Markdown、TXT、Excel（当前模型不支持图片和PDF识别）"

    return {
        "supports_vision": supports_vision,
        "model_name": model_name,
        "provider_name": provider_name,
        "source": source,
        "allowed_extensions": allowed_extensions,
        "allowed_types": allowed_types,
        "upload_tip": upload_tip,
        "max_file_size": 20 * 1024 * 1024,  # 20MB
        "max_files": 5,
    }
