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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
DIST_DIR="$SCRIPT_DIR"
TARGET="x86_64-pc-windows-msvc"

# Read version from Cargo.toml
VERSION=$(grep '^version' "$PROJECT_DIR/crates/audiofiles-app/Cargo.toml" | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "Building AudioFiles v${VERSION} Windows (${TARGET})"

# Prerequisites check
if ! command -v cargo-xwin &>/dev/null; then
    echo "Error: cargo-xwin not found. Install with: cargo install cargo-xwin"
    exit 1
fi

if ! rustup target list --installed | grep -q "$TARGET"; then
    echo "Error: Rust target $TARGET not installed. Add with: rustup target add $TARGET"
    exit 1
fi

# Step 1: Build release binary
echo "==> Building release binary..."
cd "$PROJECT_DIR"
cargo xwin build --release -p audiofiles-app --target "$TARGET"

# Step 2: Copy artifact
echo "==> Copying artifact..."
EXE_NAME="audiofiles-app.exe"
SRC="$PROJECT_DIR/target/$TARGET/release/$EXE_NAME"

if [ ! -f "$SRC" ]; then
    echo "Error: Build artifact not found at $SRC"
    exit 1
fi

DEST="$DIST_DIR/AudioFiles_${VERSION}_x86_64.exe"
cp "$SRC" "$DEST"

echo ""
echo "Done: $DEST"
echo "Size: $(du -h "$DEST" | cut -f1)"
