import { Module } from "@nestjs/common";
import { APP_INTERCEPTOR, APP_GUARD } from "@nestjs/core";
import { ThrottlerModule } from "@nestjs/throttler";
import { BullModule } from "@nestjs/bullmq";
import { ScheduleModule } from "@nestjs/schedule";
import { ThrottlerValkeyStorageService, ThrottlerApiKeyGuard } from "./common/throttler";
import { CsrfGuard } from "./common/guards/csrf.guard";
import { CsrfService } from "./common/services/csrf.service";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { CsrfController } from "./common/controllers/csrf.controller";
import { PrismaModule } from "./prisma/prisma.module";
import { DatabaseModule } from "./database/database.module";
import { AuthModule } from "./auth/auth.module";
import { ActivityModule } from "./activity/activity.module";
import { TasksModule } from "./tasks/tasks.module";
import { EventsModule } from "./events/events.module";
import { ProjectsModule } from "./projects/projects.module";
import { DomainsModule } from "./domains/domains.module";
import { IdeasModule } from "./ideas/ideas.module";
import { WidgetsModule } from "./widgets/widgets.module";
import { LayoutsModule } from "./layouts/layouts.module";
import { KnowledgeModule } from "./knowledge/knowledge.module";
import { UsersModule } from "./users/users.module";
import { WebSocketModule } from "./websocket/websocket.module";
import { LlmModule } from "./llm/llm.module";
import { LlmUsageModule } from "./llm-usage/llm-usage.module";
import { BrainModule } from "./brain/brain.module";
import { CronModule } from "./cron/cron.module";
import { AgentTasksModule } from "./agent-tasks/agent-tasks.module";
import { FindingsModule } from "./findings/findings.module";
import { AgentMemoryModule } from "./agent-memory/agent-memory.module";
import { ValkeyModule } from "./valkey/valkey.module";
import { BullMqModule } from "./bullmq/bullmq.module";
import { StitcherModule } from "./stitcher/stitcher.module";
import { TelemetryModule, TelemetryInterceptor } from "./telemetry";
import { RunnerJobsModule } from "./runner-jobs/runner-jobs.module";
import { JobEventsModule } from "./job-events/job-events.module";
import { JobStepsModule } from "./job-steps/job-steps.module";
import { CoordinatorIntegrationModule } from "./coordinator-integration/coordinator-integration.module";
import { FederationModule } from "./federation/federation.module";
import { CredentialsModule } from "./credentials/credentials.module";
import { CryptoModule } from "./crypto/crypto.module";
import { MosaicTelemetryModule } from "./mosaic-telemetry";
import { SpeechModule } from "./speech/speech.module";
import { DashboardModule } from "./dashboard/dashboard.module";
import { TerminalModule } from "./terminal/terminal.module";
import { PersonalitiesModule } from "./personalities/personalities.module";
import { WorkspacesModule } from "./workspaces/workspaces.module";
import { AdminModule } from "./admin/admin.module";
import { AgentTemplateModule } from "./agent-template/agent-template.module";
import { UserAgentModule } from "./user-agent/user-agent.module";
import { TeamsModule } from "./teams/teams.module";
import { ImportModule } from "./import/import.module";
import { ConversationArchiveModule } from "./conversation-archive/conversation-archive.module";
import { RlsContextInterceptor } from "./common/interceptors/rls-context.interceptor";
import { AgentConfigModule } from "./agent-config/agent-config.module";
import { ContainerLifecycleModule } from "./container-lifecycle/container-lifecycle.module";
import { ContainerReaperModule } from "./container-reaper/container-reaper.module";
import { FleetSettingsModule } from "./fleet-settings/fleet-settings.module";
import { OnboardingModule } from "./onboarding/onboarding.module";
import { ChatProxyModule } from "./chat-proxy/chat-proxy.module";
import { MissionControlProxyModule } from "./mission-control-proxy/mission-control-proxy.module";
import { OrchestratorModule } from "./orchestrator/orchestrator.module";
import { QueueNotificationsModule } from "./queue-notifications/queue-notifications.module";
import { GatekeeperModule } from "./gatekeeper/gatekeeper.module";

@Module({
  imports: [
    // Rate limiting configuration
    ThrottlerModule.forRootAsync({
      useFactory: () => {
        const ttl = parseInt(process.env.RATE_LIMIT_TTL ?? "60", 10) * 1000; // Convert to milliseconds
        const limit = parseInt(process.env.RATE_LIMIT_GLOBAL_LIMIT ?? "100", 10);

        return {
          throttlers: [
            {
              ttl,
              limit,
            },
          ],
          storage: new ThrottlerValkeyStorageService(),
        };
      },
    }),
    // BullMQ job queue configuration
    BullModule.forRoot({
      connection: (() => {
        const url = new URL(process.env.VALKEY_URL ?? "redis://localhost:6379");
        return {
          host: url.hostname,
          port: parseInt(url.port || "6379", 10),
        };
      })(),
    }),
    ScheduleModule.forRoot(),
    TelemetryModule,
    PrismaModule,
    DatabaseModule,
    ValkeyModule,
    BullMqModule,
    StitcherModule,
    AuthModule,
    ActivityModule,
    TasksModule,
    EventsModule,
    ProjectsModule,
    DomainsModule,
    IdeasModule,
    WidgetsModule,
    LayoutsModule,
    KnowledgeModule,
    UsersModule,
    WebSocketModule,
    LlmModule,
    LlmUsageModule,
    BrainModule,
    CronModule,
    AgentTasksModule,
    FindingsModule,
    AgentMemoryModule,
    RunnerJobsModule,
    JobEventsModule,
    JobStepsModule,
    CoordinatorIntegrationModule,
    FederationModule,
    CredentialsModule,
    CryptoModule,
    MosaicTelemetryModule,
    SpeechModule,
    DashboardModule,
    TerminalModule,
    PersonalitiesModule,
    WorkspacesModule,
    AdminModule,
    AgentTemplateModule,
    UserAgentModule,
    TeamsModule,
    ImportModule,
    ConversationArchiveModule,
    AgentConfigModule,
    ContainerLifecycleModule,
    ContainerReaperModule,
    FleetSettingsModule,
    OnboardingModule,
    ChatProxyModule,
    MissionControlProxyModule,
    OrchestratorModule,
    GatekeeperModule,
    QueueNotificationsModule,
  ],
  controllers: [AppController, CsrfController],
  providers: [
    AppService,
    CsrfService,
    {
      provide: APP_INTERCEPTOR,
      useClass: TelemetryInterceptor,
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: RlsContextInterceptor,
    },
    {
      provide: APP_GUARD,
      useClass: ThrottlerApiKeyGuard,
    },
    {
      provide: APP_GUARD,
      useClass: CsrfGuard,
    },
  ],
})
export class AppModule {}
