"""CLI bootstrap helpers.

Ensures process-wide initialization for CLI commands that depend on
persistence-backed registries by running Alembic migrations exactly once per
process.
"""

from __future__ import annotations

from threading import Lock

_database_bootstrapped = False
_bootstrap_lock = Lock()


def ensure_cli_database_bootstrapped(force: bool = False) -> None:
    """Ensure CLI database schema exists and migrations are applied."""

    global _database_bootstrapped

    if _database_bootstrapped and not force:
        return

    with _bootstrap_lock:
        if _database_bootstrapped and not force:
            return

        from cleveragents.application.container import get_database_url
        from cleveragents.infrastructure.database.migration_runner import (
            MigrationRunner,
        )

        runner = MigrationRunner(get_database_url())
        runner.init_or_upgrade(require_confirmation=False)

        _database_bootstrapped = True


def reset_bootstrap_state() -> None:
    """Reset the bootstrap state flag.

    .. warning:: **Test use only.** Do not call in production code paths —
       resetting bootstrap state mid-flight can cause inconsistent database
       initialisation state.
    """
    global _database_bootstrapped
    _database_bootstrapped = False


__all__ = ["ensure_cli_database_bootstrapped", "reset_bootstrap_state"]
