# =============================================================================
# WEBMoney - Release Script (Conforme Diretrizes v3.0)
# =============================================================================
# ESTE SCRIPT SEGUE ESTRITAMENTE AS DIRETRIZES DE DESENVOLVIMENTO
# Qualquer violacao resulta em ERRO e aborta a execucao
# =============================================================================

param(
    [Parameter(Mandatory=$true)]
    [ValidateSet('patch', 'minor', 'major')]
    [string]$VersionType,
    
    [Parameter(Mandatory=$true)]
    [string]$ChangeDescription,
    
    [ValidateSet('frontend', 'backend', 'both')]
    [string]$Deploy = 'both',
    
    [ValidateSet('Added', 'Changed', 'Fixed', 'Removed', 'Security')]
    [string]$ChangeType = 'Changed'
)

$ErrorActionPreference = "Stop"
$ProjectRoot = "c:\Users\marco\OneDrive\Documents\WebMoney"
$Server = "root@213.165.93.60"
$ProductionUrl = "https://webmoney.cnxifly.com"

# =============================================================================
# FUNCOES AUXILIARES
# =============================================================================

function Write-Header { param([string]$Text)
    Write-Host ""
    Write-Host "=======================================================" -ForegroundColor Cyan
    Write-Host "  $Text" -ForegroundColor Cyan
    Write-Host "=======================================================" -ForegroundColor Cyan
    Write-Host ""
}

function Write-Step { param([int]$N, [int]$T, [string]$Text)
    Write-Host "[$N/$T] $Text" -ForegroundColor Yellow
}

function Write-OK { param([string]$Text)
    Write-Host "[OK] $Text" -ForegroundColor Green
}

function Write-FAIL { param([string]$Text)
    Write-Host "[ERRO] $Text" -ForegroundColor Red
}

function Get-CurrentVersion {
    return (Get-Content (Join-Path $ProjectRoot "VERSION")).Trim()
}

function Get-NextVersion {
    param([string]$Current, [string]$Type)
    $p = $Current.Split('.'); $ma=[int]$p[0]; $mi=[int]$p[1]; $pa=[int]$p[2]
    switch($Type) { 'major'{$ma++;$mi=0;$pa=0} 'minor'{$mi++;$pa=0} 'patch'{$pa++} }
    return "$ma.$mi.$pa"
}

# =============================================================================
# DIRETRIZES - VALIDACOES OBRIGATORIAS
# =============================================================================

Write-Header "DIRETRIZES v3.0 - Validacao Obrigatoria"

# Diretriz: Verificar conexao SSH (necessario para deploy)
Write-Step 1 6 "Verificando conexao SSH..."
$sshTest = ssh -o ConnectTimeout=5 -o BatchMode=yes $Server "echo OK" 2>$null
if ($sshTest -ne "OK") {
    Write-FAIL "Conexao SSH falhou. Execute primeiro: .\scripts\setup-ssh.ps1"
    Write-Host "  Password do servidor: Master9354" -ForegroundColor Gray
    exit 1
}
Write-OK "Conexao SSH OK"

# Diretriz: Verificar VERSION existe
Write-Step 2 6 "Verificando arquivo VERSION..."
$versionFile = Join-Path $ProjectRoot "VERSION"
if (-not (Test-Path $versionFile)) {
    Write-FAIL "Arquivo VERSION nao encontrado"
    exit 1
}
$currentVersion = Get-CurrentVersion
$newVersion = Get-NextVersion -Current $currentVersion -Type $VersionType
Write-OK "VERSION: $currentVersion -> $newVersion"

# Diretriz: Verificar CHANGELOG existe
Write-Step 3 6 "Verificando CHANGELOG.md..."
$changelogFile = Join-Path $ProjectRoot "CHANGELOG.md"
if (-not (Test-Path $changelogFile)) {
    Write-FAIL "Arquivo CHANGELOG.md nao encontrado"
    exit 1
}
Write-OK "CHANGELOG.md existe"

# Diretriz: Verificar producao acessivel
Write-Step 4 6 "Verificando producao..."
try {
    $null = Invoke-WebRequest -Uri $ProductionUrl -TimeoutSec 10 -UseBasicParsing
    Write-OK "Producao acessivel"
} catch {
    Write-FAIL "Producao nao acessivel em $ProductionUrl"
    exit 1
}

# Diretriz: Verificar Git configurado
Write-Step 5 6 "Verificando Git..."
Push-Location $ProjectRoot
$gitOK = git rev-parse --git-dir 2>$null
Pop-Location
if (-not $gitOK) {
    Write-FAIL "Repositorio Git nao inicializado"
    exit 1
}
Write-OK "Git OK"

# Mostrar resumo
Write-Step 6 6 "Resumo da release..."
Write-Host ""
Write-Host "  Versao:     $currentVersion -> " -NoNewline; Write-Host $newVersion -ForegroundColor Green
Write-Host "  Tipo:       $ChangeType" -ForegroundColor White
Write-Host "  Descricao:  $ChangeDescription" -ForegroundColor White
Write-Host "  Deploy:     $Deploy" -ForegroundColor White
Write-Host ""

$confirm = Read-Host "  Confirmar release? (s/n)"
if ($confirm -ne 's' -and $confirm -ne 'S') {
    Write-Host "  Abortado pelo usuario" -ForegroundColor Yellow
    exit 0
}

# =============================================================================
# EXECUCAO DO WORKFLOW (Diretrizes v3.0)
# =============================================================================

Write-Header "Executando Release v$newVersion"

