"""Container startup helper.

When the app is started via gunicorn, the `if __name__ == '__main__'` block in
app.py is not executed, so the SQLite DB/tables/admin user may not be created.

This script makes startup idempotent by ensuring tables exist and creating a
default admin user if missing.
"""

import os

from werkzeug.security import generate_password_hash

from app import app, db, User, Church


def main() -> None:
    admin_username = os.environ.get("ADMIN_USERNAME", "admin")
    admin_password = os.environ.get("ADMIN_PASSWORD", "admin")

    with app.app_context():
        db.create_all()

        if not User.query.filter_by(username=admin_username).first():
            admin_church = Church.query.filter_by(name="Admin").first()
            if not admin_church:
                admin_church = Church(name="Admin")
                db.session.add(admin_church)
                db.session.commit()

            admin_user = User(
                username=admin_username,
                password=generate_password_hash(admin_password),
                church_id=admin_church.id,
                is_admin=True,
            )
            db.session.add(admin_user)
            db.session.commit()


if __name__ == "__main__":
    main()
