from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, status

from app.api.deps import CurrentUserContext, get_optional_current_user
from app.core.bootstrap import build_bootstrap_state, persist_bootstrap_config
from app.core.config import get_settings
from app.schemas.bootstrap import BootstrapSetupPayload, BootstrapStateRead

router = APIRouter(prefix="/bootstrap")


@router.get(
    "",
    response_model=BootstrapStateRead,
    summary="读取初始化状态",
    description="返回当前系统是否已完成初始化，以及公司、数据库和缓存配置快照。",
)
def get_bootstrap_state() -> BootstrapStateRead:
    settings = get_settings()
    return build_bootstrap_state(
        settings,
        redact_infrastructure=settings.setup_completed,
    )


@router.post(
    "",
    response_model=BootstrapStateRead,
    status_code=status.HTTP_201_CREATED,
    summary="写入初始化配置",
    description="保存系统初始化配置，并刷新运行时数据库连接。",
)
def initialize_bootstrap(
    payload: BootstrapSetupPayload,
    current_user: Annotated[
        CurrentUserContext | None,
        Depends(get_optional_current_user),
    ],
) -> BootstrapStateRead:
    settings = get_settings()
    if settings.setup_completed and (current_user is None or not current_user.is_admin):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="系统已完成初始化，只有平台管理员可以重新写入初始化配置。",
        )
    return persist_bootstrap_config(payload, settings)
