#!/bin/bash
#
# Application build and installation
#

build_and_install_application() {
    log_info "Building and installing Calypso application..."
    
    # Build backend
    build_backend
    
    # Build frontend
    build_frontend
    
    # Install binaries and assets
    install_application_files
    
    log_info "✓ Application built and installed"
}

build_backend() {
    log_info "Building backend..."
    
    cd "$PROJECT_ROOT/backend"
    
    # Ensure Go is in PATH
    export PATH=$PATH:/usr/local/go/bin
    
    # Download dependencies
    log_info "Downloading Go dependencies..."
    go mod download
    
    # Build binary
    log_info "Building Go binary..."
    go build -ldflags "-X main.version=$CALYPSO_VERSION -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ) -X main.gitCommit=$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" \
        -o "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/bin/calypso-api" \
        ./cmd/calypso-api
    
    if [[ -f "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/bin/calypso-api" ]]; then
        chmod +x "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/bin/calypso-api"
        log_info "✓ Backend built successfully"
    else
        log_error "Backend build failed"
        exit 1
    fi
}

build_frontend() {
    log_info "Building frontend..."
    
    cd "$PROJECT_ROOT/frontend"
    
    # Install dependencies
    if [[ ! -d "node_modules" ]]; then
        log_info "Installing frontend dependencies..."
        npm install
    fi
    
    # Build frontend
    log_info "Building frontend assets..."
    npm run build
    
    # Copy built assets
    if [[ -d "dist" ]]; then
        log_info "Copying frontend assets..."
        cp -r dist/* "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/web/"
        log_info "✓ Frontend built successfully"
    else
        log_error "Frontend build failed"
        exit 1
    fi
}

install_application_files() {
    log_info "Installing application files..."
    
    # Copy migrations
    if [[ -d "$PROJECT_ROOT/db/migrations" ]]; then
        cp -r "$PROJECT_ROOT/db/migrations"/* "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/migrations/" 2>/dev/null || true
    fi
    
    # Copy scripts
    if [[ -d "$PROJECT_ROOT/scripts" ]]; then
        cp -r "$PROJECT_ROOT/scripts"/* "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/scripts/" 2>/dev/null || true
        chmod +x "$INSTALL_PREFIX/releases/$CALYPSO_VERSION/scripts"/*.sh 2>/dev/null || true
    fi
    
    # Set ownership
    chown -R calypso:calypso "$INSTALL_PREFIX" 2>/dev/null || chown -R root:root "$INSTALL_PREFIX"
    
    log_info "✓ Application files installed"
}

