AWSTemplateFormatVersion: '2010-09-09'
Description: 'Simple Qdrant on ECS Fargate - Single node without EFS (for testing)'

Parameters:
  EnvironmentName:
    Type: String
    Default: dev
    Description: Environment name

Resources:
  # VPC
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName}-qdrant-simple-vpc

  InternetGateway:
    Type: AWS::EC2::InternetGateway

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC

  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [0, !GetAZs '']
      CidrBlock: 10.0.1.0/24
      MapPublicIpOnLaunch: true

  PublicSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [1, !GetAZs '']
      CidrBlock: 10.0.2.0/24
      MapPublicIpOnLaunch: true

  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC

  DefaultRoute:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref RouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  SubnetRouteTableAssociation1:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref RouteTable
      SubnetId: !Ref PublicSubnet1

  SubnetRouteTableAssociation2:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref RouteTable
      SubnetId: !Ref PublicSubnet2

  # Security Groups
  LoadBalancerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Security group for load balancer
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 6334
          ToPort: 6334
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 6333
          ToPort: 6333
          CidrIp: 0.0.0.0/0

  QdrantSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Security group for Qdrant
      VpcId: !Ref VPC

  QdrantSecurityGroupIngressHTTP:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref QdrantSecurityGroup
      IpProtocol: tcp
      FromPort: 6333
      ToPort: 6333
      SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup

  QdrantSecurityGroupIngressGRPC:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref QdrantSecurityGroup
      IpProtocol: tcp
      FromPort: 6334
      ToPort: 6334
      SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup

  # ECS Cluster
  ECSCluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Sub ${EnvironmentName}-qdrant-simple

  # CloudWatch Logs
  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /ecs/${EnvironmentName}-qdrant-simple
      RetentionInDays: 7

  # IAM Roles
  TaskExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy

  TaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
            Action: 'sts:AssumeRole'

  # Task Definition (NO EFS - using task storage)
  TaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub ${EnvironmentName}-qdrant-simple
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      Cpu: '1024'
      Memory: '2048'
      ExecutionRoleArn: !Ref TaskExecutionRole
      TaskRoleArn: !Ref TaskRole
      ContainerDefinitions:
        - Name: qdrant
          Image: qdrant/qdrant:latest
          Essential: true
          PortMappings:
            - ContainerPort: 6333
              Protocol: tcp
            - ContainerPort: 6334
              Protocol: tcp
          Environment:
            - Name: QDRANT__SERVICE__HTTP_PORT
              Value: '6333'
            - Name: QDRANT__SERVICE__GRPC_PORT
              Value: '6334'
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref LogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: qdrant
          HealthCheck:
            Command:
              - CMD-SHELL
              - wget --no-verbose --tries=1 --spider http://localhost:6333/health || exit 1
            Interval: 30
            Timeout: 5
            Retries: 3
            StartPeriod: 60

  # Network Load Balancer
  NetworkLoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: !Sub ${EnvironmentName}-qdrant-nlb
      Type: network
      Scheme: internet-facing
      Subnets:
        - !Ref PublicSubnet1
        - !Ref PublicSubnet2

  TargetGroupGRPC:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Sub ${EnvironmentName}-qdrant-grpc
      Port: 6334
      Protocol: TCP
      VpcId: !Ref VPC
      TargetType: ip
      HealthCheckEnabled: true
      HealthCheckProtocol: HTTP
      HealthCheckPort: '6333'
      HealthCheckPath: /health

  TargetGroupHTTP:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: !Sub ${EnvironmentName}-qdrant-http
      Port: 6333
      Protocol: TCP
      VpcId: !Ref VPC
      TargetType: ip
      HealthCheckEnabled: true
      HealthCheckProtocol: HTTP
      HealthCheckPort: '6333'
      HealthCheckPath: /health

  ListenerGRPC:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref NetworkLoadBalancer
      Port: 6334
      Protocol: TCP
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref TargetGroupGRPC

  ListenerHTTP:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref NetworkLoadBalancer
      Port: 6333
      Protocol: TCP
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref TargetGroupHTTP

  # ECS Service
  Service:
    Type: AWS::ECS::Service
    DependsOn:
      - ListenerGRPC
      - ListenerHTTP
    Properties:
      ServiceName: !Sub ${EnvironmentName}-qdrant-simple-service
      Cluster: !Ref ECSCluster
      TaskDefinition: !Ref TaskDefinition
      DesiredCount: 1
      LaunchType: FARGATE
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          SecurityGroups:
            - !Ref QdrantSecurityGroup
          Subnets:
            - !Ref PublicSubnet1
            - !Ref PublicSubnet2
      LoadBalancers:
        - TargetGroupArn: !Ref TargetGroupGRPC
          ContainerName: qdrant
          ContainerPort: 6334
        - TargetGroupArn: !Ref TargetGroupHTTP
          ContainerName: qdrant
          ContainerPort: 6333
      HealthCheckGracePeriodSeconds: 60

Outputs:
  LoadBalancerDNS:
    Value: !GetAtt NetworkLoadBalancer.DNSName

  QdrantGRPCEndpoint:
    Value: !Sub http://${NetworkLoadBalancer.DNSName}:6334

  QdrantHTTPEndpoint:
    Value: !Sub http://${NetworkLoadBalancer.DNSName}:6333

  QdrantDashboard:
    Value: !Sub http://${NetworkLoadBalancer.DNSName}:6333/dashboard
