# #region InitAuthDbScript [C:2] [TYPE Module] [SEMANTICS auth]
#
# @BRIEF Initializes the auth database and creates the necessary tables.
# @LAYER Service
# @RELATION CALLS -> [init_db]
# @RELATION CALLS -> [ensure_encryption_key]
# @RELATION CALLS -> [seed_permissions]
#
# @INVARIANT  Safe to run multiple times (idempotent).

from pathlib import Path
import sys

# Add src to path
sys.path.append(str(Path(__file__).parent.parent.parent))

from src.core.cot_logger import seed_trace_id
from src.core.database import init_db
from src.core.encryption_key import ensure_encryption_key
from src.core.logger import belief_scope, logger
from src.scripts.seed_permissions import seed_permissions


# #region run_init [C:3] [TYPE Function]
# @BRIEF Main entry point for the initialization script.
# @POST     auth.db is initialized with the correct schema and seeded permissions.
# @RELATION CALLS -> [ensure_encryption_key]
# @RELATION CALLS -> [init_db]
# @RELATION CALLS -> [seed_permissions]
def run_init():
    seed_trace_id()
    with belief_scope("init_auth_db"):
        logger.info("Initializing authentication database...")
        try:
            ensure_encryption_key()
            init_db()
            logger.info("Authentication database initialized successfully.")

            # Seed permissions
            seed_permissions()

        except Exception as e:
            logger.error(f"Failed to initialize authentication database: {e}")
            sys.exit(1)


# #endregion run_init

if __name__ == "__main__":
    run_init()

# #endregion InitAuthDbScript
