# PowerShell File Watcher & FTP Deployer
# Run: powershell -ExecutionPolicy Bypass -File watch-deploy.ps1

$watchDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ignorePatterns = @(
    '.git',
    '.vscode',
    'node_modules',
    'messages.json',
    'token_cache.json',
    'webhook_log.json',
    '.env',
    'watch-deploy',
    '.DS_Store',
    'Thumbs.db'
)

$debounceMs = 1000
$minDeployInterval = 3000
$lastDeploy = 0
$deployTimeout = $null

function Write-Status {
    param([string]$Message, [string]$Type = "Info")

    $timestamp = Get-Date -Format "HH:mm:ss"
    $color = @{
        "Info" = "Cyan"
        "Success" = "Green"
        "Warning" = "Yellow"
        "Error" = "Red"
        "File" = "White"
    }

    $icon = @{
        "Info" = "ℹ"
        "Success" = "✓"
        "Warning" = "⚠"
        "Error" = "✗"
        "File" = "📝"
    }

    Write-Host "[$timestamp] $($icon[$Type]) $Message" -ForegroundColor $color[$Type]
}

function Should-Ignore {
    param([string]$FilePath)

    foreach ($pattern in $ignorePatterns) {
        if ($FilePath -like "*$pattern*") {
            return $true
        }
    }
    return $false
}

function Invoke-Deploy {
    $now = [DateTime]::Now.Ticks / 10000

    if ($now - $lastDeploy -lt $minDeployInterval) {
        Write-Status "Skipping deploy (too soon, waiting...)" "Warning"
        return
    }

    $global:lastDeploy = $now
    Write-Status "" "Info"
    Write-Status "Deploying to FTP server..." "Info"

    try {
        & php deploy.php
        Write-Status "Deploy successful" "Success"
    }
    catch {
        Write-Status "Deploy failed: $_" "Error"
    }
    Write-Status "" "Info"
}

function Start-FileWatcher {
    Write-Host @"

╔══════════════════════════════════════════════════════════════╗
║          SMS App - File Watcher & FTP Deployer               ║
╚══════════════════════════════════════════════════════════════╝

📂 Watching: $watchDir
🔗 Target:  ftps://ftp.shanesmith.com.au:21
⏱ Debounce: ${debounceMs}ms

"@ -ForegroundColor Cyan

    Write-Status "Watcher ready. Making changes will trigger FTP upload." "Success"
    Write-Status "Press Ctrl+C to stop." "Info"
    Write-Status "" "Info"

    $watcher = New-Object System.IO.FileSystemWatcher
    $watcher.Path = $watchDir
    $watcher.IncludeSubdirectories = $true
    $watcher.EnableRaisingEvents = $true

    $script:lastChangeTime = 0

    Register-ObjectEvent -InputObject $watcher -EventName "Changed" -Action {
        $filepath = $Event.SourceEventArgs.FullPath
        $name = Split-Path -Leaf $filepath

        if (-not (Should-Ignore $filepath)) {
            Write-Status "$name changed" "File"

            if ($null -ne $script:deployTimeout) {
                Unregister-Event -SourceIdentifier $script:deployTimeout
            }

            $script:deployTimeout = Register-ObjectEvent -InputObject (New-Object System.Timers.Timer) `
                -EventName "Elapsed" `
                -SourceIdentifier "deploy_timer_$([guid]::NewGuid())" `
                -Action {
                    Invoke-Deploy
                    Unregister-Event -SourceIdentifier $Event.SourceIdentifier
                } | Select-Object -ExpandProperty Name

            $timer = Get-EventSubscriber -SourceIdentifier $script:deployTimeout | Select-Object -ExpandProperty SourceObject
            $timer.Interval = $debounceMs
            $timer.AutoReset = $false
            $timer.Start()
        }
    } | Out-Null

    while ($true) {
        Start-Sleep -Seconds 1
    }
}

# Run the watcher
try {
    Start-FileWatcher
}
catch {
    Write-Status "Error: $_" "Error"
}
finally {
    Get-EventSubscriber | Unregister-Event -Force -ErrorAction SilentlyContinue
    Write-Status "Watcher stopped" "Info"
}
