import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import { Construct } from 'constructs';
import { studioSecrets } from '../secrets/studio-secrets';
import { Platform } from 'aws-cdk-lib/aws-ecr-assets';
import { DatadogAgentServiceProps } from './datadog-agent-utils';

export class DatadogRedisService extends Construct {
  public service: ecs.FargateService;

  constructor(scope: Construct, id: string, props: DatadogAgentServiceProps) {
    super(scope, id); // registers child construct within BackendInfraStack CDK construct

    const datadogTaskDefinition = new ecs.FargateTaskDefinition(this, 'DatadogTaskDef', {
      memoryLimitMiB: 32768,
      cpu: 8192,
      ephemeralStorageGiB: 200,
      family: `datadog-redis-${props.accountStage}`,
    });
    const secrets = studioSecrets(this, props.accountStage, true);

    const image = ecs.ContainerImage.fromAsset('./lib/backend-infra-stack/ecs/datadog-agent-container', {
      platform: Platform.LINUX_AMD64,
    });

    const redisEndpoint =
      props.accountStage === 'staging'
        ? 'valkey-cluster-default.ic34gd.ng.0001.use2.cache.amazonaws.com'
        : 'valkey-cluster-default.9rcjcr.ng.0001.use2.cache.amazonaws.com';

    // Add the Datadog container to the task definition
    const datadogContainer = datadogTaskDefinition.addContainer('DatadogContainer', {
      image,
      logging: new ecs.AwsLogDriver({
        streamPrefix: 'datadog-redis',
      }),
      environment: {
        DD_SITE: 'datadoghq.com',
        ECS_FARGATE: 'true',
        DD_ENV: props.accountStage,
        DD_INTEGRATIONS_ENABLED: 'true',
        AWS_REGION: 'us-east-2',
      },
      secrets: {
        DD_API_KEY: secrets['DD_API_KEY'],
      },
      cpu: 8192,
      memoryLimitMiB: 32768,
      essential: true,
      healthCheck: {
        command: ['CMD-SHELL', 'agent health'],
        interval: cdk.Duration.seconds(30),
        timeout: cdk.Duration.seconds(5),
        retries: 3,
        startPeriod: cdk.Duration.seconds(15),
      },
      dockerLabels: {
        'com.datadoghq.ad.checks': `{
          "redisdb": {
            "init_config": {},
            "instances": [
              {
                "host": "${redisEndpoint}",
                "port": 6379,
                "tags": ["env:${props.accountStage}", "service:celery"],
                "keys": ["celery", "celery_tasks"]
              }
            ]
          }
        }`,
      },
    });

    // Create a security group for the Fargate service
    const datadogSecurityGroup = new ec2.SecurityGroup(this, 'DatadogSecurityGroup', {
      vpc: props.vpc,
      allowAllOutbound: true,
      securityGroupName: `datadog-redis-sg-${props.accountStage}`,
      description: "Security group for datadog redis integrationservice",
    });

    // Define the Fargate service first
    this.service = new ecs.FargateService(this, 'DatadogFargateService', {
      cluster: props.cluster,
      taskDefinition: datadogTaskDefinition,
      serviceName: `datadog-redis-service-${props.accountStage}`,
      deploymentController: {
        type: ecs.DeploymentControllerType.ECS,
      },
      securityGroups: [datadogSecurityGroup],
      vpcSubnets: {
        subnets: props.subnets,
      },
      enableExecuteCommand: true,
      desiredCount: 1,
    });

  }
}
