#!/usr/bin/env python3
"""schema.sql を MySQL に適用する。"""
from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import pymysql  # noqa: E402

from config import DB_CHARSET, DB_HOST, DB_NAME, DB_PASSWORD, DB_PORT, DB_USER  # noqa: E402

SCHEMA = os.path.join(os.path.dirname(__file__), "schema.sql")


def main() -> None:
    with open(SCHEMA, encoding="utf-8") as f:
        sql = f.read()
    conn = pymysql.connect(
        host=DB_HOST,
        port=DB_PORT,
        user=DB_USER,
        password=DB_PASSWORD,
        charset=DB_CHARSET,
    )
    try:
        with conn.cursor() as cur:
            for stmt in sql.split(";"):
                stmt = stmt.strip()
                if stmt:
                    cur.execute(stmt)
        conn.commit()
        print(f"OK: applied {SCHEMA}")
    finally:
        conn.close()


if __name__ == "__main__":
    main()
