#!/bin/bash
# DragonX ImGui Wallet - Release Build Script
# Copyright 2024-2026 The Hush Developers
# Released under the GPLv3

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BUILD_DIR="${SCRIPT_DIR}/build/linux"
VERSION="1.2.0"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

print_status() {
    echo -e "${GREEN}[*]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

usage() {
    echo "DragonX ImGui Wallet Build Script"
    echo ""
    echo "Usage: $0 [options]"
    echo ""
    echo "Options:"
    echo "  -d, --debug       Build debug version"
    echo "  -r, --release     Build release version (default)"
    echo "  -c, --clean       Clean build directory first"
    echo "  -j N              Use N parallel jobs (default: auto)"
    echo "  -a, --appimage    Create AppImage after build"
    echo "  -h, --help        Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 -r             # Release build"
    echo "  $0 -c -r          # Clean + release build"
    echo "  $0 -r -a          # Release build + AppImage"
    echo "  $0 -d -j4         # Debug build with 4 threads"
}

# Default options
BUILD_TYPE="Release"
CLEAN=false
JOBS=$(nproc 2>/dev/null || echo 4)
CREATE_APPIMAGE=false

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -d|--debug)
            BUILD_TYPE="Debug"
            shift
            ;;
        -r|--release)
            BUILD_TYPE="Release"
            shift
            ;;
        -c|--clean)
            CLEAN=true
            shift
            ;;
        -j)
            JOBS="$2"
            shift 2
            ;;
        -a|--appimage)
            CREATE_APPIMAGE=true
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            usage
            exit 1
            ;;
    esac
done

print_status "DragonX ImGui Wallet v${VERSION} - Build Script"
print_status "Build type: ${BUILD_TYPE}"
print_status "Parallel jobs: ${JOBS}"

# Clean if requested
if [ "$CLEAN" = true ]; then
    print_status "Cleaning build directory..."
    rm -rf "${BUILD_DIR}"
fi

# Create build directory
mkdir -p "${BUILD_DIR}"
cd "${BUILD_DIR}"

# Configure
print_status "Running CMake configuration..."
cmake .. \
    -DCMAKE_BUILD_TYPE="${BUILD_TYPE}" \
    -DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG" \
    -DDRAGONX_USE_SYSTEM_SDL3=ON

# Build
print_status "Building with ${JOBS} parallel jobs..."
cmake --build . -j "${JOBS}"

# Check if build succeeded
if [ -f "bin/ObsidianDragon" ]; then
    print_status "Build successful!"
    
    # Show binary info
    BINARY_SIZE=$(du -h bin/ObsidianDragon | cut -f1)
    print_status "Binary size: ${BINARY_SIZE}"
    
    # Strip in release mode
    if [ "$BUILD_TYPE" = "Release" ]; then
        print_status "Stripping debug symbols..."
        strip bin/ObsidianDragon
        STRIPPED_SIZE=$(du -h bin/ObsidianDragon | cut -f1)
        print_status "Stripped size: ${STRIPPED_SIZE}"
    fi
    
    # Bundle daemon files if available
    DAEMON_BUNDLED=0
    
    # Look for hush-arrakis-chain in common locations (the daemon launcher script)
    LAUNCHER_PATHS=(
        "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/hush-arrakis-chain"
        "${SCRIPT_DIR}/../hush-arrakis-chain"
        "${SCRIPT_DIR}/hush-arrakis-chain"
        "$HOME/dragonx/src/hush-arrakis-chain"
    )
    
    for lpath in "${LAUNCHER_PATHS[@]}"; do
        if [ -f "$lpath" ]; then
            print_status "Bundling hush-arrakis-chain from $lpath"
            cp "$lpath" bin/hush-arrakis-chain
            chmod +x bin/hush-arrakis-chain
            DAEMON_BUNDLED=1
            break
        fi
    done
    
    # Also look for hushd (the actual daemon binary)
    HUSHD_PATHS=(
        "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/hushd"
        "${SCRIPT_DIR}/../hushd"
        "${SCRIPT_DIR}/hushd"
        "$HOME/dragonx/src/hushd"
    )
    
    for hpath in "${HUSHD_PATHS[@]}"; do
        if [ -f "$hpath" ]; then
            print_status "Bundling hushd from $hpath"
            cp "$hpath" bin/hushd
            chmod +x bin/hushd
            break
        fi
    done
    
    # Also copy dragonxd script if available (alternative launcher)
    DRAGONXD_PATHS=(
        "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/dragonxd"
        "${SCRIPT_DIR}/../dragonxd"
        "${SCRIPT_DIR}/dragonxd"
        "$HOME/dragonx/src/dragonxd"
    )
    
    for dpath in "${DRAGONXD_PATHS[@]}"; do
        if [ -f "$dpath" ]; then
            print_status "Bundling dragonxd script from $dpath"
            cp "$dpath" bin/dragonxd
            chmod +x bin/dragonxd
            break
        fi
    done
    
    # Look for asmap.dat
    ASMAP_PATHS=(
        "${SCRIPT_DIR}/prebuilt-binaries/dragonxd-linux/asmap.dat"
        "${SCRIPT_DIR}/../asmap.dat"
        "${SCRIPT_DIR}/asmap.dat"
        "$HOME/dragonx/asmap.dat"
        "$HOME/dragonx/contrib/asmap/asmap.dat"
    )
    
    for apath in "${ASMAP_PATHS[@]}"; do
        if [ -f "$apath" ]; then
            print_status "Bundling asmap.dat from $apath"
            cp "$apath" bin/
            break
        fi
    done
    
    if [ $DAEMON_BUNDLED -eq 1 ]; then
        print_status "Daemon bundled - ready for distribution!"
    else
        print_warning "dragonxd not found - place prebuilt-binaries/dragonxd-linux/ in project directory for bundling"
    fi
else
    print_error "Build failed - binary not found"
    exit 1
fi

# Create AppImage if requested
if [ "$CREATE_APPIMAGE" = true ]; then
    print_status "Creating AppImage..."
    "${SCRIPT_DIR}/create-appimage.sh" || print_warning "AppImage creation failed"
fi

print_status ""
print_status "Build complete!"
print_status "Binary: ${BUILD_DIR}/bin/ObsidianDragon"
print_status ""
print_status "To run: cd ${BUILD_DIR}/bin && ./ObsidianDragon"
