from typing import Optional

from fastapi import APIRouter, Body, Depends, HTTPException
from sqlalchemy.orm import Session

from database import get_db
from dependencies import verify_admin_api_key
import services.feature_flag_service as feature_flag_service

router = APIRouter(
    prefix="/admin/feature-flags",
    tags=["admin-feature-flags"],
    # Same trust boundary as /admin/quota and /admin/cache: a static
    # service-to-service key, not a per-user JWT. The admin panel sends
    # X-Api-Key on every call.
    dependencies=[Depends(verify_admin_api_key)],
)


def _known(feature: str) -> str:
    """404 for a feature nothing reads - otherwise a typo in the path
    (POST /admin/feature-flags/genral_chat) silently creates a row and the
    caller believes the feature was switched."""
    if feature not in feature_flag_service.KNOWN_FEATURES:
        raise HTTPException(status_code=404,
                            detail=f"Unknown feature {feature!r}. Known: "
                                   f"{sorted(feature_flag_service.KNOWN_FEATURES)}")
    return feature


@router.get("/{feature}")
async def read_feature_flag(feature: str, db: Session = Depends(get_db)):
    """What this feature is currently set to, at every scope.

    Reports `master_enabled` alongside the rows because the env kill-switch
    overrides them: a row reading enabled=true while the capability is off
    looks like a bug unless the override is visible.
    """
    feature = _known(feature)
    return feature_flag_service.describe(db, feature)


@router.post("/{feature}")
async def set_feature_flag(
    feature: str,
    enabled: bool = Body(..., embed=True),
    company_id: Optional[int] = Body(None, embed=True),
    updated_by: Optional[int] = Body(None, embed=True),
    db: Session = Depends(get_db),
):
    """Turns a feature on or off.

    Omit company_id to set the GLOBAL default (what ships today). Passing a
    company_id writes a per-tenant override instead — the table supports it
    from the start so enabling for one company later needs no migration.

    The response reports what the flag now SAYS rather than echoing the
    request, because the two differ when the env master switch is off.
    """
    feature = _known(feature)
    row = feature_flag_service.set_enabled(
        db, feature, enabled, company_id=company_id, updated_by=updated_by,
    )
    return {
        "feature": row.feature,
        "scope_type": row.scope_type,
        "scope_id": row.scope_id,
        "enabled": bool(row.enabled),
        "master_enabled": feature_flag_service._master_enabled(feature),
        "effective_global": feature_flag_service.is_enabled(db, feature),
    }
