# Auto-generated by DjangoCFG - see CLAUDE.md

"""
Django CFG API - API Client with JWT Management

Usage:
    >>> from api import API
    >>>
    >>> api = API('https://api.example.com')
    >>>
    >>> # Set JWT token
    >>> api.set_token('your-jwt-token', 'refresh-token')
    >>>
    >>> # Use API
    >>> async with api:
    ...     posts = await api.posts.list()
    ...     user = await api.users.retrieve(1)
    >>>
    >>> # Check authentication
    >>> if api.is_authenticated():
    ...     # ...
    >>>
    >>> # Get OpenAPI schema path
    >>> schema_path = api.get_schema_path()
"""

from __future__ import annotations

import threading
from typing import Any

from .client import APIClient
from .enums import (
    CfgRqTestingScheduleDemoCreateRequestScheduleType,
    DeviceListStatus,
    OAuthConnectionProvider,
    OTPRequestRequestChannel,
    QuickActionColor,
    RunDemoRequestRequestScenario,
    StatCardChangeType,
    StressTestRequestRequestScenario,
    SystemHealthOverallStatus,
)
from .helpers import LoggerConfig, RetryConfig
from .cfg__accounts__auth import CfgAuthAPI
from .cfg__totp__backup_codes import CfgBackupCodesAPI
from .cfg__centrifugo__centrifugo_admin_api import CfgCentrifugoAdminApiAPI
from .cfg__centrifugo__centrifugo_auth import CfgCentrifugoAuthAPI
from .cfg__centrifugo__centrifugo_monitoring import CfgCentrifugoMonitoringAPI
from .cfg__centrifugo__centrifugo_testing import CfgCentrifugoTestingAPI
from .cfg__dashboard__dashboard_api_zones import CfgDashboardApiZonesAPI
from .cfg__dashboard__dashboard_activity import CfgDashboardActivityAPI
from .cfg__dashboard__dashboard_charts import CfgDashboardChartsAPI
from .cfg__dashboard__dashboard_commands import CfgDashboardCommandsAPI
from .cfg__dashboard__dashboard_config import CfgDashboardConfigAPI
from .cfg__dashboard__dashboard_overview import CfgDashboardOverviewAPI
from .cfg__dashboard__dashboard_statistics import CfgDashboardStatisticsAPI
from .cfg__dashboard__dashboard_system import CfgDashboardSystemAPI
from .cfg__dashboard__dashboard_metrics import CfgDashboardMetricsAPI
from .cfg__accounts__oauth import CfgOauthAPI
from .cfg__rq__rq_jobs import CfgRqJobsAPI
from .cfg__rq__rq_monitoring import CfgRqMonitoringAPI
from .cfg__rq__rq_queues import CfgRqQueuesAPI
from .cfg__rq__rq_registries import CfgRqRegistriesAPI
from .cfg__rq__rq_schedules import CfgRqSchedulesAPI
from .cfg__rq__rq_testing import CfgRqTestingAPI
from .cfg__rq__rq_workers import CfgRqWorkersAPI
from .cfg__totp__totp_management import CfgTotpManagementAPI
from .cfg__totp__totp_setup import CfgTotpSetupAPI
from .cfg__totp__totp_verification import CfgTotpVerificationAPI
from .cfg__accounts__user_profile import CfgUserProfileAPI
from .cfg__accounts import CfgAccountsAPI
from .cfg__grpc__grpc_api_keys import CfgGrpcApiKeysAPI
from .cfg__grpc__grpc_configuration import CfgGrpcConfigurationAPI
from .cfg__grpc__grpc_monitoring import CfgGrpcMonitoringAPI
from .cfg__grpc__grpc_services import CfgGrpcServicesAPI
from .cfg__health import CfgHealthAPI
from .cfg__totp import CfgTotpAPI

TOKEN_KEY = "auth_token"
REFRESH_TOKEN_KEY = "refresh_token"

# Auto-generated by DjangoCFG - see CLAUDE.md

