#!/bin/bash
# Build native binaries for Incus deployment (without Docker)
# Usage: ./build-native.sh [service-name]
# If no service specified, builds all services

set -euo pipefail

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BUILD_DIR="${PROJECT_ROOT}/.build/incus"
SERVICE="${1:-all}"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${BLUE}🔨 Building native binaries for Incus deployment...${NC}"

mkdir -p "${BUILD_DIR}"

build_backend_api() {
    echo -e "${BLUE}Building backend-api (Go)...${NC}"
    cd "${PROJECT_ROOT}/veza-backend-api"
    
    # Check if Go modules are downloaded
    if [ ! -f "go.sum" ]; then
        echo -e "${YELLOW}Downloading Go modules...${NC}"
        go mod download
    fi
    
    # Build Go binary
    # Using cmd/api/main.go instead of cmd/modern-server/main.go to avoid logger issues
    CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
        -ldflags="-w -s" \
        -o "${BUILD_DIR}/veza-backend-api" \
        ./cmd/api/main.go
    
    if [ ! -f "${BUILD_DIR}/veza-backend-api" ]; then
        echo -e "${RED}❌ Failed to build backend-api${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ backend-api built${NC}"
}

build_chat_server() {
    echo -e "${BLUE}Building chat-server (Rust)...${NC}"
    cd "${PROJECT_ROOT}/veza-chat-server"
    
    # Try cross-compilation first, fallback to native
    BINARY_PATH=""
    if command -v rustup >/dev/null 2>&1 && rustup target list --installed | grep -q "x86_64-unknown-linux-gnu"; then
        echo -e "${YELLOW}Attempting cross-compilation...${NC}"
        if cargo build --release --target x86_64-unknown-linux-gnu 2>&1 | tee /tmp/chat-build.log; then
            BINARY_PATH="target/x86_64-unknown-linux-gnu/release/chat-server"
        fi
    fi
    
    # Fallback to native build
    if [ -z "${BINARY_PATH}" ] || [ ! -f "${BINARY_PATH}" ]; then
        echo -e "${YELLOW}Using native build...${NC}"
        if cargo build --release 2>&1 | tee /tmp/chat-build.log; then
            BINARY_PATH="target/release/chat-server"
        else
            echo -e "${RED}❌ Failed to build chat-server${NC}"
            echo -e "${YELLOW}Build log saved to /tmp/chat-build.log${NC}"
            return 1
        fi
    fi
    
    # Copy binary
    if [ -f "${BINARY_PATH}" ]; then
        cp "${BINARY_PATH}" "${BUILD_DIR}/veza-chat-server"
        chmod +x "${BUILD_DIR}/veza-chat-server"
    else
        echo -e "${RED}❌ Failed to build chat-server: binary not found${NC}"
        return 1
    fi
    
    if [ ! -f "${BUILD_DIR}/veza-chat-server" ]; then
        echo -e "${RED}❌ Failed to copy chat-server binary${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ chat-server built${NC}"
    return 0
}