# REGRA #1: Atualizar VERSION
Write-Step 1 7 "Atualizando VERSION (Regra #1)..."
Set-Content -Path $versionFile -Value $newVersion -NoNewline
Write-OK "VERSION = $newVersion"

# REGRA #1: Atualizar CHANGELOG
Write-Step 2 7 "Atualizando CHANGELOG (Regra #1)..."
$date = Get-Date -Format "yyyy-MM-dd"
$changelog = Get-Content $changelogFile -Raw
$insertPos = $changelog.IndexOf("`n## [")
if ($insertPos -eq -1) { $insertPos = 0 }
$entry = "`n`n## [$newVersion] - $date`n`n### $ChangeType`n- $ChangeDescription"
$newChangelog = $changelog.Insert($insertPos, $entry)
Set-Content -Path $changelogFile -Value $newChangelog -NoNewline
Write-OK "CHANGELOG atualizado"

# REGRA #4: Deploy via script - FRONTEND
if ($Deploy -eq 'frontend' -or $Deploy -eq 'both') {
    Write-Step 3 7 "Deploy Frontend (Regra #4)..."
    Push-Location (Join-Path $ProjectRoot "frontend")
    npm run build 2>&1 | Out-Null
    ssh $Server "rm -rf /var/www/webmoney/frontend/dist/*" 2>&1 | Out-Null
    scp -r ".\dist\*" "${Server}:/var/www/webmoney/frontend/dist/" 2>&1 | Out-Null
    Pop-Location
    Write-OK "Frontend deployed"
} else {
    Write-Step 3 7 "Frontend: pulado"
}

# REGRA #4: Deploy via script - BACKEND
if ($Deploy -eq 'backend' -or $Deploy -eq 'both') {
    Write-Step 4 7 "Deploy Backend (Regra #4)..."
    Push-Location (Join-Path $ProjectRoot "backend")
    $tar = "$env:TEMP\wm-backend.tar.gz"
    tar -czf $tar --exclude='.git' --exclude='node_modules' --exclude='vendor' --exclude='storage/logs/*' --exclude='.env' . 2>&1 | Out-Null
    scp $tar "${Server}:/tmp/wm-backend.tar.gz" 2>&1 | Out-Null
    ssh $Server "cd /var/www/webmoney/backend && tar -xzf /tmp/wm-backend.tar.gz && rm /tmp/wm-backend.tar.gz && composer install --no-dev -q && php artisan config:cache && php artisan route:cache && systemctl restart php8.4-fpm" 2>&1 | Out-Null
    Remove-Item $tar -ErrorAction SilentlyContinue
    Pop-Location
    Write-OK "Backend deployed"
} else {
    Write-Step 4 7 "Backend: pulado"
}

# REGRA #2: Teste em producao OBRIGATORIO
Write-Step 5 7 "Teste em Producao (Regra #2 - OBRIGATORIO)..."
Start-Process $ProductionUrl
Write-Host ""
Write-Host "  =============================================" -ForegroundColor Yellow
Write-Host "  TESTE EM PRODUCAO OBRIGATORIO (Diretriz #2)" -ForegroundColor Yellow
Write-Host "  =============================================" -ForegroundColor Yellow
Write-Host ""
Write-Host "  URL: $ProductionUrl" -ForegroundColor Cyan
Write-Host ""
Write-Host "  Checklist:" -ForegroundColor White
Write-Host "    [ ] Site carrega corretamente" -ForegroundColor Gray
Write-Host "    [ ] Console sem erros (F12)" -ForegroundColor Gray
Write-Host "    [ ] Funcionalidade testada OK" -ForegroundColor Gray
Write-Host ""

$testOK = Read-Host "  TESTES OK? (s/n)"
if ($testOK -ne 's' -and $testOK -ne 'S') {
    Write-FAIL "Testes nao confirmados - COMMIT BLOQUEADO (Diretriz #2)"
    Write-Host ""
    Write-Host "  As alteracoes de VERSION e CHANGELOG foram feitas." -ForegroundColor Yellow
    Write-Host "  Corrija o problema e execute novamente." -ForegroundColor Yellow
    exit 1
}
Write-OK "Testes confirmados pelo usuario"

# REGRA #5: Commit
Write-Step 6 7 "Git Commit (Regra #5)..."
Push-Location $ProjectRoot
$env:WEBMONEY_RELEASE = "true"
git add -A 2>&1 | Out-Null
git commit -m "v$newVersion - $ChangeDescription" 2>&1 | Out-Null
$env:WEBMONEY_RELEASE = $null
Pop-Location
Write-OK "Commit: v$newVersion - $ChangeDescription"

# Push
Write-Step 7 7 "Git Push..."
Push-Location $ProjectRoot
git push 2>&1 | Out-Null
Pop-Location
Write-OK "Push realizado"

# =============================================================================
# CONCLUSAO
# =============================================================================

Write-Header "Release v$newVersion Concluida"

Write-Host "  VERSION:    $newVersion" -ForegroundColor Green
Write-Host "  CHANGELOG:  Atualizado" -ForegroundColor Green
Write-Host "  DEPLOY:     $Deploy" -ForegroundColor Green
Write-Host "  TESTE:      Confirmado" -ForegroundColor Green
Write-Host "  COMMIT:     OK" -ForegroundColor Green
Write-Host "  PUSH:       OK" -ForegroundColor Green
Write-Host ""
Write-Host "  $ProductionUrl" -ForegroundColor Cyan
Write-Host ""
Write-Host "  Todas as diretrizes v3.0 foram seguidas." -ForegroundColor Green
Write-Host ""
