name: "~ OSDC: Plan (reusable)"

on:
  workflow_call:
    inputs:
      cluster:
        required: true
        type: string
      pr_number:
        required: true
        type: number
      environment:
        description: "GitHub environment for secrets/gating (default: osdc-staging)"
        required: false
        type: string
        default: osdc-staging
      use_lf_credentials:
        description: "Use LF_AWS_PLAN_ROLE_ARN secret instead of Meta AWS credentials"
        required: false
        type: boolean
        default: false

permissions:
  id-token: write
  contents: read
  pull-requests: write

defaults:
  run:
    working-directory: osdc

jobs:
  plan:
    name: tofu plan (${{ inputs.cluster }})
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment }}
    timeout-minutes: 45
    # Serialize all tofu state-locking work per cluster. Shared with
    # _osdc-deploy.yml so plan and deploy against the same cluster never
    # race on the DynamoDB state lock.
    concurrency:
      group: osdc-tofu-${{ inputs.cluster }}
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1

      - name: Install just
        uses: extractions/setup-just@f8a3cce218d9f83db3a2ecd90e41ac3de6cdfd9b # v3.1.0

      - name: Install mise
        uses: jdx/mise-action@c37c93293d6b742fc901e1406b8f764f6fb19dac # v2.4.4
        with:
          version: "2026.5.11"
          install: true
          working_directory: osdc

      - name: Install Python dependencies
        run: uv sync

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@b47578312673ae6fa5b5096b330d9fbac3d116df # v4.2.1
        with:
          role-to-assume: ${{ inputs.use_lf_credentials && secrets.LF_AWS_PLAN_ROLE_ARN || format('arn:aws:iam::{0}:role/{1}', secrets.META_AWS_ACC_ID, secrets.META_AWS_DEPLOY_PLAN_ROLE) }}
          aws-region: us-west-2
          role-duration-seconds: 3600

      - name: Run tofu plan
        id: plan
        continue-on-error: true
        env:
          TF_IN_AUTOMATION: "1"
        run: |
          set -o pipefail
          just plan ${{ inputs.cluster }} 2>&1 | tee plan.txt

      - name: Post plan to PR
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ inputs.pr_number }}
          REPO: ${{ github.repository }}
          PLAN_OUTCOME: ${{ steps.plan.outcome }}
          CLUSTER: ${{ inputs.cluster }}
          MARKER: "<!-- osdc-plan-prod-${{ inputs.cluster }} -->"
        run: |
          set -euo pipefail
          MAX=60000
          if [ "$(wc -c < plan.txt)" -gt "$MAX" ]; then
              head -c "$MAX" plan.txt > plan-trimmed.txt
              printf '\n... (truncated — see workflow logs for full plan)\n' >> plan-trimmed.txt
              mv plan-trimmed.txt plan.txt
          fi
          if [ "$PLAN_OUTCOME" = "success" ]; then
              STATUS="✅ Plan succeeded"
          else
              STATUS="❌ Plan failed"
          fi
          {
              echo "$MARKER"
              echo "### tofu plan — ${CLUSTER}"
              echo ""
              echo "$STATUS · commit \`${GITHUB_SHA::8}\` · [run log](${GITHUB_SERVER_URL}/${REPO}/actions/runs/${GITHUB_RUN_ID})"
              echo ""
              echo '<details><summary>Plan output</summary>'
              echo ""
              echo '```'
              cat plan.txt
              echo '```'
              echo ""
              echo '</details>'
          } > body.md

          EXISTING=$(gh api "/repos/${REPO}/issues/${PR_NUMBER}/comments" \
              --jq ".[] | select(.body | startswith(\"${MARKER}\")) | .id" | head -n1)
          BODY_JSON=$(jq -Rs '{body: .}' body.md)
          if [ -n "$EXISTING" ]; then
              echo "Updating existing comment $EXISTING"
              echo "$BODY_JSON" | gh api --method PATCH --input - \
                  "/repos/${REPO}/issues/comments/${EXISTING}" >/dev/null
          else
              echo "Creating new comment"
              echo "$BODY_JSON" | gh api --method POST --input - \
                  "/repos/${REPO}/issues/${PR_NUMBER}/comments" >/dev/null
          fi

      - name: Fail the job if plan failed
        if: steps.plan.outcome != 'success'
        run: |
          echo "tofu plan failed — see the plan step logs and the PR comment for details."
          exit 1
