$ErrorActionPreference = 'Stop'
try { [Console]::OutputEncoding = [Text.Encoding]::UTF8; $OutputEncoding = [Text.Encoding]::UTF8 } catch {}
$source = Split-Path -Parent $MyInvocation.MyCommand.Path
$installDir = Join-Path $env:LOCALAPPDATA 'FlowInsta BR Agent'
$startupDir = [Environment]::GetFolderPath('Startup')
$startupCmd = Join-Path $startupDir 'FlowInsta BR Agent.cmd'
$launcherCmd = Join-Path $installDir 'ABRIR_AGENT.cmd'
$iconPath = Join-Path $installDir 'flowinsta-agent-icon.ico'
$desktopLauncher = Join-Path ([Environment]::GetFolderPath('Desktop')) 'FlowInsta BR Agent.cmd'
$desktopShortcut = Join-Path ([Environment]::GetFolderPath('Desktop')) 'FlowInsta BR Agent.lnk'
$installLogPath = Join-Path $installDir 'install.log'

function New-AgentShortcut([string]$shortcutPath, [string]$targetPath) {
  try {
    $shell = New-Object -ComObject WScript.Shell
    $shortcut = $shell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = $targetPath
    $shortcut.WorkingDirectory = Split-Path -Parent $targetPath
    $shortcut.WindowStyle = 1
    $shortcut.Description = 'Abrir FlowInsta BR Agent'
    if (Test-Path -LiteralPath $iconPath) { $shortcut.IconLocation = $iconPath }
    $shortcut.Save()
    return $true
  } catch {
    Add-Content -LiteralPath $installLogPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Falha ao criar atalho: $($_.Exception.Message)" -Encoding UTF8
    return $false
  }
}

Write-Host ''
Write-Host 'FlowInsta BR Agent 6.0.4 - Instalação' -ForegroundColor Green
Write-Host 'A extensão Chrome atual continuará funcionando, mas este Agent executa direto, sem chrome://extensions.'

New-Item -ItemType Directory -Path $installDir -Force | Out-Null
Copy-Item -Path (Join-Path $source '*') -Destination $installDir -Recurse -Force
Add-Content -LiteralPath $installLogPath -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') Instalação/atualizacao executada." -Encoding UTF8

$startupContent = "@echo off`r`nchcp 65001 >nul`r`nstart `"FlowInsta BR Agent`" `"$launcherCmd`"`r`n"
[IO.File]::WriteAllText($startupCmd, $startupContent, [Text.Encoding]::ASCII)
if (Test-Path -LiteralPath $launcherCmd) {
  [IO.File]::WriteAllText($desktopLauncher, "@echo off`r`nchcp 65001 >nul`r`ncall `"$launcherCmd`"`r`n", [Text.Encoding]::ASCII)
  New-AgentShortcut $desktopShortcut $launcherCmd | Out-Null
}

Write-Host "Instalado em: $installDir" -ForegroundColor Green
Write-Host 'O Agent iniciará junto com o Windows.'
Write-Host "Atalho criado na Área de Trabalho: $desktopShortcut" -ForegroundColor Green
Write-Host "Atalho alternativo criado: $desktopLauncher" -ForegroundColor Green
Write-Host "Log da instalação: $installLogPath"
Write-Host ''
Write-Host 'Vou abrir o Agent em uma janela separada. Ele mostrará status, contadores e próximas ações.' -ForegroundColor Yellow
Write-Host 'Se ele pedir código, gere o código no painel e digite na janela.' -ForegroundColor Yellow
Write-Host 'Esta versão corrige a abertura repetida de guias do Chrome pelo Agent.' -ForegroundColor Yellow
if (Test-Path -LiteralPath $launcherCmd) {
  Start-Process -FilePath $launcherCmd
} else {
  $agentArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$(Join-Path $installDir 'agent.ps1')`"") -join ' '
  Start-Process powershell.exe -ArgumentList $agentArgs
}




