#!/bin/bash
set -e

echo "🔨 Building pyhdwallet standalone binary..."

# Check venv more strictly
if [ -z "$VIRTUAL_ENV" ] || [[ "$VIRTUAL_ENV" != *"hdwalletpy"* ]]; then
    echo "❌ Not in virtual environment!"
    echo ""
    echo "Activate it first:"
    echo "   source .venv/bin/activate"
    exit 1
fi

# Install PyInstaller if needed
if ! pip show pyinstaller &>/dev/null; then
    echo "📦 Installing PyInstaller..."
    pip install pyinstaller
fi

# Create patched version for frozen builds
echo "📝 Creating frozen-compatible version..."
python3 << 'PATCH'
with open('src/pyhdwallet.py', 'r') as f:
    content = f.read()

# Patch _require() for PyInstaller
content = content.replace(
    """def _require(mod: str, pkg: str) -> None:
    try:
        __import__(mod)""",
    """def _require(mod: str, pkg: str) -> None:
    # Skip check in PyInstaller frozen executable
    if getattr(sys, 'frozen', False):
        return
    try:
        __import__(mod)"""
)

with open('src/pyhdwallet_frozen.py', 'w') as f:
    f.write(content)
PATCH

# Clean previous builds
rm -rf build/ dist/ *.spec

# Build
echo "🔧 Building with PyInstaller..."
pyinstaller --onefile \
  --name pyhdwallet \
  --clean \
  --collect-all bip_utils \
  --collect-all pgpy \
  --collect-all nacl \
  --collect-all pyzipper \
  --collect-all coincurve \
  --copy-metadata coincurve \
  src/pyhdwallet_frozen.py

# Clean up temp file
rm src/pyhdwallet_frozen.py

# Test
echo ""
echo "✅ Testing binary..."
./dist/pyhdwallet test

# Show results
echo ""
echo "🎉 Binary created successfully!"
echo "   Location: dist/pyhdwallet"
echo "   Size: $(du -h dist/pyhdwallet | cut -f1)"
echo ""
echo "Quick test:"
echo "   ./dist/pyhdwallet gen --help"
echo "   ./dist/pyhdwallet gen-child --help"
