import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as awsx from "@pulumi/awsx";
import * as docker from "@pulumi/docker";



type STACK_NAME = 'staging' | 'prod'

const org = pulumi.getOrganization();

const stackRef = new pulumi.StackReference(`${org}/discord-bot/discord-staging`)
const stackName = pulumi.getStack();
const env = stackName.indexOf('staging') >= 0 ? 'staging' : 'prod';

console.log('here', env)
const sunoAiZone = aws.route53.getZoneOutput({ name: "suno.ai" })
// export const infraStack = new pulumi.StackReference(`${org}/suno-infra/${stack}`)


// const apiCertArn = infraStack.getOutput('apiCertArn');
// const vpcId = infraStack.getOutput('vpcId') as pulumi.Output<string>;
// const vpcPrivateSubnets = infraStack.getOutput('vpcPrivateSubnets') as pulumi.Output<string[]>;


if (env === 'staging') {
  const apiCert = new aws.acm.Certificate(
    'discord-api-cert', {
    domainName: '*.suno.ai',
    validationMethod: 'DNS'
  })
}

const repoName = env == 'prod' ? 'studio-api-prod' : 'studio-api-base';
const botImageRepo = new awsx.ecr.Repository(
  repoName,
  {
    name: repoName,
  },

)
const authToken = aws.ecr.getAuthorizationTokenOutput({
  registryId: botImageRepo.repository.registryId,
});


const image = new docker.Image("studio-api-image", {
  build: {
    args: {
      BUILDKIT_INLINE_CACHE: "1",
    },
    cacheFrom: {
      images: [pulumi.interpolate`${botImageRepo.repository.repositoryUrl}:latest`],
    },
    context: "../../studio_api",
    dockerfile: "../../studio_api/Dockerfile.bot",
    platform: "linux/amd64",
  },
  imageName: pulumi.interpolate`${botImageRepo.repository.repositoryUrl}:latest`,
  registry: {
    username: pulumi.secret(authToken.apply(authToken => authToken.userName)),
    password: pulumi.secret(authToken.apply(authToken => authToken.password)),
    server: botImageRepo.repository.repositoryUrl,
  },
});

const cluster = new awsx.classic.ecs.Cluster(`suno-${env}`);

const alb = new awsx.lb.ApplicationLoadBalancer(`discord-${env}`);

const dnsRecord = new aws.route53.Record(
  `discord-${env}`,
  {
    zoneId: sunoAiZone.zoneId,
    name: env == 'prod' ? 'dc.suno.ai' : `dc-staging.suno.ai`,
    type: 'A',
    aliases: [{
      name: alb.loadBalancer.dnsName,
      zoneId: alb.loadBalancer.zoneId,
      evaluateTargetHealth: true,
    }],
  }
)


let defaultTargetGroup = new aws.lb.TargetGroup(`discord-${env}`, {
  port: 8080,
  protocol: "HTTP",
  targetType: "ip",
  vpcId: alb.loadBalancer.vpcId,
  healthCheck: {
    path: '/status/',
  },
});

let listener = new aws.lb.Listener("listener", {
  loadBalancerArn: alb.loadBalancer.arn,
  port: 443,
  protocol: "HTTPS",
  sslPolicy: "ELBSecurityPolicy-2016-08",
  certificateArn: 'arn:aws:acm:us-east-1:734185074900:certificate/7267093e-d4fb-4328-be8c-199e026a0e18',
  defaultActions: [{
    type: "forward",
    targetGroupArn: defaultTargetGroup.arn
  }]
});

const service = new awsx.ecs.FargateService(`discord-${env}`, {
  cluster: cluster.cluster.arn,
  desiredCount: env === 'prod' ? 6 : 2,
  assignPublicIp: true,
  deploymentMinimumHealthyPercent: 66,
  taskDefinitionArgs: {
    containers: {
      bot: {
        image: image.imageName,
        memory: 1024,
        cpu: 512,
        portMappings: [{
          targetGroup: defaultTargetGroup,
          containerPort: 8080,
          hostPort: 8080,
          protocol: 'HTTP',
        }],
        "logConfiguration": {
          "logDriver": "awsfirelens"
        }
      },
      logRouter: {
        image: "betterstack/aws-ecs-fluent-bit:amd64-latest",
        essential: true,
        environment: [
          {
            name: "LOGTAIL_SOURCE_TOKEN",
            value: env === 'prod' ? 'RhW1JGqJgfBhk2huQkFkhQwR' : "GzhsVmoPYPfFcYdNY3BTCHiK",
          }
        ],

        name: 'log_router',
        memoryReservation: 50,

        firelensConfiguration: {
          "type": "fluentbit",
          "options": {
            "config-file-type": "file",
            "config-file-value": "/fluent-bit-logtail.conf",
            "enable-ecs-log-metadata": "true"
          }
        }
      }
    },
  },
});
