import os

from sqlalchemy import Engine
from sqlmodel import create_engine

db_driver_available = {
    "sqlite": ["sqlite3"],
    "mysql": ["pymysql"],
    "postgresql": ["psycopg"],
}
db_type_allowlist = ["sqlite", "mysql", "postgresql"]


def build_engine() -> Engine:
    from logging import getLogger

    logger = getLogger(__name__)

    db_type = os.environ.get("NYAHOME_DB_TYPE", "sqlite")
    db_driver = os.environ.get("NYAHOME_DB_DRIVER")
    if db_type not in db_type_allowlist:
        logger.warning(f"数据库类型 {db_type} 不受 NyaHome 官方支持，建议改用受支持的数据库：{db_type_allowlist}")
    else:
        if db_driver is None:
            db_driver = db_driver_available[db_type][0]

    if db_type == "sqlite":
        if db_driver == "sqlite3":  # fix: sqlalchemy 中使用 pysqlite 表示默认的 sqlite3 标准库驱动，气得我直接缺省算惹
            return create_engine("sqlite:///.nyahome/nyahome.db")
        return create_engine(f"sqlite+{db_driver}:///.nyahome/nyahome.db")
    db_name = os.environ.get("NYAHOME_DB_NAME", "nyahome")
    db_user = os.environ.get("NYAHOME_DB_USER", "nyahome")
    db_password = os.environ.get("NYAHOME_DB_PASSWORD", "nyahome")
    db_host = os.environ.get("NYAHOME_DB_HOST", "localhost")
    db_port = os.environ.get("NYAHOME_DB_PORT", "3306")
    return create_engine(f"{db_type}+{db_driver}://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}")


engine = build_engine()
