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

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_feature_flags(
    request: Request,
    flag: str = Query(""),
    db=Depends(get_system_db_dep),
):
    conn, cur = db

    if flag:
        await cur.execute(
            "SELECT flag_key, flag_name, description, flag_type, value_boolean, value_percentage, value_json, target_edition, enabled_for_c_end FROM feature_flags WHERE flag_key = %s",
            (flag,),
        )
        row = await cur.fetchone()
        if not row:
            return {"flag_key": flag, "enabled": False}
        r = dict(row)
        return {
            "flag_key": r["flag_key"],
            "flag_name": r["flag_name"],
            "description": r.get("description"),
            "flag_type": r.get("flag_type", "boolean"),
            "enabled": r["value_boolean"] == 1 if r.get("value_boolean") is not None else False,
            "target_edition": r.get("target_edition"),
            "enabled_for_c_end": r.get("enabled_for_c_end") == 1,
        }

    await cur.execute("SELECT flag_key, flag_name, value_boolean, flag_type, target_edition, enabled_for_c_end FROM feature_flags ORDER BY flag_key")
    rows = await cur.fetchall()

    flags = {}
    for row in rows:
        r = dict(row)
        flags[r["flag_key"]] = r["value_boolean"] == 1 if r.get("value_boolean") is not None else False

    return {"flags": flags}
