# ============================================
# FLOWBOT DCI - AUTOMATED DEPLOYMENT SCRIPT
# PowerShell version for Windows
# ============================================
# Deploys v2 to production server via SCP/SSH
#
# Usage: .\deploy.ps1 [-DryRun]
# ============================================

param(
    [switch]$DryRun
)

# Configuration
$RemoteHost = "159-100-13-177.cprapid.com"
$RemoteUser = "root"
$RemotePort = "22"
$RemotePath = "/home/digupdog/public_html/flowb0t.com/v2"
$LocalPath = Split-Path -Parent $PSScriptRoot

# Colors
function Write-Success { Write-Host $args -ForegroundColor Green }
function Write-Warning { Write-Host $args -ForegroundColor Yellow }
function Write-Error { Write-Host $args -ForegroundColor Red }

Write-Success "======================================"
Write-Success "  FLOWBOT DCI - DEPLOYMENT SCRIPT    "
Write-Success "======================================"
Write-Host ""
Write-Host "Local:  $LocalPath"
Write-Host "Remote: $RemoteUser@$RemoteHost`:$RemotePath"
Write-Host ""

if ($DryRun) {
    Write-Warning "DRY RUN MODE - No changes will be made"
    Write-Host ""
}

# Files/directories to exclude
$Excludes = @(
    ".env",
    ".git",
    ".gitignore",
    "error_log",
    "temp",
    "logs\*.log",
    "debug_*.html",
    "*.tmp",
    "*.bak",
    "node_modules",
    ".vscode"
)

# Check for SSH/SCP
Write-Warning "Step 1: Checking SSH availability..."
$sshPath = Get-Command ssh -ErrorAction SilentlyContinue
if (-not $sshPath) {
    Write-Error "ERROR: SSH not found. Please install OpenSSH or Git Bash."
    exit 1
}
Write-Success "SSH found: $($sshPath.Source)"
Write-Host ""

# Create backup
if (-not $DryRun) {
    Write-Warning "Step 2: Creating remote backup..."
    $BackupName = "backup_$(Get-Date -Format 'yyyyMMdd_HHmmss').tar.gz"
    $BackupCmd = "cd /home/digupdog/public_html/flowb0t.com && tar -czf /home/digupdog/backups/$BackupName v2/ 2>/dev/null || echo 'No existing v2'"
    & ssh -p $RemotePort "$RemoteUser@$RemoteHost" $BackupCmd
    Write-Success "Backup initiated: $BackupName"
} else {
    Write-Warning "Step 2: Skipping backup (dry-run)"
}
Write-Host ""

# Deploy files using SCP
Write-Warning "Step 3: Deploying files..."

# Get all files except excluded
$Files = Get-ChildItem -Path $LocalPath -Recurse -File | Where-Object {
    $relativePath = $_.FullName.Substring($LocalPath.Length + 1)
    $exclude = $false
    foreach ($pattern in $Excludes) {
        if ($relativePath -like $pattern -or $relativePath -like "*\$pattern" -or $relativePath -like "*\$pattern\*") {
            $exclude = $true
            break
        }
    }
    -not $exclude
}

Write-Host "Found $($Files.Count) files to deploy"

if (-not $DryRun) {
    # Create remote directories and sync
    Write-Host "Creating remote directory structure..."
    & ssh -p $RemotePort "$RemoteUser@$RemoteHost" "mkdir -p $RemotePath"

    # Use rsync if available (Git Bash), otherwise fallback to scp
    $rsyncPath = Get-Command rsync -ErrorAction SilentlyContinue
    if ($rsyncPath) {
        Write-Host "Using rsync for deployment..."
        $excludeArgs = $Excludes | ForEach-Object { "--exclude='$_'" }
        $rsyncCmd = "rsync -avz --progress --delete $($excludeArgs -join ' ') -e 'ssh -p $RemotePort' '$LocalPath/' '$RemoteUser@$RemoteHost`:$RemotePath/'"
        bash -c $rsyncCmd
    } else {
        Write-Host "Using SCP for deployment (slower)..."
        # SCP the entire directory
        & scp -r -P $RemotePort "$LocalPath\*" "$RemoteUser@$RemoteHost`:$RemotePath/"
    }
    Write-Success "Files deployed"
} else {
    Write-Warning "Step 3: Would deploy $($Files.Count) files (dry-run)"
}
Write-Host ""

# Set permissions
if (-not $DryRun) {
    Write-Warning "Step 4: Setting file permissions..."
    & ssh -p $RemotePort "$RemoteUser@$RemoteHost" "chmod -R 755 $RemotePath && chmod -R 777 $RemotePath/temp $RemotePath/logs 2>/dev/null || true"
    Write-Success "Permissions set"
} else {
    Write-Warning "Step 4: Skipping permissions (dry-run)"
}
Write-Host ""

# Done
Write-Success "======================================"
Write-Success "  DEPLOYMENT COMPLETED SUCCESSFULLY  "
Write-Success "======================================"
Write-Host ""
Write-Host "Deployed to: https://flowb0t.com/v2/"
Write-Host ""

if ($DryRun) {
    Write-Warning "This was a dry-run. Run without -DryRun to deploy."
}
