#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TARGET_GO_VERSION="1.26.2"

GO_MOD="$ROOT_DIR/backend/go.mod"
BACKEND_DOCKERFILE="$ROOT_DIR/backend/Dockerfile"
LOCAL_COMPOSE="$ROOT_DIR/docker-compose.yaml"
STAGING_COMPOSE="$ROOT_DIR/docker/docker-compose.staging.template.yaml"
PULL_COMPOSE="$ROOT_DIR/docker/staging_pull_compose.template.yaml"
DEPLOY_TEMPLATE="$ROOT_DIR/deploy/templates/docker-compose.yaml"
README="$ROOT_DIR/README.md"
README_EN="$ROOT_DIR/README_en.md"
TEST_GUIDE="$ROOT_DIR/docs/TEST_GUIDE.md"
COMPLETION_REPORT="$ROOT_DIR/docs/개발완료보고서.md"

for file in \
  "$GO_MOD" \
  "$BACKEND_DOCKERFILE" \
  "$LOCAL_COMPOSE" \
  "$STAGING_COMPOSE" \
  "$PULL_COMPOSE" \
  "$DEPLOY_TEMPLATE" \
  "$README" \
  "$README_EN" \
  "$TEST_GUIDE" \
  "$COMPLETION_REPORT"
do
  if [[ ! -f "$file" ]]; then
    echo "ERROR: expected file not found: $file" >&2
    exit 1
  fi
done

if ! grep -Eq "^go ${TARGET_GO_VERSION}$" "$GO_MOD"; then
  echo "ERROR: backend go.mod must use go ${TARGET_GO_VERSION}." >&2
  exit 1
fi

if ! grep -Eq "^FROM golang:${TARGET_GO_VERSION}-alpine$" "$BACKEND_DOCKERFILE"; then
  echo "ERROR: backend Dockerfile must use golang:${TARGET_GO_VERSION}-alpine." >&2
  exit 1
fi

for file in "$LOCAL_COMPOSE" "$PULL_COMPOSE"; do
  if ! grep -Fq "context: ./backend" "$file" && ! grep -Fq "context: ../../backend" "$file"; then
    echo "ERROR: backend compose build context is missing in $file." >&2
    exit 1
  fi
done

for file in "$STAGING_COMPOSE" "$DEPLOY_TEMPLATE"; do
  if ! grep -Eq "^[[:space:]]+backend:$" "$file"; then
    echo "ERROR: backend service is missing in $file." >&2
    exit 1
  fi
done

legacy_refs="$(
  grep -R -nE "golang:1\\.25|^go 1\\.25" \
    "$ROOT_DIR/backend" \
    "$ROOT_DIR/docker-compose.yaml" \
    "$ROOT_DIR/docker" \
    "$ROOT_DIR/deploy/templates" \
    "$README" \
    "$README_EN" \
    "$TEST_GUIDE" \
    "$COMPLETION_REPORT" || true
)"

if [[ -n "$legacy_refs" ]]; then
  echo "ERROR: legacy backend Go version references remain." >&2
  echo "$legacy_refs" >&2
  exit 1
fi

echo "OK: backend Go base version policy is ${TARGET_GO_VERSION}"
