#!/usr/bin/env pwsh
# Build ARM64 binary on Raspberry Pi via SSH and mounted SMB share
# Usage: .\build-pi.ps1 [hostname]
# Default hostname: pi4c

param(
    [string]$PiHost = "pi4c"
)

$ErrorActionPreference = "Stop"

$ProjectRoot = "y:\dev\utils\msger"
$NativeDir = "$ProjectRoot\msger-native"

Write-Host ""
Write-Host "======================================"
Write-Host "Building ARM64 binary on Raspberry Pi"
Write-Host "======================================"
Write-Host "Target: $PiHost"
Write-Host ""

# Mount SMB share
Write-Host "Mounting SMB share from $PiHost..."
try {
    & mountsmb.ps1 $PiHost
    if ($LASTEXITCODE -ne 0) {
        throw "mountsmb.ps1 failed"
    }
} catch {
    Write-Error "ERROR: Failed to mount SMB share: $_"
    exit 1
}

$PPath = "c:\drives\smb\$PiHost\home\pi"
Write-Host "SMB path: $PPath"
Write-Host ""

# Verify mount exists
if (!(Test-Path $PPath)) {
    Write-Error "ERROR: Mounted path does not exist: $PPath"
    exit 1
}

# Create project directory on Pi
Write-Host "Creating project directory on Pi..."
New-Item -ItemType Directory -Force -Path "$PPath\msger\src" | Out-Null

# Copy source files
Write-Host "Copying source files to Pi..."
try {
    Copy-Item "$NativeDir\Cargo.toml" "$PPath\msger\" -Force
    Copy-Item "$NativeDir\src\*" "$PPath\msger\src\" -Recurse -Force
    Write-Host "Source files copied successfully"
} catch {
    Write-Error "ERROR: Failed to copy source files: $_"
    exit 1
}
Write-Host ""

# Check SSH connectivity
Write-Host "Testing SSH connection..."
try {
    $null = ssh $PiHost "echo Connected" 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "SSH connection failed"
    }
    Write-Host "SSH connection successful"
} catch {
    Write-Error "ERROR: Cannot connect to Pi via SSH"
    Write-Error "   Make sure you can run: ssh $PiHost"
    Write-Error "   You may need to set up SSH keys: ssh-copy-id $PiHost"
    exit 1
}
Write-Host ""

# Check and install Rust
Write-Host "Checking for Rust/Cargo on Pi..."
ssh $PiHost "command -v cargo" 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Host "Installing Rust on Pi (this may take a few minutes)..."
    ssh $PiHost "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y"
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ERROR: Failed to install Rust"
        exit 1
    }
    Write-Host "Rust installed successfully"
} else {
    Write-Host "Rust/Cargo found"
}
Write-Host ""

# Check and install pkg-config
Write-Host "Checking for pkg-config on Pi..."
ssh $PiHost "command -v pkg-config" 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) {
    Write-Host "Installing pkg-config..."
    ssh $PiHost "sudo apt-get update && sudo apt-get install -y pkg-config"
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ERROR: Failed to install pkg-config"
        exit 1
    }
    Write-Host "pkg-config installed"
} else {
    Write-Host "pkg-config found"
}
Write-Host ""

# Check and install build dependencies
Write-Host "Checking for build dependencies (GLib, GTK, WebKit) on Pi..."
$hasDeps = ssh $PiHost "pkg-config --exists glib-2.0 gobject-2.0 gio-2.0 gtk+-3.0 webkit2gtk-4.0 2>&1 && echo 'OK' || echo 'MISSING'"
if ($hasDeps -notcontains "OK") {
    Write-Host "Installing build dependencies (this may take several minutes)..."
    Write-Host "  - build-essential"
    Write-Host "  - libglib2.0-dev"
    Write-Host "  - libgtk-3-dev"
    Write-Host "  - libwebkit2gtk-4.0-dev"
    Write-Host "  - libsoup2.4-dev"
    Write-Host ""
    Write-Host "Running: sudo apt-get update && sudo apt-get install -y ..."
    ssh $PiHost "sudo apt-get update -qq && sudo apt-get install -y build-essential libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.0-dev libsoup2.4-dev"
    if ($LASTEXITCODE -ne 0) {
        Write-Error "ERROR: Failed to install build dependencies"
        Write-Host ""
        Write-Host "TRY MANUALLY:"
        Write-Host "  ssh $PiHost"
        Write-Host "  sudo apt-get update"
        Write-Host "  sudo apt-get install -y build-essential libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.0-dev libsoup2.4-dev"
        exit 1
    }
    Write-Host "Build dependencies installed successfully"
    
    # Verify installation
    Write-Host "Verifying installation..."
    $verify = ssh $PiHost "pkg-config --exists glib-2.0 gobject-2.0 gio-2.0 gtk+-3.0 webkit2gtk-4.0 2>&1 && echo 'OK' || echo 'STILL_MISSING'"
    if ($verify -contains "STILL_MISSING") {
        Write-Error "ERROR: Dependencies still missing after installation"
        Write-Host "Try running manually on the Pi:"
        Write-Host "  sudo apt-get update"
        Write-Host "  sudo apt-get install -y build-essential libglib2.0-dev libgtk-3-dev libwebkit2gtk-4.0-dev libsoup2.4-dev"
        exit 1
    }
} else {
    Write-Host "Build dependencies found"
}
Write-Host ""

