from fastapi import APIRouter, Depends, Request
from ...core.database import get_db, get_system_db, _has_split_databases
from ...core.permission import require_login

router = APIRouter()


async def get_system_db_dep():
    """FastAPI 依赖：优先使用 system.db，单库模式回退到 get_db()"""
    _db_gen = get_system_db() if _has_split_databases() else get_db()
    async for db in _db_gen:
        yield db


@router.get("")
async def get_system_config(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    conn, cur = db

    try:
        await cur.execute("SELECT config_key, config_value, config_type, description, is_public FROM system_configs ORDER BY config_key")
        rows = [dict(row) for row in (await cur.fetchall())]
        configs = {}
        for row in rows:
            configs[row["config_key"]] = row["config_value"]
    except Exception:
        configs = {}

    return configs