class API:
    """
    API Client wrapper with JWT token management.

    This class provides:
    - Thread-safe JWT token storage
    - Automatic Authorization header injection
    - Context manager support for async operations
    - Optional retry and logging configuration

    Example:
        >>> api = API('https://api.example.com')
        >>> api.set_token('jwt-token')
        >>> async with api:
        ...     users = await api.users.list()
        >>>
        >>> # With retry and logging
        >>> api = API(
        ...     'https://api.example.com',
        ...     retry_config=RetryConfig(max_attempts=5),
        ...     logger_config=LoggerConfig(enabled=True)
        ... )
    """

    def __init__(
        self,
        base_url: str,
        logger_config: LoggerConfig | None = None,
        retry_config: RetryConfig | None = None,
        **kwargs: Any
    ):
        """
        Initialize API client.

        Args:
            base_url: Base API URL (e.g., 'https://api.example.com')
            logger_config: Logger configuration (None to disable logging)
            retry_config: Retry configuration (None to disable retry)
            **kwargs: Additional httpx.AsyncClient kwargs
        """
        self.base_url = base_url.rstrip('/')
        self._kwargs = kwargs
        self._logger_config = logger_config
        self._retry_config = retry_config
        self._token: str | None = None
        self._refresh_token: str | None = None
        self._lock = threading.Lock()
        self._client: APIClient | None = None
        self._init_clients()

    def _init_clients(self) -> None:
        """Initialize API client with current token."""
        # Create httpx client with auth header if token exists
        headers = {}
        if self._token:
            headers['Authorization'] = f'Bearer {self._token}'

        kwargs = {**self._kwargs}
        if headers:
            kwargs['headers'] = headers

        # Create new APIClient
        self._client = APIClient(
            self.base_url,
            logger_config=self._logger_config,
            retry_config=self._retry_config,
            **kwargs
        )

    @property
    def cfg_auth(self) -> CfgAuthAPI:
        """Access Auth endpoints."""
        return self._client.cfg_auth

    @property
    def cfg_backup_codes(self) -> CfgBackupCodesAPI:
        """Access Backup Codes endpoints."""
        return self._client.cfg_backup_codes

    @property
    def cfg_centrifugo_admin_api(self) -> CfgCentrifugoAdminApiAPI:
        """Access Centrifugo Admin API endpoints."""
        return self._client.cfg_centrifugo_admin_api

    @property
    def cfg_centrifugo_auth(self) -> CfgCentrifugoAuthAPI:
        """Access Centrifugo Auth endpoints."""
        return self._client.cfg_centrifugo_auth

    @property
    def cfg_centrifugo_monitoring(self) -> CfgCentrifugoMonitoringAPI:
        """Access Centrifugo Monitoring endpoints."""
        return self._client.cfg_centrifugo_monitoring

    @property
    def cfg_centrifugo_testing(self) -> CfgCentrifugoTestingAPI:
        """Access Centrifugo Testing endpoints."""
        return self._client.cfg_centrifugo_testing

    @property
    def cfg_dashboard_api_zones(self) -> CfgDashboardApiZonesAPI:
        """Access Dashboard - API Zones endpoints."""
        return self._client.cfg_dashboard_api_zones

    @property
    def cfg_dashboard_activity(self) -> CfgDashboardActivityAPI:
        """Access Dashboard - Activity endpoints."""
        return self._client.cfg_dashboard_activity

    @property
    def cfg_dashboard_charts(self) -> CfgDashboardChartsAPI:
        """Access Dashboard - Charts endpoints."""
        return self._client.cfg_dashboard_charts

    @property
    def cfg_dashboard_commands(self) -> CfgDashboardCommandsAPI:
        """Access Dashboard - Commands endpoints."""
        return self._client.cfg_dashboard_commands

    @property
    def cfg_dashboard_config(self) -> CfgDashboardConfigAPI:
        """Access Dashboard - Config endpoints."""
        return self._client.cfg_dashboard_config

    @property
    def cfg_dashboard_overview(self) -> CfgDashboardOverviewAPI:
        """Access Dashboard - Overview endpoints."""
        return self._client.cfg_dashboard_overview

    @property
    def cfg_dashboard_statistics(self) -> CfgDashboardStatisticsAPI:
        """Access Dashboard - Statistics endpoints."""
        return self._client.cfg_dashboard_statistics

    @property
    def cfg_dashboard_system(self) -> CfgDashboardSystemAPI:
        """Access Dashboard - System endpoints."""
        return self._client.cfg_dashboard_system

    @property
    def cfg_dashboard_metrics(self) -> CfgDashboardMetricsAPI:
        """Access Dashboard Metrics endpoints."""
        return self._client.cfg_dashboard_metrics

    @property
    def cfg_oauth(self) -> CfgOauthAPI:
        """Access OAuth endpoints."""
        return self._client.cfg_oauth

    @property
    def cfg_rq_jobs(self) -> CfgRqJobsAPI:
        """Access RQ Jobs endpoints."""
        return self._client.cfg_rq_jobs

    @property
    def cfg_rq_monitoring(self) -> CfgRqMonitoringAPI:
        """Access RQ Monitoring endpoints."""
        return self._client.cfg_rq_monitoring

    @property
    def cfg_rq_queues(self) -> CfgRqQueuesAPI:
        """Access RQ Queues endpoints."""
        return self._client.cfg_rq_queues

    @property
    def cfg_rq_registries(self) -> CfgRqRegistriesAPI:
        """Access RQ Registries endpoints."""
        return self._client.cfg_rq_registries

    @property
    def cfg_rq_schedules(self) -> CfgRqSchedulesAPI:
        """Access RQ Schedules endpoints."""
        return self._client.cfg_rq_schedules

    @property
    def cfg_rq_testing(self) -> CfgRqTestingAPI:
        """Access RQ Testing endpoints."""
        return self._client.cfg_rq_testing

    @property
    def cfg_rq_workers(self) -> CfgRqWorkersAPI:
        """Access RQ Workers endpoints."""
        return self._client.cfg_rq_workers

    @property
    def cfg_totp_management(self) -> CfgTotpManagementAPI:
        """Access TOTP Management endpoints."""
        return self._client.cfg_totp_management

    @property
    def cfg_totp_setup(self) -> CfgTotpSetupAPI:
        """Access TOTP Setup endpoints."""
        return self._client.cfg_totp_setup

    @property
    def cfg_totp_verification(self) -> CfgTotpVerificationAPI:
        """Access TOTP Verification endpoints."""
        return self._client.cfg_totp_verification

    @property
    def cfg_user_profile(self) -> CfgUserProfileAPI:
        """Access User Profile endpoints."""
        return self._client.cfg_user_profile

    @property
    def cfg_accounts(self) -> CfgAccountsAPI:
        """Access accounts endpoints."""
        return self._client.cfg_accounts

    @property
    def cfg_grpc_api_keys(self) -> CfgGrpcApiKeysAPI:
        """Access gRPC API Keys endpoints."""
        return self._client.cfg_grpc_api_keys

    @property
    def cfg_grpc_configuration(self) -> CfgGrpcConfigurationAPI:
        """Access gRPC Configuration endpoints."""
        return self._client.cfg_grpc_configuration

    @property
    def cfg_grpc_monitoring(self) -> CfgGrpcMonitoringAPI:
        """Access gRPC Monitoring endpoints."""
        return self._client.cfg_grpc_monitoring

    @property
    def cfg_grpc_services(self) -> CfgGrpcServicesAPI:
        """Access gRPC Services endpoints."""
        return self._client.cfg_grpc_services

    @property
    def cfg_health(self) -> CfgHealthAPI:
        """Access health endpoints."""
        return self._client.cfg_health

    @property
    def cfg_totp(self) -> CfgTotpAPI:
        """Access totp endpoints."""
        return self._client.cfg_totp

    def get_token(self) -> str | None:
        """Get current JWT token."""
        with self._lock:
            return self._token

    def get_refresh_token(self) -> str | None:
        """Get current refresh token."""
        with self._lock:
            return self._refresh_token

    def set_token(self, token: str, refresh_token: str | None = None) -> None:
        """
        Set JWT token and refresh token.

        Args:
            token: JWT access token
            refresh_token: JWT refresh token (optional)
        """
        with self._lock:
            self._token = token
            if refresh_token:
                self._refresh_token = refresh_token

        # Reinitialize clients with new token
        self._init_clients()

    def clear_tokens(self) -> None:
        """Clear all tokens."""
        with self._lock:
            self._token = None
            self._refresh_token = None

        # Reinitialize clients without token
        self._init_clients()

    def is_authenticated(self) -> bool:
        """Check if user is authenticated."""
        return self.get_token() is not None

    def set_base_url(self, url: str) -> None:
        """
        Update base URL and reinitialize clients.

        Args:
            url: New base URL
        """
        self.base_url = url.rstrip('/')
        self._init_clients()

    def get_base_url(self) -> str:
        """Get current base URL."""
        return self.base_url

    def get_schema_path(self) -> str:
        """
        Get OpenAPI schema path.

        Returns:
            Path to the OpenAPI schema JSON file

        Note:
            The OpenAPI schema is available in the schema.json file.
            You can load it dynamically using:
            ```python
            import json
            from pathlib import Path

            schema_path = Path(__file__).parent / 'schema.json'
            with open(schema_path) as f:
                schema = json.load(f)
            ```
        """
        return './schema.json'

    async def __aenter__(self) -> API:
        """Async context manager entry."""
        if self._client:
            await self._client.__aenter__()
        return self

    async def __aexit__(self, *args: Any) -> None:
        """Async context manager exit."""
        if self._client:
            await self._client.__aexit__(*args)

    async def close(self) -> None:
        """Close HTTP client."""
        if self._client:
            await self._client.close()

__all__ = [
    "API",
    "APIClient",
    "CfgRqTestingScheduleDemoCreateRequestScheduleType",
    "DeviceListStatus",
    "OAuthConnectionProvider",
    "OTPRequestRequestChannel",
    "QuickActionColor",
    "RunDemoRequestRequestScenario",
    "StatCardChangeType",
    "StressTestRequestRequestScenario",
    "SystemHealthOverallStatus",
]