# Sync script to keep origin and upstream remotes in sync
# Usage: .\sync_remotes.ps1 [--push-to-origin]

param(
    [switch]$PushToOrigin
)

$ErrorActionPreference = "Stop"
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Split-Path -Parent (Split-Path -Parent $scriptPath)

Write-Host "Remote Sync Script - WebDrop Bridge" -ForegroundColor Cyan
Write-Host "Repository: $repoRoot`n" -ForegroundColor Gray

# Change to repo directory
Push-Location $repoRoot

try {
    # Fetch from both remotes
    Write-Host "Fetching from origin..." -ForegroundColor Yellow
    git fetch origin
    
    Write-Host "Fetching from upstream..." -ForegroundColor Yellow
    git fetch upstream
    
    # Show status
    Write-Host "`nRemote Status:" -ForegroundColor Cyan
    git remote -v
    
    # Show branch comparison
    Write-Host "`nBranch Comparison:" -ForegroundColor Cyan
    Write-Host "Latest commits:" -ForegroundColor Gray
    
    # Suppress errors for log commands
    $ErrorActionPreference = "SilentlyContinue"
    
    $originLog = git log --oneline origin/main -5
    if ($originLog) {
        Write-Host "Origin:" -ForegroundColor Gray
        $originLog | ForEach-Object { Write-Host "  $_" }
    } else {
        Write-Host "  origin/main: (not found)" -ForegroundColor Gray
    }
    
    $upstreamLog = git log --oneline upstream/main -5
    if ($upstreamLog) {
        Write-Host "Upstream:" -ForegroundColor Gray
        $upstreamLog | ForEach-Object { Write-Host "  $_" }
    } else {
        Write-Host "  upstream/main: (not found)" -ForegroundColor Gray
    }
    
    # Restore error handling
    $ErrorActionPreference = "Stop"
    
    # Optionally push to origin
    if ($PushToOrigin) {
        Write-Host "`nPushing current branch to origin..." -ForegroundColor Yellow
        $currentBranch = git rev-parse --abbrev-ref HEAD
        git push origin $currentBranch
        Write-Host "Pushed $currentBranch to origin" -ForegroundColor Green
    } else {
        Write-Host "`nTip: Use --push-to-origin flag to push current branch to origin" -ForegroundColor Gray
    }
    
    Write-Host "`nSync complete!" -ForegroundColor Green
}
catch {
    Write-Host "`nError: $_" -ForegroundColor Red
    exit 1
}
finally {
    Pop-Location
}
