from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.user import User
from app.routers.auth import get_current_user
from app.schemas.settings import (
    SettingsOut, ProfileUpdateIn, LLMConfigIn, SchedulerConfigIn, LLMTestIn
)
from app.services.settings_service import (
    get_user_settings, update_user_profile, update_llm_config,
    update_scheduler_config, test_llm_connection
)

router = APIRouter(prefix="/api/settings", tags=["设置"])


@router.get("", response_model=SettingsOut)
async def get_settings(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    settings = await get_user_settings(current_user.id, db)
    if not settings:
        raise HTTPException(status_code=404, detail="用户不存在")
    return settings


@router.put("/profile")
async def update_profile(
    data: ProfileUpdateIn,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    try:
        user = await update_user_profile(
            current_user.id, db,
            full_name=data.full_name,
            password=data.password,
            current_password=data.current_password
        )
        return user
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.put("/llm")
async def update_llm(
    data: LLMConfigIn,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    try:
        config = await update_llm_config(current_user.id, data.model_dump(exclude_none=True), db)
        return {"llm_config": config}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/llm/test")
async def test_llm(
    data: LLMTestIn,
    current_user: User = Depends(get_current_user),
):
    result = await test_llm_connection(
        provider=data.provider,
        model=data.model,
        base_url=data.base_url,
        api_key=data.api_key
    )
    return result


@router.put("/scheduler")
async def update_scheduler(
    data: SchedulerConfigIn,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    try:
        config = await update_scheduler_config(
            current_user.id,
            data.model_dump(exclude_none=True),
            db
        )
        return {"scheduler_config": config}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
