################
# Providers
################

module "default_tags" {
  source             = "git@github.com:theorchard/terraform-default-tags.git//?ref=2.1.0"
  environment        = var.environment
  application_family = var.application_family
  service_name       = var.service_name
  team_name          = var.team_name
}

provider "aws" {
  region = var.aws_region

  default_tags {
    tags = module.default_tags.tags
  }
}

provider "aws" {
  region  = var.aws_region
  alias   = "networking"
  profile = "networking"

  default_tags {
    tags = module.default_tags.tags
  }
}

terraform {
  backend "s3" {
    bucket  = "orcd-terraform-state"
    key     = "qa/ows-ai-eval-runner/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

################
# Data sources
################

data "aws_caller_identity" "current" {}

module "vpc_info" {
  source      = "git@github.com:theorchard/terraform-vpc-info.git//?ref=3.3.0"
  environment = var.environment
}

data "aws_acm_certificate" "theorchard_io" {
  domain   = "*.theorchard.io"
  statuses = ["ISSUED"]
}

################
# Fargate
################

module "fargate_environment" {
  source = "git@github.com:theorchard/terraform-fargate.git//?ref=6.7.0"

  providers = {
    aws.dns = aws.networking
  }

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family
  aws_region         = var.aws_region
  commit_sha         = "latest"
  container_port     = "8080"
  task_type          = "web_service"
  health_check_path  = "/hello/"
  desired_task_count = 2
  task_cpu           = 1024
  task_memory        = 2048
  maximum_capacity   = 4
  minimum_capacity   = 2

  vpc_id                                   = module.vpc_info.vpc_id
  https_listener_certificate_id            = split("/", data.aws_acm_certificate.theorchard_io.arn)[1]
  fargate_service_subnets                  = module.vpc_info.default_private_subnet_ids
  load_balancer_subnets                    = module.vpc_info.default_private_subnet_ids
  load_balancer_access_logs_s3_bucket_name = "orch-elb-logs"

  iam_managed_policy_attachments = [
    aws_iam_policy.bedrock_policy.arn,
    aws_iam_policy.jobs_table_rw_policy.arn,
  ]

  secrets = [
    {
      # LLM Observability requires agentless mode's API key regardless of the
      # Datadog Agent sidecar — see ddtrace's should_use_agentless() detection.
      # Same shared secret the module already grants the execution role access to.
      DD_API_KEY = "${var.environment}/datadog/DD_API_KEY"
    },
  ]

  environment_variables = [
    {
      # config.py reads os.environ["Environment"] (capital E)
      Environment = var.environment
    },
    {
      DD_TRACE_ENABLED = "1"
    },
    {
      DD_PROFILING_ENABLED = "1"
    },
    {
      DD_LLMOBS_ENABLED = "1"
    },
    {
      DD_LLMOBS_ML_APP = var.service_name
    },
    {
      # Only model with Bedrock account access granted so far — see the app's README open questions.
      BEDROCK_MODEL = "us.anthropic.claude-haiku-4-5-20251001-v1:0"
    },
    {
      BEDROCK_REGION = var.aws_region
    },
    {
      MCP_MAX_TOOL_TURNS = "10"
    },
    {
      JOBS_TABLE_NAME = module.jobs_table.aws_dynamodb_table_id
    },
    {
      JOB_TTL_SECONDS = "21600"
    },
    {
      SENTRY_DSN = module.sentry.sentry_key_dsn_public_output
    },
  ]
}

################
# DynamoDB — eval jobs table
################

module "jobs_table" {
  source = "git@github.com:theorchard/terraform-dynamodb.git//?ref=3.3.1"

  env                   = var.environment
  table_name            = "ows-ai-eval-runner-jobs"
  application_family    = var.application_family
  hash_key              = "job_id"
  ttl_attribute_name    = "expires_at"
  ttl_enabled           = true
  use_custom_table_name = true
  custom_table_name     = "${var.environment}-${var.service_name}-jobs"

  attribute = [
    {
      name = "job_id"
      type = "S"
    },
  ]
  # No attribute entry needed for expires_at — TTL attributes aren't part of
  # AttributeDefinitions/KeySchema, only actual keys/index keys are.
}

data "aws_iam_policy_document" "jobs_table_rw_policy_document" {
  statement {
    effect    = "Allow"
    actions   = ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem"]
    resources = [module.jobs_table.aws_dynamodb_table_arn]
  }
}

resource "aws_iam_policy" "jobs_table_rw_policy" {
  name   = "Dynamo-${var.environment}-${var.service_name}-jobs-RW"
  policy = data.aws_iam_policy_document.jobs_table_rw_policy_document.json
}

################
# IAM — Bedrock
################

# Inference-only access, scoped to Haiku only (the only model this account has
# access to so far — extend to other models once Marketplace access is granted).
data "aws_iam_policy_document" "bedrock_policy_document" {
  statement {
    sid    = "AllowBedrockModelInvoke"
    effect = "Allow"

    actions = [
      "bedrock:InvokeModel",
      "bedrock:InvokeModelWithResponseStream",
    ]

    resources = [
      "arn:aws:bedrock:us-*::foundation-model/anthropic.claude-haiku-4-5-*",
      "arn:aws:bedrock:us-*:${data.aws_caller_identity.current.account_id}:inference-profile/us.anthropic.claude-haiku-4-5-*",
    ]
  }
}

resource "aws_iam_policy" "bedrock_policy" {
  name        = "${var.environment}-${var.service_name}-bedrock-policy"
  description = "Allow ows-ai-eval-runner to invoke Claude Haiku via Bedrock"
  policy      = data.aws_iam_policy_document.bedrock_policy_document.json
}

resource "aws_iam_role_policy_attachment" "bedrock_policy_attachment" {
  role       = module.fargate_environment.fargate_task_iam_role_name
  policy_arn = aws_iam_policy.bedrock_policy.arn
}

################
# Sentry
################

module "sentry" {
  source = "git@github.com:theorchard/terraform-sentry.git//?ref=5.1.0"

  environment        = var.environment
  platform           = "python"
  service_name       = var.service_name
  teams              = [var.environment]
  application_family = var.application_family
}

################
# Datadog
################

module "service_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/service?ref=6.19.0"

  environment                       = var.environment
  environment_type                  = "fargate"
  service_name                      = var.service_name
  application_family                = var.application_family
  teams                             = [var.team_name]
  notification_endpoints            = "@slack-qa-automation"
  escalation_notification_endpoints = "@slack-qa-automation"
}
