import argparse

from alembic import command
from alembic.config import Config

from app.db.init_db import create_tables, seed_defaults
from app.db.session import SessionLocal


def main() -> None:
    parser = argparse.ArgumentParser(description="Certificate system management commands")
    subparsers = parser.add_subparsers(dest="command", required=True)

    init_parser = subparsers.add_parser("init-db")
    init_parser.add_argument("--admin-username", default="admin")
    init_parser.add_argument("--admin-password", required=True)

    args = parser.parse_args()
    if args.command == "init-db":
        try:
            command.upgrade(Config("alembic.ini"), "head")
        except Exception:
            create_tables()
        with SessionLocal() as db:
            seed_defaults(db, args.admin_username, args.admin_password)
        print("Database initialized")


if __name__ == "__main__":
    main()
