from __future__ import annotations

from pathlib import Path
from typing import Any

from vyro.runtime import (
    ABIStablePluginSystem,
    APIKeyManager,
    AsyncHttpClient,
    AuthorizationCore,
    BackpressureController,
    BlueGreenRolloutHelper,
    CacheBackend,
    CacheInvalidationHooks,
    CanaryRoutingControls,
    CommandBus,
    ContentNegotiator,
    CORSProfile,
    CronScheduler,
    CSRFProtector,
    DBConnectionPoolManager,
    DeadLetterQueue,
    ETagManager,
    ExtensionMarketplaceManifest,
    FeatureFlagEngine,
    GracefulShutdownPolicy,
    GrpcGateway,
    Http2StreamManager,
    InternalEventBus,
    JobRetryExecutor,
    JobRuntime,
    JWTAuthGuard,
    KubernetesManifestGenerator,
    MemoryCacheBackend,
    MigrationRunner,
    MultiKeyRateLimiter,
    MultipartParser,
    MultipartUploadStream,
    NoGILWorkerTuner,
    OAuth2OIDCHelper,
    OAUTH2_DEFAULT_CONFIG,
    OutboundBulkhead,
    OutboundCircuitBreaker,
    OutboxPatternHelper,
    QueryBus,
    QueryExecutionPolicy,
    ResponseCacheService,
    ResponseCompressor,
    RetryPolicy,
    RouteConcurrencyLimiter,
    SagaOrchestrator,
    SafeRuntimeConfigReloader,
    SchemaDriftDetector,
    SecretsManager,
    SecurityAuditLogger,
    ServiceDiscoveryRegistry,
    SQLiteAsyncAdapter,
    StaticFileService,
    TenantIsolationModel,
    TenantRoutingConfig,
    TimeoutBudget,
    TokenBucketRateLimiter,
    TransactionScope,
    WebSocketRouteRegistry,
)
from vyro.middleware.idempotency import IdempotencyKeyMiddleware
from vyro.settings import DEFAULT_STATIC_ROOT


def build_default_components() -> dict[str, Any]:
    cache: CacheBackend = MemoryCacheBackend()
    dead_letter_queue = DeadLetterQueue()
    return {
        "idempotency": IdempotencyKeyMiddleware(),
        "authz": AuthorizationCore(),
        "api_keys": APIKeyManager(),
        "audit": SecurityAuditLogger(),
        "cache": cache,
        "cache_invalidation": CacheInvalidationHooks(),
        "blue_green": BlueGreenRolloutHelper(),
        "bulkhead": OutboundBulkhead(),
        "canary": CanaryRoutingControls(),
        "circuit_breaker": OutboundCircuitBreaker(),
        "compression": ResponseCompressor(),
        "concurrency": RouteConcurrencyLimiter(),
        "cors": CORSProfile.preset("standard"),
        "cron": CronScheduler(),
        "command_bus": CommandBus(),
        "query_bus": QueryBus(),
        "csrf": CSRFProtector.with_random_secret(),
        "db_pools": DBConnectionPoolManager(),
        "dead_letter_queue": dead_letter_queue,
        "job_retry": JobRetryExecutor(dead_letter_queue=dead_letter_queue),
        "discovery": ServiceDiscoveryRegistry(),
        "etag": ETagManager(),
        "event_bus": InternalEventBus(),
        "feature_flags": FeatureFlagEngine(),
        "grpc_gateway": GrpcGateway(),
        "hot_reload": SafeRuntimeConfigReloader(),
        "http_client": AsyncHttpClient(),
        "http2_streams": Http2StreamManager(),
        "jwt": JWTAuthGuard(secret=b"vyro-dev-secret"),
        "jobs": JobRuntime(),
        "k8s_generator": KubernetesManifestGenerator(),
        "multipart_upload": MultipartUploadStream(boundary=b"vyro-default"),
        "multipart_parser": MultipartParser(),
        "migrations": MigrationRunner(database=Path("app.db"), migrations_dir=Path("migrations")),
        "marketplace": ExtensionMarketplaceManifest(),
        "negotiator": ContentNegotiator(),
        "nogil_tuner": NoGILWorkerTuner(),
        "oauth2": OAuth2OIDCHelper(config=OAUTH2_DEFAULT_CONFIG),
        "outbox": OutboxPatternHelper(),
        "plugins": ABIStablePluginSystem(),
        "rate_limiter": TokenBucketRateLimiter(rate_per_sec=1000.0, burst=2000),
        "multi_rate_limiter": MultiKeyRateLimiter(rate_per_sec=500.0, burst=1000),
        "response_cache": ResponseCacheService(backend=cache),
        "retry_policy": RetryPolicy(),
        "saga": SagaOrchestrator(),
        "schema_drift": SchemaDriftDetector(database=Path("app.db")),
        "secrets": SecretsManager(),
        "shutdown_policy": GracefulShutdownPolicy(),
        "sql": SQLiteAsyncAdapter(database=Path(":memory:")),
        "sql_policy": QueryExecutionPolicy(),
        "static_files": StaticFileService(root=Path(DEFAULT_STATIC_ROOT)),
        "tenant_isolation": TenantIsolationModel(),
        "tenant_routing": TenantRoutingConfig(),
        "timeout_budget": TimeoutBudget(timeout_sec=30.0),
        "transaction": TransactionScope(),
        "websocket": WebSocketRouteRegistry(),
        "backpressure": BackpressureController(),
    }
