from __future__ import annotations

import os
from typing import Any

from app.auth import hash_password
from app.core.logging import get_audit_logger, get_logger


ADMIN_USERNAME = os.getenv("ADMIN_USERNAME", "admin")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
ADMIN_FORCE_RESET = os.getenv("ADMIN_FORCE_RESET", "0").lower() in {"1", "true", "yes"}
logger = get_logger(__name__)
audit_logger = get_audit_logger()


def ensure_admin_user(sync_db: Any) -> dict[str, str]:
    users = sync_db["users"]
    existing = users.find_one({"username": ADMIN_USERNAME})
    if existing:
        if ADMIN_FORCE_RESET and ADMIN_PASSWORD:
            users.update_one(
                {"_id": existing["_id"]},
                {"$set": {"password": hash_password(ADMIN_PASSWORD)}},
            )
            logger.info("Admin password updated by ADMIN_FORCE_RESET")
            audit_logger.business_event(
                event_type="auth.admin_bootstrap",
                action="update_admin_password",
                outcome="warning",
                service="admin_bootstrap",
                resource={"username": ADMIN_USERNAME},
            )
            return {"status": "updated", "username": ADMIN_USERNAME}
        logger.info("Admin user already exists")
        return {"status": "exists", "username": ADMIN_USERNAME}

    if not ADMIN_PASSWORD:
        raise RuntimeError("ADMIN_PASSWORD es obligatorio para bootstrappear el usuario admin.")

    users.insert_one(
        {
            "username": ADMIN_USERNAME,
            "password": hash_password(ADMIN_PASSWORD),
            "role": "admin",
        }
    )
    logger.info("Admin user created during explicit bootstrap")
    audit_logger.business_event(
        event_type="auth.admin_bootstrap",
        action="create_admin_user",
        outcome="success",
        service="admin_bootstrap",
        resource={"username": ADMIN_USERNAME},
    )
    return {"status": "created", "username": ADMIN_USERNAME}
