resource "aws_ecs_cluster" "quber" {
  name = "quber"
}

resource "aws_security_group" "task" {
  name        = "quber-task"
  description = "Egress-only security group for the quber Fargate task"
  vpc_id      = data.aws_vpc.default.id

  egress {
    description = "All egress (ECR, S3, Anthropic, Logfire)"
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

locals {
  image          = "${aws_ecr_repository.quber.repository_url}:${var.image_tag}"
  container_name = "quber"
}

resource "aws_ecs_task_definition" "table" {
  family                   = "quber-table"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = var.task_cpu
  memory                   = var.task_memory
  execution_role_arn       = aws_iam_role.task_execution.arn
  task_role_arn            = aws_iam_role.task.arn

  container_definitions = jsonencode([{
    name      = local.container_name
    image     = local.image
    essential = true
    # Overridden per document by the trigger Lambda; this default is harmless.
    command = ["table", "--help"]
    environment = [
      { name = "QUBER_LLM_BACKEND", value = "api" },
      { name = "AWS_REGION", value = var.region },
      { name = "QUBER_S3_REGION", value = var.region },
      { name = "PYTHONUNBUFFERED", value = "1" },
      # LangSmith tracing: the flag and project name are not secret. The tracer
      # stays a no-op unless TRACE_TO_LANGSMITH is true and the API key below is
      # present (see langsmith_tracer.langsmith_enabled).
      { name = "TRACE_TO_LANGSMITH", value = "true" },
      { name = "CC_LANGSMITH_PROJECT", value = "quberai" },
    ]
    secrets = [
      { name = "ANTHROPIC_API_KEY", valueFrom = aws_ssm_parameter.anthropic_api_key.arn },
      { name = "LOGFIRE_TOKEN", valueFrom = aws_ssm_parameter.logfire_token.arn },
      { name = "CC_LANGSMITH_API_KEY", valueFrom = aws_ssm_parameter.langsmith_api_key.arn },
    ]
    logConfiguration = {
      logDriver = "awslogs"
      options = {
        "awslogs-group"         = aws_cloudwatch_log_group.task.name
        "awslogs-region"        = var.region
        "awslogs-stream-prefix" = "table"
      }
    }
  }])

  # The CI deploy registers new revisions with updated images; ignore the image
  # drift here so `terraform apply` does not fight the pipeline.
  lifecycle {
    ignore_changes = [container_definitions]
  }
}
