################
# IAM — Bedrock
################
#
# Inference-only access to Claude models (same shape as ows-coda / graphql-abacus).
# Cross-Region inference profiles (the `us.` prefix) route across US regions for
# availability, so each model needs both a foundation-model ARN and an
# inference-profile ARN. The region segment is intentionally `us-*` (not just the run
# region): a cross-Region profile may be served from any US region, so narrowing the
# resource ARNs to us-east-1/us-west-2 would break that routing. The us-east-1/us-west-2
# constraint is on where the *runner* runs (var.aws_region), not where Bedrock routes.
#
# The managed policy is attached to the shared cross-account `generic-engineer-role`
# (see generic-engineer-role.tf) and exported (outputs.tf) so CI or other roles can
# attach it too.

locals {
  account_id = data.aws_caller_identity.current.account_id

  bedrock_model_arns = concat(
    [for p in var.bedrock_model_id_patterns : "arn:aws:bedrock:us-*::foundation-model/${p}"],
    [for p in var.bedrock_model_id_patterns : "arn:aws:bedrock:us-*:${local.account_id}:inference-profile/us.${p}"],
  )
}

data "aws_iam_policy_document" "bedrock_invoke" {
  statement {
    sid    = "AllowBedrockModelInvoke"
    effect = "Allow"

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

    resources = local.bedrock_model_arns
  }
}

resource "aws_iam_policy" "bedrock_invoke" {
  name        = "${var.environment}-${var.service_name}-bedrock-policy"
  description = "Inference-only Bedrock access for the skill-eval-runner eval harness"
  policy      = data.aws_iam_policy_document.bedrock_invoke.json
}
