#!/usr/bin/env bash
# Proto regeneration script for NoteFlow
# Regenerates Python, Rust, and provides guidance for TypeScript sync
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
PROTO_DIR="$PROJECT_ROOT/src/noteflow/grpc/proto"
PROTO_FILE="$PROTO_DIR/noteflow.proto"

echo "=== NoteFlow Proto Regeneration ==="
echo ""

# Verify proto file exists
if [[ ! -f "$PROTO_FILE" ]]; then
    echo "ERROR: Proto file not found: $PROTO_FILE"
    exit 1
fi

# Python stubs
echo "[1/3] Regenerating Python stubs..."
python -m grpc_tools.protoc \
    -I "$PROTO_DIR" \
    --python_out="$PROTO_DIR" \
    --grpc_python_out="$PROTO_DIR" \
    --pyi_out="$PROTO_DIR" \
    "$PROTO_FILE"

# Fix imports for Python 3.12+ (relative imports in grpc stub)
echo "[2/3] Fixing Python imports..."
GRPC_FILE="$PROTO_DIR/noteflow_pb2_grpc.py"
if [[ "$OSTYPE" == "darwin"* ]]; then
    sed -i '' 's/^import noteflow_pb2/from . import noteflow_pb2/' "$GRPC_FILE"
else
    sed -i 's/^import noteflow_pb2/from . import noteflow_pb2/' "$GRPC_FILE"
fi

# Rust stubs (via cargo build)
echo "[3/3] Regenerating Rust stubs..."
if command -v cargo &> /dev/null && [[ -d "$PROJECT_ROOT/client/src-tauri" ]]; then
    (cd "$PROJECT_ROOT/client" && cargo build --package noteflow-tauri 2>&1) || {
        echo "  Rust build failed or skipped (run 'cd client && cargo build' manually)"
    }
else
    echo "  Rust toolchain not found or client directory missing, skipping"
fi

echo ""
echo "=== Proto regeneration complete ==="
echo ""
echo "Files updated:"
echo "  - $PROTO_DIR/noteflow_pb2.py"
echo "  - $PROTO_DIR/noteflow_pb2_grpc.py"
echo "  - $PROTO_DIR/noteflow_pb2.pyi"
if [[ -d "$PROJECT_ROOT/client/src-tauri/src/grpc" ]]; then
    echo "  - client/src-tauri/src/grpc/noteflow.rs"
fi
echo ""
echo "Next steps:"
echo "  1. Update TypeScript types in client/src/api/types.ts (if proto changed)"
echo "  2. Run tests: pytest tests/grpc/"
echo "  3. Commit all generated files together"
