"""Provision the bootstrap super admin on boot (design D8, spec admin-auth).

`make seed` cannot be the production path — it also writes a demo wedding, demo events and
message templates, none of which belong in a customer's database. So this runs on every
start, in every environment.

Without it a fresh production deployment locks itself out on the first day: the roster is
empty, the first Google sign-in creates a `PENDING` account, and nobody holds
`MANAGE_ADMINS` to approve it. There is no recovery from inside the application.

It is idempotent in the strong sense — not merely "does not duplicate", but **does not
overwrite**. A super admin who deliberately demoted this account, withdrew it, or gave it a
password must not have that undone by the next restart. The only thing this function will do
to an existing row is nothing.
"""

import logging
from datetime import UTC, datetime

from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.config import get_settings
from app.models import AdminUser
from app.models.enums import AdminRole, AdminStatus, AuthMethod

logger = logging.getLogger(__name__)


async def ensure_bootstrap_super_admin(session: AsyncSession) -> AdminUser | None:
    """Create the configured bootstrap account if it is absent. Never modify it if present."""
    email = (get_settings().seed_super_admin_email or "").strip().lower()
    if not email:
        # Production refuses to boot without it (`assert_production_ready`), so reaching
        # here means a development run where an empty roster is a nuisance, not a lockout.
        logger.warning("SEED_SUPER_ADMIN_EMAIL is unset; no bootstrap super admin provisioned")
        return None

    existing = await session.scalar(select(AdminUser).where(func.lower(AdminUser.email) == email))
    if existing is not None:
        logger.debug("bootstrap super admin already present; leaving it untouched")
        return existing

    now = datetime.now(UTC)
    admin = AdminUser(
        email=email,
        name="Super Admin",
        role=AdminRole.SUPER_ADMIN,
        status=AdminStatus.ACTIVE,
        # Google, not password: nobody could safely choose a password here, and one baked
        # into configuration would be a shared secret in a file.
        auth_method=AuthMethod.GOOGLE,
        first_seen_at=now,
    )
    session.add(admin)
    await session.commit()
    logger.info("provisioned the bootstrap super admin")
    return admin
