#!/bin/bash
tmp_dir=$(mktemp -d)
find -L . -name "*.proto" -exec cp -L --parents {} "$tmp_dir/" \; 2>/dev/null || true

python3 -c '
import os, re, sys

tmp_dir = sys.argv[1]
for root, _, files in os.walk(tmp_dir):
    for file in files:
        if file.endswith(".proto"):
            p = os.path.join(root, file)
            try:
                with open(p, "r", encoding="utf-8", errors="ignore") as f:
                    content = f.read()
                if "edition" not in content:
                    continue
                content = re.sub(r"edition\s*=\s*\"[0-9]+\"\s*;", "syntax = \"proto3\";", content)
                content = re.sub(r".*google/protobuf/cpp_features\.proto.*", "// &", content)
                content = re.sub(r".*option features.*", "// &", content)
                new_lines = []
                in_enum = False
                in_oneof = False
                for line in content.splitlines(True):
                    stripped = line.strip()
                    if stripped.startswith("enum "):
                        in_enum = True
                    elif in_enum and "}" in stripped:
                        in_enum = False
                    elif stripped.startswith("oneof "):
                        in_oneof = True
                    elif in_oneof and "}" in stripped:
                        in_oneof = False
                    elif not in_enum and not in_oneof:
                        m = re.match(r"^(\s+)(?!repeated|optional|required|message|enum|oneof|option|reserved|package|import|syntax|//|/\*|\*)([A-Za-z0-9_.]+)\s+([A-Za-z0-9_]+)\s*=\s*([0-9]+)(.*);", line)
                        if m:
                            indent, ftype, fname, fnum, rest = m.groups()
                            line = f"{indent}optional {ftype} {fname} = {fnum}{rest};\n"
                    new_lines.append(line)
                with open(p, "w", encoding="utf-8") as f:
                    f.write("".join(new_lines))
            except Exception:
                pass
' "$tmp_dir" 2>/dev/null || true

new_args=()
for arg in "$@"; do
  case "$arg" in
    -I*)
      dir="${arg#-I}"
      if [ -d "$tmp_dir/$dir" ]; then
        new_args+=("-I$tmp_dir/$dir")
      elif [ -d "$dir" ]; then
        new_args+=("-I$dir")
      else
        new_args+=("$arg")
      fi
      ;;
    *.proto)
      if [ -f "$tmp_dir/$arg" ]; then
        new_args+=("$tmp_dir/$arg")
      else
        new_args+=("$arg")
      fi
      ;;
    *)
      new_args+=("$arg")
      ;;
  esac
done
/usr/bin/protoc "${new_args[@]}"
ret=$?
rm -rf "$tmp_dir"
exit $ret
