# Git Auto-Sync - PlatformSistemas
# Branch: frontend_React

param(
    [switch]$NoBuild = $false
)

$BRANCH_NAME = "frontend_React"
$DEBOUNCE_SECONDS = 10

$global:LastChangeTime = Get-Date
$global:PendingChanges = $false
$global:ChangedFiles = @()

function Test-ShouldIgnoreFile {
    param([string]$FilePath)
    
    $ignorePatterns = @("node_modules", ".git", "dist", ".env", ".log", "package-lock.json", ".tmp", ".cache", ".vscode", ".idea")
    
    foreach ($pattern in $ignorePatterns) {
        if ($FilePath -match [regex]::Escape($pattern)) {
            return $true
        }
    }
    
    return $false
}

function Invoke-GitSync {
    if (-not $global:PendingChanges) { 
        return 
    }
    
    Write-Host "`n========================================" -ForegroundColor Cyan
    Write-Host "Iniciando sincronizacao Git..." -ForegroundColor Cyan
    Write-Host "========================================" -ForegroundColor Cyan
    
    try {
        $gitStatus = git status --porcelain
        if ([string]::IsNullOrWhiteSpace($gitStatus)) {
            Write-Host "Nenhuma alteracao para commitar." -ForegroundColor Yellow
            $global:PendingChanges = $false
            $global:ChangedFiles = @()
            return
        }
        
        Write-Host "`nArquivos alterados:" -ForegroundColor Gray
        $global:ChangedFiles | ForEach-Object { Write-Host "  - $_" -ForegroundColor DarkGray }
        
        if (-not $NoBuild) {
            Write-Host "`nGerando build de producao..." -ForegroundColor Yellow
            npm run build
            if ($LASTEXITCODE -ne 0) {
                Write-Host "Erro no build! Abortando commit." -ForegroundColor Red
                return
            }
            Write-Host "Build concluido com sucesso!" -ForegroundColor Green
        }
        
        Write-Host "`nAdicionando arquivos ao stage..." -ForegroundColor Yellow
        git add .
        
        $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        $fileCount = ($global:ChangedFiles | Measure-Object).Count
        $commitMessage = "Auto-deploy: $timestamp | $fileCount arquivo(s) alterado(s)"
        
        if (-not $NoBuild) {
            $commitMessage += " [Build included]"
        }
        
        Write-Host "Criando commit..." -ForegroundColor Yellow
        git commit -m $commitMessage
        
        if ($LASTEXITCODE -ne 0) {
            Write-Host "Nada para commitar ou erro no commit." -ForegroundColor Yellow
            $global:PendingChanges = $false
            $global:ChangedFiles = @()
            return
        }
        
        Write-Host "Enviando para o repositorio remoto (branch: $BRANCH_NAME)..." -ForegroundColor Yellow
        git push origin $BRANCH_NAME
        
        if ($LASTEXITCODE -eq 0) {
            Write-Host "`nSincronizacao concluida com sucesso!" -ForegroundColor Green
            Write-Host "========================================`n" -ForegroundColor Cyan
        }
        else {
            Write-Host "`nErro ao fazer push para o repositorio remoto!" -ForegroundColor Red
            Write-Host "========================================`n" -ForegroundColor Cyan
        }
    }
    catch {
        Write-Host "`nErro ao sincronizar com o Git: $_" -ForegroundColor Red
        Write-Host "========================================`n" -ForegroundColor Cyan
    }
    finally {
        $global:PendingChanges = $false
        $global:ChangedFiles = @()
    }
}

$Watcher = New-Object IO.FileSystemWatcher
$Watcher.Path = $PSScriptRoot
$Watcher.Filter = "*.*"
$Watcher.IncludeSubdirectories = $true
$Watcher.EnableRaisingEvents = $true
$Watcher.NotifyFilter = [System.IO.NotifyFilters]::FileName -bor [System.IO.NotifyFilters]::DirectoryName -bor [System.IO.NotifyFilters]::LastWrite

$Action = {
    $path = $Event.SourceEventArgs.FullPath
    $changeType = $Event.SourceEventArgs.ChangeType
    
    if (Test-ShouldIgnoreFile -FilePath $path) { 
        return 
    }
    
    $relativePath = $path.Replace($PSScriptRoot, "").TrimStart("\")
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $changeType : $relativePath" -ForegroundColor DarkCyan
    
    $global:LastChangeTime = Get-Date
    $global:PendingChanges = $true
    
    if ($global:ChangedFiles -notcontains $relativePath) {
        $global:ChangedFiles += $relativePath
    }
}

Register-ObjectEvent $Watcher "Changed" -Action $Action | Out-Null
Register-ObjectEvent $Watcher "Created" -Action $Action | Out-Null
Register-ObjectEvent $Watcher "Deleted" -Action $Action | Out-Null
Register-ObjectEvent $Watcher "Renamed" -Action $Action | Out-Null

Write-Host "`n============================================================" -ForegroundColor Green
Write-Host "  Git Auto-Sync - PlatformSistemas" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Green
Write-Host "  Branch: $BRANCH_NAME" -ForegroundColor Cyan
Write-Host "  Remote: https://git.itguys.com.br/itguys_dev/Workspace" -ForegroundColor Cyan
Write-Host "  Debounce: $DEBOUNCE_SECONDS segundos" -ForegroundColor Cyan
Write-Host "  Build automatico: $(if($NoBuild){'Desabilitado'}else{'Habilitado'})" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Green
Write-Host "  Status: Monitorando alteracoes..." -ForegroundColor Yellow
Write-Host "  Pressione Ctrl+C para parar" -ForegroundColor Yellow
Write-Host "============================================================`n" -ForegroundColor Green

$lastHeartbeat = Get-Date
while ($true) {
    Start-Sleep -Seconds 1
    
    if ((Get-Date) - $lastHeartbeat -gt (New-TimeSpan -Minutes 5)) {
        Write-Host "[$(Get-Date -Format 'HH:mm:ss')] Heartbeat: Script ativo e monitorando..." -ForegroundColor Gray
        $lastHeartbeat = Get-Date
    }

    if ($global:PendingChanges) {
        $timeSinceLastChange = (Get-Date) - $global:LastChangeTime
        
        if ($timeSinceLastChange.TotalSeconds -ge $DEBOUNCE_SECONDS) {
            Invoke-GitSync
        }
    }
}

