"""tenant.rbac — Role-based access control."""
from __future__ import annotations
from agentpaas.api.middleware.auth import TenantContext

ROLE_PERMISSIONS = {
    "admin": {"tenants:*", "agents:*", "keys:*", "billing:read", "secrets:*", "admin:*"},
    "developer": {"agents:read", "agents:write", "agents:execute", "keys:read", "keys:write", "runs:read", "secrets:read"},
    "viewer": {"agents:read", "runs:read", "billing:read"},
}

def check_permission(tenant_ctx: TenantContext, required: str) -> bool:
    role = tenant_ctx.role or "developer"
    perms = ROLE_PERMISSIONS.get(role, set())
    if required in perms:
        return True
    # Check wildcard (e.g., "agents:*" covers "agents:read")
    category = required.split(":")[0]
    if f"{category}:*" in perms:
        return True
    # Check scopes from API key
    if required in tenant_ctx.scopes or f"{category}:*" in tenant_ctx.scopes:
        return True
    return False

def require_permission(tenant_ctx: TenantContext, required: str):
    if not check_permission(tenant_ctx, required):
        from fastapi import HTTPException
        raise HTTPException(403, {"error": {"code": "FORBIDDEN", "message": f"Missing permission: {required}"}})
