"""Super Admin — AI Profile Management
Routes:
  GET    /superadmin/ai-profiles            list all profiles
  POST   /superadmin/ai-profiles            create profile
  PUT    /superadmin/ai-profiles/{id}        update profile
  DELETE /superadmin/ai-profiles/{id}        delete profile (blocked if tenants reference it)
  POST   /superadmin/ai-profiles/test        test connection
"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, field_validator
from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_superadmin_user
from app.core.models.ai_profile import AiProfile
from app.core.models.tenant import Tenant
from app.core.ai_utils import call_ai

router = APIRouter(prefix="/superadmin/ai-profiles", tags=["超管-AI配置"])

_STRIP_FIELDS = ("name", "provider", "api_key", "base_url", "model")


class AiProfileCreate(BaseModel):
    name: str
    provider: str
    api_key: str | None = None
    base_url: str | None = None
    model: str | None = None
    is_default: bool = False
    is_active: bool = True

    @field_validator(*_STRIP_FIELDS, mode="before")
    @classmethod
    def _strip(cls, v):
        return v.strip() if isinstance(v, str) else v


class AiProfileUpdate(BaseModel):
    name: str | None = None
    provider: str | None = None
    api_key: str | None = None
    base_url: str | None = None
    model: str | None = None
    is_default: bool | None = None
    is_active: bool | None = None

    @field_validator(*_STRIP_FIELDS, mode="before")
    @classmethod
    def _strip(cls, v):
        return v.strip() if isinstance(v, str) else v


class AiProfileTest(BaseModel):
    """测试连接 — 支持 profile_id 用于编辑场景下密钥留空时回退到已保存的值"""
    profile_id: int | None = None
    provider: str
    api_key: str | None = None
    base_url: str | None = None
    model: str | None = None
    prompt: str = "你好，请用一句话介绍你自己。"


async def _unset_other_defaults(db: AsyncSession, exclude_id: int | None = None):
    q = select(AiProfile).where(AiProfile.is_default == True)  # noqa: E712
    if exclude_id is not None:
        q = q.where(AiProfile.id != exclude_id)
    for p in (await db.execute(q)).scalars().all():
        p.is_default = False


@router.get("/", summary="列出所有 AI 配置")
async def list_profiles(db: AsyncSession = Depends(get_db), _=Depends(get_superadmin_user)):
    r = await db.execute(select(AiProfile).order_by(AiProfile.id))
    profiles = r.scalars().all()
    return [
        {
            "id": p.id, "name": p.name, "provider": p.provider,
            "base_url": p.base_url, "model": p.model,
            "has_api_key": bool(p.api_key),
            "is_default": p.is_default, "is_active": p.is_active,
        }
        for p in profiles
    ]


@router.post("/", summary="创建 AI 配置", status_code=201)
async def create_profile(
    body: AiProfileCreate, db: AsyncSession = Depends(get_db), _=Depends(get_superadmin_user)
):
    profile = AiProfile(**body.model_dump())
    db.add(profile)
    await db.flush()
    if profile.is_default:
        await _unset_other_defaults(db, exclude_id=profile.id)
    await db.commit()
    await db.refresh(profile)
    return {"id": profile.id}


@router.post("/test", summary="测试 AI 配置连接")
async def test_profile(
    body: AiProfileTest, db: AsyncSession = Depends(get_db), _=Depends(get_superadmin_user)
):
    api_key = body.api_key
    if body.profile_id and not api_key:
        r = await db.execute(select(AiProfile).where(AiProfile.id == body.profile_id))
        existing = r.scalar_one_or_none()
        if existing:
            api_key = existing.api_key

    extra = {
        "ai_provider": body.provider,
        "ai_api_key": api_key,
        "ai_base_url": body.base_url,
        "ai_model": body.model,
    }
    reply = await call_ai(body.prompt, extra, timeout=60, max_tokens=256)
    return {"ok": True, "reply": reply}


@router.put("/{profile_id}", summary="更新 AI 配置")
async def update_profile(
    profile_id: int, body: AiProfileUpdate,
    db: AsyncSession = Depends(get_db), _=Depends(get_superadmin_user),
):
    r = await db.execute(select(AiProfile).where(AiProfile.id == profile_id))
    profile = r.scalar_one_or_none()
    if not profile:
        raise HTTPException(status_code=404, detail="AI 配置不存在")
    for k, v in body.model_dump(exclude_unset=True).items():
        if k == "api_key" and not v:
            continue
        setattr(profile, k, v)
    if profile.is_default:
        await _unset_other_defaults(db, exclude_id=profile.id)
    await db.commit()
    return {"id": profile.id, "ok": True}


@router.delete("/{profile_id}", summary="删除 AI 配置")
async def delete_profile(
    profile_id: int, db: AsyncSession = Depends(get_db), _=Depends(get_superadmin_user)
):
    count_r = await db.execute(
        select(func.count()).select_from(Tenant).where(Tenant.ai_profile_id == profile_id)
    )
    if count_r.scalar_one() > 0:
        raise HTTPException(status_code=400, detail="仍有租户在使用该 AI 配置，请先取消分配")
    r = await db.execute(select(AiProfile).where(AiProfile.id == profile_id))
    profile = r.scalar_one_or_none()
    if not profile:
        raise HTTPException(status_code=404, detail="AI 配置不存在")
    await db.delete(profile)
    await db.commit()
    return {"ok": True}
