# Amazon Ergo playground backend: one streaming Lambda that calls Bedrock ConverseStream.
# The API in front of it is in api.tf and its web ACL in waf.tf.

data "aws_caller_identity" "current" {}

# Shared sign-in (Cognito pool, web client, site origin) from the platform stack.
data "terraform_remote_state" "platform" {
  backend = "local"

  config = {
    path = "${path.module}/../../../../platform/terraform/terraform.tfstate"
  }
}

locals {
  auth     = data.terraform_remote_state.platform.outputs.auth
  model_id = "global.amazon.ergo-1.0"

  # Ergo is served through cross-Region inference only, so a call touches the profile and the
  # foundation model in whichever Region serves it.
  ergo_arns = [
    "arn:aws:bedrock:*:*:inference-profile/us.amazon.ergo-1.0",
    "arn:aws:bedrock:*:*:inference-profile/global.amazon.ergo-1.0",
    "arn:aws:bedrock:*::foundation-model/amazon.ergo-1.0",
  ]
}

# The zip holds only the handler; the SDK comes from the Lambda runtime.
data "archive_file" "chat" {
  type        = "zip"
  source_file = "${path.module}/../lambda/index.mjs"
  output_path = "${path.module}/../../build/chat.zip"
}

resource "aws_cloudwatch_log_group" "chat" {
  name              = "/aws/lambda/${local.name}"
  retention_in_days = 14
}

data "aws_iam_policy_document" "chat_assume" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["lambda.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "chat" {
  statement {
    sid       = "InvokeErgo"
    actions   = ["bedrock:InvokeModel", "bedrock:InvokeModelWithResponseStream"]
    resources = local.ergo_arns
  }

  statement {
    sid       = "WriteOwnLogs"
    actions   = ["logs:CreateLogStream", "logs:PutLogEvents"]
    resources = ["${aws_cloudwatch_log_group.chat.arn}:*"]
  }

  # X-Ray write actions do not support resource-level permissions.
  statement {
    sid       = "WriteTraces"
    actions   = ["xray:PutTraceSegments", "xray:PutTelemetryRecords"]
    resources = ["*"]
  }
}

resource "aws_iam_role" "chat" {
  name               = "${local.name}-chat"
  assume_role_policy = data.aws_iam_policy_document.chat_assume.json
}

resource "aws_iam_role_policy" "chat" {
  name   = "invoke-ergo"
  role   = aws_iam_role.chat.id
  policy = data.aws_iam_policy_document.chat.json
}

resource "aws_lambda_function" "chat" {
  function_name    = local.name
  role             = aws_iam_role.chat.arn
  runtime          = "nodejs26.x"
  architectures    = ["arm64"]
  handler          = "index.handler"
  filename         = data.archive_file.chat.output_path
  source_code_hash = data.archive_file.chat.output_base64sha256
  memory_size      = 256
  timeout          = 120

  # Cost guard: at most five model calls run at once.
  reserved_concurrent_executions = 5

  environment {
    variables = {
      MODEL_ID       = local.model_id
      ALLOWED_ORIGIN = local.auth.site_origin
    }
  }

  tracing_config {
    mode = "Active"
  }

  logging_config {
    log_format = "Text"
    log_group  = aws_cloudwatch_log_group.chat.name
  }

  depends_on = [aws_iam_role_policy.chat]
}

resource "aws_lambda_permission" "api" {
  statement_id  = "AllowChatMethod"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.chat.function_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_api_gateway_rest_api.this.execution_arn}/*/POST/chat"
}
