#!/bin/bash
# File: scripts/gen-proto.sh
set -xe

# Find protoc-gen-go
PROTOC_GEN_GO_PATH=""
if command -v protoc-gen-go &> /dev/null; then
    PROTOC_GEN_GO_PATH=$(command -v protoc-gen-go)
elif [ -f "$(go env GOBIN)/protoc-gen-go" ]; then
    PROTOC_GEN_GO_PATH="$(go env GOBIN)/protoc-gen-go"
elif [ -f "$(go env GOPATH)/bin/protoc-gen-go" ]; then
    PROTOC_GEN_GO_PATH="$(go env GOPATH)/bin/protoc-gen-go"
else
    echo "protoc-gen-go not found. Please run:"
    echo "go install google.golang.org/protobuf/cmd/protoc-gen-go"
    echo "And ensure GOBIN or GOPATH/bin is in your PATH."
    exit 1
fi

# Project root assumed to be parent of 'scripts' directory
PROJECT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
API_DIR="${PROJECT_ROOT}/api/v1alpha1"
# Output generated code directly into the api/v1alpha1 directory, alongside kat.proto
# This is a common pattern and simplifies imports.
# The go_package option in kat.proto already points here.
OUT_DIR="${API_DIR}"

# Ensure output directory exists (it should, it's the same as API_DIR)
mkdir -p "$OUT_DIR"

echo "Generating Go code from Protobuf definitions..."
protoc --proto_path="${API_DIR}" \
       --plugin="protoc-gen-go=${PROTOC_GEN_GO_PATH}" \
       --go_out="${OUT_DIR}" --go_opt=paths=source_relative \
       "${API_DIR}/kat.proto"

echo "Protobuf Go code generated in ${OUT_DIR}"

# Optional: Generate gRPC stubs if/when you add services
# PROTOC_GEN_GO_GRPC_PATH="" # Similar logic to find protoc-gen-go-grpc
# go install google.golang.org/grpc/cmd/protoc-gen-go-grpc
# protoc --proto_path="${API_DIR}" \
#        --plugin="protoc-gen-go=${PROTOC_GEN_GO_PATH}" \
#        --plugin="protoc-gen-go-grpc=${PROTOC_GEN_GO_GRPC_PATH}" \
#        --go_out="${OUT_DIR}" --go_opt=paths=source_relative \
#        --go-grpc_out="${OUT_DIR}" --go-grpc_opt=paths=source_relative \
#        "${API_DIR}/kat.proto"