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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
canonical_proto="$repo_root/proto/message_common.proto"
go_proto="$repo_root/go/packets/message_common.proto"
kotlin_proto="$repo_root/kotlin/src/main/proto/message_common.proto"
python_proto="$repo_root/python/proto_socket/packets/message_common.proto"

if [[ ! -f "$canonical_proto" ]]; then
  echo "Missing canonical proto: $canonical_proto" >&2
  exit 1
fi

if [[ ! -f "$go_proto" ]]; then
  echo "Missing Go proto copy: $go_proto" >&2
  exit 1
fi

if [[ -d "$repo_root/kotlin" && ! -f "$kotlin_proto" ]]; then
  echo "Missing Kotlin proto copy: $kotlin_proto" >&2
  exit 1
fi

if [[ -d "$repo_root/python" && ! -f "$python_proto" ]]; then
  echo "Missing Python proto copy: $python_proto" >&2
  exit 1
fi

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

normalize_proto() {
  awk '
    /^[[:space:]]*option go_package[[:space:]]*=.*;[[:space:]]*$/ { next }
    /^[[:space:]]*option java_package[[:space:]]*=.*;[[:space:]]*$/ { next }
    /^[[:space:]]*option java_outer_classname[[:space:]]*=.*;[[:space:]]*$/ { next }
    /^[[:space:]]*option java_multiple_files[[:space:]]*=.*;[[:space:]]*$/ { next }
    /^[[:space:]]*$/ { next }
    { print }
  ' "$1"
}

normalize_proto "$canonical_proto" >"$tmp_dir/canonical.proto"
normalize_proto "$go_proto" >"$tmp_dir/go.proto"
if [[ -f "$kotlin_proto" ]]; then
  normalize_proto "$kotlin_proto" >"$tmp_dir/kotlin.proto"
fi
if [[ -f "$python_proto" ]]; then
  normalize_proto "$python_proto" >"$tmp_dir/python.proto"
fi

if ! cmp -s "$tmp_dir/canonical.proto" "$tmp_dir/go.proto"; then
  echo "Proto schema mismatch: go/packets/message_common.proto must match proto/message_common.proto except option go_package." >&2
  diff -u "$tmp_dir/canonical.proto" "$tmp_dir/go.proto" >&2
  exit 1
fi

if [[ -f "$tmp_dir/kotlin.proto" ]] && ! cmp -s "$tmp_dir/canonical.proto" "$tmp_dir/kotlin.proto"; then
  echo "Proto schema mismatch: kotlin/src/main/proto/message_common.proto must match proto/message_common.proto except Java options." >&2
  diff -u "$tmp_dir/canonical.proto" "$tmp_dir/kotlin.proto" >&2
  exit 1
fi

if [[ -f "$tmp_dir/python.proto" ]] && ! cmp -s "$tmp_dir/canonical.proto" "$tmp_dir/python.proto"; then
  echo "Proto schema mismatch: python/proto_socket/packets/message_common.proto must match proto/message_common.proto." >&2
  diff -u "$tmp_dir/canonical.proto" "$tmp_dir/python.proto" >&2
  exit 1
fi

echo "Proto schemas are in sync."
