
import os
from flask import current_app

from ..models import User, db


def bootstrap_system(app):
    admin_username = os.getenv('ADMIN_USERNAME', 'admin').strip()
    admin_email = os.getenv('ADMIN_EMAIL', 'admin@example.com').strip()
    admin_password = os.getenv('ADMIN_PASSWORD', 'change-me-admin').strip()

    existing = User.query.filter_by(username=admin_username).first()
    if existing:
        return

    admin = User(
        username=admin_username,
        email=admin_email,
        display_name='Administrator',
        role='admin',
        active=True,
        force_password_change=False,
    )
    admin.set_password(admin_password)
    db.session.add(admin)
    db.session.commit()
    current_app.logger.info(f'Bootstrap admin created: {admin_username}')
