"""
Admin Demo Config API

Provides endpoints to list, load, and remove demo configurations.
SysAdmin-only access.
"""

import logging
from fastapi import APIRouter, Depends, HTTPException, Request, status

from modules.auth import limiter
from modules.auth.authentication import requireSysAdminRole
from modules.datamodels.datamodelUam import User
from modules.security.rootAccess import getRootDbAppConnector

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/api/admin/demo-config",
    tags=["Admin Demo Config"],
)


@router.get("")
@limiter.limit("30/minute")
def listDemoConfigs(
    request: Request,
    currentUser: User = Depends(requireSysAdminRole),
) -> dict:
    """List all available demo configurations."""
    from modules.demoConfigs import _getAvailableDemoConfigs

    configs = _getAvailableDemoConfigs()
    return {
        "configs": [cfg.toDict() for cfg in configs.values()],
    }


@router.post("/{code}/load")
@limiter.limit("5/minute")
def loadDemoConfig(
    code: str,
    request: Request,
    currentUser: User = Depends(requireSysAdminRole),
) -> dict:
    """Load (create) a demo configuration. Idempotent."""
    from modules.demoConfigs import _getDemoConfigByCode

    config = _getDemoConfigByCode(code)
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Demo config '{code}' not found",
        )

    db = getRootDbAppConnector()
    logger.info(f"Loading demo config '{code}' (user: {currentUser.username})")
    summary = config.load(db)
    logger.info(f"Demo config '{code}' loaded: {summary}")

    return {"status": "ok", "code": code, "summary": summary}


@router.post("/{code}/remove")
@limiter.limit("5/minute")
def removeDemoConfig(
    code: str,
    request: Request,
    currentUser: User = Depends(requireSysAdminRole),
) -> dict:
    """Remove all data created by a demo configuration."""
    from modules.demoConfigs import _getDemoConfigByCode

    config = _getDemoConfigByCode(code)
    if not config:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Demo config '{code}' not found",
        )

    db = getRootDbAppConnector()
    logger.info(f"Removing demo config '{code}' (user: {currentUser.username})")
    summary = config.remove(db)
    logger.info(f"Demo config '{code}' removed: {summary}")

    return {"status": "ok", "code": code, "summary": summary}