build_stream_server() {
    echo -e "${BLUE}Building stream-server (Rust)...${NC}"
    cd "${PROJECT_ROOT}/veza-stream-server"
    
    # Try cross-compilation first, fallback to native
    BINARY_PATH=""
    if command -v rustup >/dev/null 2>&1 && rustup target list --installed | grep -q "x86_64-unknown-linux-gnu"; then
        echo -e "${YELLOW}Attempting cross-compilation...${NC}"
        if cargo build --release --target x86_64-unknown-linux-gnu 2>&1 | tee /tmp/stream-build.log; then
            BINARY_PATH="target/x86_64-unknown-linux-gnu/release/stream_server"
        fi
    fi
    
    # Fallback to native build
    if [ -z "${BINARY_PATH}" ] || [ ! -f "${BINARY_PATH}" ]; then
        echo -e "${YELLOW}Using native build...${NC}"
        if cargo build --release 2>&1 | tee /tmp/stream-build.log; then
            BINARY_PATH="target/release/stream_server"
        else
            echo -e "${RED}❌ Failed to build stream-server${NC}"
            echo -e "${YELLOW}Build log saved to /tmp/stream-build.log${NC}"
            return 1
        fi
    fi
    
    # Copy binary
    if [ -f "${BINARY_PATH}" ]; then
        cp "${BINARY_PATH}" "${BUILD_DIR}/veza-stream-server"
        chmod +x "${BUILD_DIR}/veza-stream-server"
    else
        echo -e "${RED}❌ Failed to build stream-server: binary not found${NC}"
        return 1
    fi
    
    if [ ! -f "${BUILD_DIR}/veza-stream-server" ]; then
        echo -e "${RED}❌ Failed to copy stream-server binary${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✅ stream-server built${NC}"
    return 0
}

build_web() {
    echo -e "${BLUE}Building web frontend (Node.js)...${NC}"
    cd "${PROJECT_ROOT}/apps/web"
    
    # Install dependencies if needed
    if [ ! -d "node_modules" ]; then
        echo -e "${YELLOW}Installing npm dependencies...${NC}"
        npm install --silent
    fi
    
    # Build frontend with relative URLs (works automatically with HAProxy)
    # URLs relatives fonctionnent automatiquement avec HAProxy qui route /api/v1 vers backend
    export VITE_API_URL="${VITE_API_URL:-/api/v1}"
    export VITE_WS_URL="${VITE_WS_URL:-/ws}"
    export VITE_STREAM_URL="${VITE_STREAM_URL:-/stream}"
    export VITE_UPLOAD_URL="${VITE_UPLOAD_URL:-/upload}"
    echo -e "${BLUE}Building with API URLs: ${VITE_API_URL}${NC}"
    npm run build
    
    # Check if build succeeded
    if [ ! -d "dist" ]; then
        echo -e "${RED}❌ Failed to build web frontend: dist directory not found${NC}"
        exit 1
    fi
    
    # Stamp service worker cache version for this build
    if [ -f "dist/sw.js" ]; then
        BUILD_VERSION="$(date +%Y%m%d%H%M%S)"
        sed -i "s/__BUILD_VERSION__/${BUILD_VERSION}/g" dist/sw.js
    fi

    # Copy build output
    mkdir -p "${BUILD_DIR}/web"
    cp -r dist/* "${BUILD_DIR}/web/"
    
    if [ ! -f "${BUILD_DIR}/web/index.html" ]; then
        echo -e "${RED}❌ Failed to copy web frontend files${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✅ web frontend built${NC}"
}

case "${SERVICE}" in
    backend-api)
        build_backend_api
        ;;
    chat-server)
        build_chat_server
        ;;
    stream-server)
        build_stream_server
        ;;
    web)
        build_web
        ;;
    all)
        FAILED=0
        build_backend_api || FAILED=$((FAILED + 1))
        build_chat_server || FAILED=$((FAILED + 1))
        build_stream_server || FAILED=$((FAILED + 1))
        build_web || FAILED=$((FAILED + 1))
        
        if [ ${FAILED} -eq 0 ]; then
            echo -e "${GREEN}✅ All services built successfully!${NC}"
            echo -e "${BLUE}Build artifacts are in: ${BUILD_DIR}${NC}"
        else
            echo -e "${YELLOW}⚠️  ${FAILED} service(s) failed to build${NC}"
            echo -e "${BLUE}Build artifacts are in: ${BUILD_DIR}${NC}"
            echo -e "${YELLOW}You can still deploy the successfully built services${NC}"
            exit 1
        fi
        ;;
    *)
        echo -e "${YELLOW}Unknown service: ${SERVICE}${NC}"
        echo "Available services: backend-api, chat-server, stream-server, web, all"
        exit 1
        ;;
esac
