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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
proto_root="$root/packages/contracts/proto"
go_out="$root/packages/contracts/gen/go"
dart_out="$root/apps/client/lib/src/generated"
dart_plugin="$root/apps/client/tool/protoc-gen-dart"

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "contracts-gen: required command not found: $1" >&2
    exit 1
  fi
}

require_cmd protoc
require_cmd protoc-gen-go

if [ ! -x "$dart_plugin" ]; then
  echo "contracts-gen: dart protoc plugin wrapper missing or not executable: $dart_plugin" >&2
  exit 1
fi

protos=(
  "alt/v1/common.proto"
  "alt/v1/market.proto"
  "alt/v1/backtest.proto"
  "alt/v1/paper_trading.proto"
  "alt/v1/live_trading.proto"
)

mkdir -p "$go_out"
mkdir -p "$dart_out"

(
  cd "$proto_root"
  protoc \
    -I . \
    --go_out="$go_out" \
    --go_opt=paths=source_relative \
    "${protos[@]}"
)

(
  cd "$proto_root"
  protoc \
    -I . \
    --plugin=protoc-gen-dart="$dart_plugin" \
    --dart_out="$dart_out" \
    "${protos[@]}"
)
