# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from devplacepy.utils import require_admin
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit
from devplacepy.services.manager import service_manager
from devplacepy.services.openai_gateway import quota

logger = logging.getLogger(__name__)
router = APIRouter()


@router.post("/ai-quota/reset-guests")
async def admin_reset_guest_ai_quota(request: Request):
    admin = require_admin(request)
    devii = service_manager.get_service("devii")
    removed = devii.reset_guest_quotas() if devii is not None else 0
    logger.info(
        f"Admin {admin['username']} reset all guest AI quotas ({removed} ledger rows)"
    )
    audit.record(
        request,
        "admin.ai_quota.reset_guests",
        user=admin,
        metadata={"rows_removed": removed},
        summary=f"admin {admin['username']} reset all guest AI quotas",
    )
    return action_result(request, "/admin/ai-usage")


@router.post("/ai-quota/reset-all")
async def admin_reset_all_ai_quota(request: Request):
    admin = require_admin(request)
    devii = service_manager.get_service("devii")
    removed = devii.reset_all_quotas() if devii is not None else 0
    gateway = quota.reset(created_by=admin["uid"])
    logger.info(
        f"Admin {admin['username']} reset ALL AI quotas "
        f"({removed} Devii ledger rows, gateway watermark {gateway['reset_at']})"
    )
    audit.record(
        request,
        "admin.ai_quota.reset_all",
        user=admin,
        metadata={"rows_removed": removed, "gateway_reset_at": gateway["reset_at"]},
        summary=(
            f"admin {admin['username']} reset all AI quotas "
            "(Devii assistant and AI gateway)"
        ),
    )
    return action_result(request, "/admin/ai-usage")

