"""Create tables and seed MySQL from sql/init_db.sql when the user table is empty."""
import os
import subprocess
import sys

from app import create_app
from app.models import User, db


def main() -> None:
    app = create_app()
    with app.app_context():
        db.create_all()
        if User.query.count() > 0:
            print("Database already initialized, skipping seed.")
            return

        sql_path = os.path.join(os.getcwd(), "sql", "init_db.sql")
        if not os.path.isfile(sql_path):
            print(f"Seed file not found: {sql_path}", file=sys.stderr)
            sys.exit(1)

        host = os.environ["MYSQL_HOST"]
        port = os.environ.get("MYSQL_PORT", "3306")
        user = os.environ["MYSQL_USER"]
        password = os.environ["MYSQL_PASSWORD"]
        database = os.environ["MYSQL_DATABASE"]

        cmd = [
            "mysql",
            "--default-character-set=utf8mb4",
            f"-h{host}",
            f"-P{port}",
            f"-u{user}",
            f"-p{password}",
            database,
        ]
        print("Seeding database from sql/init_db.sql ...")
        with open(sql_path, "rb") as f:
            subprocess.run(cmd, stdin=f, check=True)
        print("Seed completed.")


if __name__ == "__main__":
    main()
