"""平台/服务商路由"""

from typing import List, Optional

from fastapi import APIRouter, Depends, Query
from sqlmodel import Session

from app.core.security import require_api_key
from app.core.seed import seed_providers
from app.database import get_session
from app.models.provider import ProviderCategory
from app.schemas.provider import ProviderCreate, ProviderRead, ProviderUpdate
from app.adapters import registry
from app.services import provider_service, sync_service

router = APIRouter(prefix="/api/providers", tags=["providers"])


@router.post(
    "/seed",
    summary="初始化预设平台",
    dependencies=[Depends(require_api_key)],
)
def seed(session: Session = Depends(get_session)) -> dict:
    added = seed_providers(session)
    return {"added": added}


@router.get("/adapters", summary="已支持的 SDK 适配器元信息")
def adapters() -> dict:
    return {
        "adapters": registry.adapter_meta(),
        "supported_types": registry.supported_types(),
        "capabilities": registry.sdk_capabilities(),
    }


@router.get("", response_model=List[ProviderRead], summary="平台列表")
def list_providers(
    category: Optional[ProviderCategory] = Query(default=None),
    enabled: Optional[bool] = Query(default=None),
    session: Session = Depends(get_session),
):
    return provider_service.list_providers(session, category, enabled)


@router.get("/{provider_id}", response_model=ProviderRead, summary="平台详情")
def get_provider(provider_id: int, session: Session = Depends(get_session)):
    return provider_service.get_provider(session, provider_id)


@router.post(
    "",
    response_model=ProviderRead,
    status_code=201,
    summary="创建平台",
    dependencies=[Depends(require_api_key)],
)
def create_provider(data: ProviderCreate, session: Session = Depends(get_session)):
    return provider_service.create_provider(session, data)


@router.put(
    "/{provider_id}",
    response_model=ProviderRead,
    summary="更新平台",
    dependencies=[Depends(require_api_key)],
)
def update_provider(
    provider_id: int, data: ProviderUpdate, session: Session = Depends(get_session)
):
    return provider_service.update_provider(session, provider_id, data)


@router.delete(
    "/{provider_id}",
    status_code=204,
    summary="删除平台",
    dependencies=[Depends(require_api_key)],
)
def delete_provider(provider_id: int, session: Session = Depends(get_session)):
    provider_service.delete_provider(session, provider_id)


@router.post(
    "/{provider_id}/test",
    summary="测试平台连接 / 凭证有效性",
    dependencies=[Depends(require_api_key)],
)
def test_connection(provider_id: int, session: Session = Depends(get_session)) -> dict:
    return sync_service.test_provider(session, provider_id)


@router.post(
    "/{provider_id}/sync",
    summary="同步平台资产到本地库",
    dependencies=[Depends(require_api_key)],
)
def sync_assets(provider_id: int, session: Session = Depends(get_session)) -> dict:
    return sync_service.sync_provider(session, provider_id)
