from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
import yaml
from {{ base_package }}.core.config import settings

def load_db_config():
    """
    运行时从 curdezgen.yaml 加载数据库配置。
    在当前目录和父目录中搜索。
    """
    target_file = "curdezgen.yaml"
    current_dir = os.getcwd()
    
    # 潜在的检查路径
    check_paths = [
        os.path.join(current_dir, target_file),
        os.path.join(os.path.dirname(current_dir), target_file),
        # 如果可能，也检查相对于此文件的位置，但在安装的包中不太可靠
        os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), target_file)
    ]
    
    for path in check_paths:
        if os.path.exists(path):
            try:
                with open(path, "r", encoding="utf-8") as f:
                    data = yaml.safe_load(f)
                    if data and "db" in data:
                        return data["db"]
            except Exception as e:
                print(f"警告: 从 {path} 读取配置失败: {e}")
                pass
    
    print("警告: 未找到 curdezgen.yaml 或文件无效。")
    return {}

db_config = load_db_config()

# 优先从环境变量读取，否则使用运行时读取的 YAML 配置
SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
if not SQLALCHEMY_DATABASE_URL:
    if db_config.get("url"):
        SQLALCHEMY_DATABASE_URL = db_config["url"]
    else:
        # 动态构建 URL
        DB_TYPE = db_config.get("type", "postgresql")
        DB_USER = db_config.get("user", "")
        DB_PASS = db_config.get("password", "")
        DB_HOST = db_config.get("host", "localhost")
        DB_PORT = db_config.get("port", 5432)
        DB_NAME = db_config.get("name", "")
        
        driver = "postgresql+psycopg2" if DB_TYPE == "postgresql" else DB_TYPE
        if DB_TYPE == "mysql":
            driver = "mysql+pymysql"
            
        SQLALCHEMY_DATABASE_URL = f"{driver}://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"

connect_args = {}
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
    connect_args = {"check_same_thread": False}

# 如果是 PostgreSQL 且指定了 Schema
execution_options = {}
schema_name = db_config.get("schema_name")
# 检查是否使用 postgresql (在 url 或 type 中)
if schema_name and ("postgresql" in SQLALCHEMY_DATABASE_URL or db_config.get("type") == "postgresql"):
    execution_options = {"schema_translate_map": {None: schema_name}}

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, 
    connect_args=connect_args,
    execution_options=execution_options
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