# Build on Pi
Write-Host "======================================"
Write-Host "Checking if rebuild is needed..."
Write-Host "======================================"
Write-Host ""

# Check if binary exists and is up to date
$destBinary = "$binDir\msgernative-arm64"
$needsRebuild = $false

if (!(Test-Path $destBinary)) {
    Write-Host "Binary does not exist, build needed"
    $needsRebuild = $true
} else {
    $binaryTime = (Get-Item $destBinary).LastWriteTime
    Write-Host "Binary timestamp: $binaryTime"
    
    # Check source files
    $sourceFiles = @(
        "$NativeDir\Cargo.toml"
        "$NativeDir\build.rs"
    )
    $sourceFiles += Get-ChildItem "$NativeDir\src" -Recurse -File
    
    foreach ($file in $sourceFiles) {
        if ($file.LastWriteTime -gt $binaryTime) {
            Write-Host "Source file changed: $($file.Name) ($($file.LastWriteTime))"
            $needsRebuild = $true
            break
        }
    }
}

if (!$needsRebuild) {
    Write-Host ""
    Write-Host "======================================"
    Write-Host "Binary is up to date, skipping build"
    Write-Host "======================================"
    $fileSize = (Get-Item $destBinary).Length
    $sizeMB = [math]::Round($fileSize / 1MB, 2)
    Write-Host "Binary: $destBinary"
    Write-Host "Size: $sizeMB MB"
    Write-Host ""
    exit 0
}

Write-Host ""
Write-Host "======================================"
Write-Host "Building ARM64 binary on Pi..."
Write-Host "This may take several minutes..."
Write-Host "======================================"
Write-Host ""
ssh $PiHost "cd ~/msger && export PATH=~/.cargo/bin:`$PATH && cargo build --release"
if ($LASTEXITCODE -ne 0) {
    Write-Host ""
    Write-Error "ERROR: Build failed on Pi"
    exit 1
}
Write-Host ""
Write-Host "Build completed successfully!"
Write-Host ""

# Copy binary back
Write-Host "Copying binary back from Pi..."
$binDir = "$NativeDir\bin"
if (!(Test-Path $binDir)) {
    New-Item -ItemType Directory -Force -Path $binDir | Out-Null
}

$sourceBinary = "$PPath\msger\target\release\msgernative"
$destBinary = "$binDir\msgernative-arm64"

if (!(Test-Path $sourceBinary)) {
    Write-Error "ERROR: Built binary not found at: $sourceBinary"
    exit 1
}

Copy-Item $sourceBinary $destBinary -Force

# Get file size
$fileSize = (Get-Item $destBinary).Length
$sizeMB = [math]::Round($fileSize / 1MB, 2)
Write-Host "Binary copied to: $destBinary"
Write-Host "Binary size: $sizeMB MB"
Write-Host ""

# Cleanup on Pi
Write-Host "Cleaning up build artifacts on Pi..."
ssh $PiHost "rm -rf ~/msger/target" 2>$null

Write-Host ""
Write-Host "======================================"
Write-Host "ARM64 binary ready!"
Write-Host "======================================"
Write-Host "The binary is now included in the project"
Write-Host "and will be packaged with npm publish"
Write-Host ""
