import httpx
from typing import Any, Dict, List, Literal, Optional, Union
from .types import *

from src.auth.auth_guard import enforce_auth
from src.auth.authz_client import AuthzClient

# Auth configuration per operation
AUTH_CONFIG: Dict[str, Dict[str, Any]] = {
    "experimental_service_experimental_count_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_register_relationship_counter": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_unregister_relationship_counter": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_diff_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_bulk_check_permission": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_computable_permissions": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_dependent_relations": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_experimental_reflect_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_bulk_export_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "experimental_service_bulk_import_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_check_permission": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_check_bulk_permissions": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_expand_permission_tree": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_lookup_resources": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_lookup_subjects": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_delete_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "admin",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_export_bulk_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_import_bulk_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_read_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "permissions_service_write_relationships": {
        "mode": "required",
        "resource_type": "project",
        "permission": "write",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_diff_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_computable_permissions": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_dependent_relations": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_read_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_reflect_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "schema_service_write_schema": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
    "watch_service_watch": {
        "mode": "required",
        "resource_type": "project",
        "permission": "read",
        "resource_id_source": "jwt",
        "resource_id_field": "org_id",
    },
}
class ExperimentalClient:
    """
    Layer 0 raw client for Experimental operations.
    """

    def __init__(self, base_url: str, api_token: str, authz: Optional["AuthzClient"] = None):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_token}",
                "Content-Type": "application/json",
            }
        )
        self._authz = authz

    async def experimental_service_experimental_count_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_count_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/countrelationships"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_experimental_register_relationship_counter(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_register_relationship_counter",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/registerrelationshipcounter"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_experimental_unregister_relationship_counter(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_unregister_relationship_counter",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/unregisterrelationshipcounter"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()


class DeprecatedClient:
    """
    Layer 0 raw client for Deprecated operations.
    """

    def __init__(self, base_url: str, api_token: str, authz: Optional["AuthzClient"] = None):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_token}",
                "Content-Type": "application/json",
            }
        )
        self._authz = authz

    async def experimental_service_experimental_diff_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_diff_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/diffschema"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_bulk_check_permission(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_bulk_check_permission",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/permissions/bulkcheckpermission"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_experimental_computable_permissions(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_computable_permissions",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/permissions/computable"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_experimental_dependent_relations(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_dependent_relations",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/permissions/dependent"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_experimental_reflect_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_experimental_reflect_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/reflectschema"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_bulk_export_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_bulk_export_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/relationships/bulkexport"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def experimental_service_bulk_import_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="experimental_service_bulk_import_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/experimental/relationships/bulkimport"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()


class PermissionsClient:
    """
    Layer 0 raw client for Permissions operations.
    """

    def __init__(self, base_url: str, api_token: str, authz: Optional["AuthzClient"] = None):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_token}",
                "Content-Type": "application/json",
            }
        )
        self._authz = authz

    async def permissions_service_check_permission(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_check_permission",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/permissions/check"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_check_bulk_permissions(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_check_bulk_permissions",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/permissions/checkbulk"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_expand_permission_tree(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_expand_permission_tree",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/permissions/expand"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_lookup_resources(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_lookup_resources",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/permissions/resources"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        # SpiceDB streaming response: parse NDJSON and wrap in results array
        import json
        results = []
        for line in response.text.strip().split('\n'):
            if line:
                try:
                    results.append(json.loads(line))
                except json.JSONDecodeError:
                    continue
        return {"results": results}

    async def permissions_service_lookup_subjects(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_lookup_subjects",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/permissions/subjects"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        # SpiceDB streaming response: parse NDJSON and wrap in results array
        import json
        results = []
        for line in response.text.strip().split('\n'):
            if line:
                try:
                    results.append(json.loads(line))
                except json.JSONDecodeError:
                    continue
        return {"results": results}

    async def permissions_service_delete_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_delete_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/relationships/delete"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_export_bulk_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_export_bulk_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/relationships/exportbulk"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_import_bulk_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_import_bulk_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/relationships/importbulk"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def permissions_service_read_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_read_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/relationships/read"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        # SpiceDB streaming response: parse NDJSON and wrap in results array
        import json
        results = []
        for line in response.text.strip().split('\n'):
            if line:
                try:
                    results.append(json.loads(line))
                except json.JSONDecodeError:
                    continue
        return {"results": results}

    async def permissions_service_write_relationships(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="permissions_service_write_relationships",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/relationships/write"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()


class SchemaClient:
    """
    Layer 0 raw client for Schema operations.
    """

    def __init__(self, base_url: str, api_token: str, authz: Optional["AuthzClient"] = None):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_token}",
                "Content-Type": "application/json",
            }
        )
        self._authz = authz

    async def schema_service_diff_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_diff_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/diffschema"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def schema_service_computable_permissions(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_computable_permissions",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/permissions/computable"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def schema_service_dependent_relations(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_dependent_relations",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/permissions/dependent"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def schema_service_read_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        """Errors include:
- INVALID_ARGUMENT: a provided value has failed to semantically validate
- NOT_FOUND: no schema has been defined"""
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_read_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/read"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def schema_service_reflect_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_reflect_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/reflectschema"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

    async def schema_service_write_schema(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="schema_service_write_schema",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/schema/write"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()


class WatchClient:
    """
    Layer 0 raw client for Watch operations.
    """

    def __init__(self, base_url: str, api_token: str, authz: Optional["AuthzClient"] = None):
        self.client = httpx.AsyncClient(
            base_url=base_url,
            headers={
                "Authorization": f"Bearer {api_token}",
                "Content-Type": "application/json",
            }
        )
        self._authz = authz

    async def watch_service_watch(
        self,
        body: Dict[str, Any],
        auth_token: Optional[str] = None
    ) -> Dict[str, Any]:
        # Auth enforcement (skipped when authz is None for standalone use)
        if self._authz is not None:
            await enforce_auth(
                auth_token=auth_token,
                operation_name="watch_service_watch",
                auth_config=AUTH_CONFIG,
                authz=self._authz,
                body=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body,
                path_params=None,
                query_params=None,
            )

        url = f"/v1/watch"

        params: Dict[str, Any] = {
        }

        headers: Dict[str, Any] = {
        }
        # Filter None
        params = {k: v for k, v in params.items() if v is not None}
        headers = {k: v for k, v in headers.items() if v is not None}

        response = await self.client.request(
            method="POST",
            url=url,
            params=params,
            headers=headers,
            json=body.model_dump(by_alias=True) if hasattr(body, 'model_dump') else body
        )
        response.raise_for_status()

        return response.json()

