@echo off
chcp 65001 > nul
title IALIST - Instalador e Inicializador do Agente v3.0
color 0A

echo.
echo ==========================================
echo   Instalador do Agente IALIST v3.0
echo ==========================================
echo.

echo [1/4] Verificando Node.js...
where node >nul 2>nul
if %ERRORLEVEL% neq 0 (
    echo [ERRO] Node.js nao encontrado!
    echo Por favor, instale o Node.js em: https://nodejs.org
    pause
    exit /b 1
)
echo [OK] Node.js encontrado.

set "AGENT_DIR=%USERPROFILE%\ialist-agent"
if not exist "%AGENT_DIR%" (
    mkdir "%AGENT_DIR%" 2>nul
)
cd /d "%AGENT_DIR%"

if not exist "package.json" (
    echo { "name": "ialist-agent", "version": "3.0.0" } > package.json
)

echo [2/4] Instalando dependencias...
call npm install playwright axios @google/generative-ai dotenv --save --silent 2>nul
call npx playwright install chromium 2>nul
echo [OK] Dependencias instaladas.

if not exist ".env" (
    echo [3/4] Criando arquivo .env...
    echo GEMINI_API_KEY=SUA_CHAVE_GEMINI_AQUI > .env
    echo.
    echo [IMPORTANTE] Abra o arquivo .env em:
    echo %AGENT_DIR%\.env
    echo e adicione sua chave GEMINI_API_KEY antes de continuar.
    echo.
    pause
) else (
    echo [3/4] .env ja existe, pulando.
)

echo [4/4] Baixando agente mais recente do servidor...
powershell -Command "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri 'https://ialist.deletrics.site/api/download-agent' -OutFile 'agent.js'" 2>nul
if %ERRORLEVEL% neq 0 (
    curl -s -o agent.js "https://ialist.deletrics.site/api/download-agent" 2>nul
)
echo [OK] Agente atualizado.

echo.
echo ==========================================
echo   TUDO PRONTO! Iniciando o Agente...
echo ==========================================
echo.

node agent.js

pause