"""外部系统连接管理 API(DESIGN §8.14)。"""
from __future__ import annotations

from uuid import UUID

from fastapi import Depends, HTTPException, Response, status

from core.external_systems.service import (
    ExternalSystemError,
    create_external_system,
    delete_external_system,
    list_external_systems,
    provider_catalog,
    test_external_system,
    update_external_system_credentials,
)

from ..schemas import ExternalSystemCreateRequest, ExternalSystemCredentialsRequest


def _uuid(raw: str) -> UUID:
    try:
        return UUID(raw)
    except (ValueError, TypeError) as exc:
        raise HTTPException(404, "external system not found") from exc


def _bad_request(exc: ExternalSystemError) -> HTTPException:
    message = str(exc)
    code = 404 if message == "external system not found" else 400
    return HTTPException(code, message)


def register_external_system_routes(app, *, require_user) -> None:
    @app.get("/v1/external-system-providers", tags=["external-systems"])
    def external_system_providers(user_id: UUID = Depends(require_user)):
        return {"providers": provider_catalog(user_id)}

    @app.get("/v1/external-systems", tags=["external-systems"])
    def external_system_list(user_id: UUID = Depends(require_user)):
        return {"results": list_external_systems(user_id)}

    @app.post(
        "/v1/external-systems",
        tags=["external-systems"],
        status_code=status.HTTP_201_CREATED,
    )
    def external_system_create(
        body: ExternalSystemCreateRequest,
        user_id: UUID = Depends(require_user),
    ):
        try:
            return create_external_system(
                user_id,
                definition_id=body.definition_id,
                name=body.name,
                credentials=body.credentials,
            )
        except ExternalSystemError as exc:
            raise _bad_request(exc)

    @app.put("/v1/external-systems/{system_id}/credentials", tags=["external-systems"])
    def external_system_credentials(
        system_id: str,
        body: ExternalSystemCredentialsRequest,
        user_id: UUID = Depends(require_user),
    ):
        try:
            return update_external_system_credentials(
                user_id,
                _uuid(system_id),
                credentials=body.credentials,
            )
        except ExternalSystemError as exc:
            raise _bad_request(exc)

    @app.post("/v1/external-systems/{system_id}/test", tags=["external-systems"])
    def external_system_test(system_id: str, user_id: UUID = Depends(require_user)):
        try:
            return test_external_system(user_id, _uuid(system_id))
        except ExternalSystemError as exc:
            raise _bad_request(exc)

    @app.delete("/v1/external-systems/{system_id}", tags=["external-systems"])
    def external_system_delete(system_id: str, user_id: UUID = Depends(require_user)):
        if not delete_external_system(user_id, _uuid(system_id)):
            raise HTTPException(404, "external system not found")
        return Response(status_code=204)
