@echo off
setlocal
cd /d "%~dp0"
chcp 65001 >nul

rem Advanced usage: RepoKey-Setup.cmd init|register|selftest [project-path]
if /i "%~1"=="diagnose" (
  "%~dp0repokey-client.cmd" diagnose
  pause
  exit /b %errorlevel%
)
if /i "%~1"=="init" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\init_project_prompt.ps1" %2
  pause
  exit /b %errorlevel%
)
if /i "%~1"=="register" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\register_all_mcp.ps1" -Mode install
  pause
  exit /b %errorlevel%
)
if /i "%~1"=="selftest" (
  powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\customer_self_test.ps1"
  pause
  exit /b %errorlevel%
)

cls
echo ============================================
echo   RepoKey Vivado AI - Setup Wizard
echo ============================================
echo.
echo This wizard runs the required steps in order.
echo Please follow the prompts; each step runs automatically.
echo.
pause

echo.
echo [Step 1/4] Install / Repair  (License + Vivado + config)
echo.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\setup_wizard.ps1"
if errorlevel 1 goto fail
echo.
pause

echo.
echo [Step 2/4] Self Test
echo.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\customer_self_test.ps1"
echo.
pause

echo.
echo [Step 3/4] Init Project  (choose your Vivado project folder)
echo.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\init_project_prompt.ps1"
if errorlevel 3 goto stopped
if errorlevel 1 goto fail
echo.
pause

echo.
echo [Step 4/4] Register MCP  (register all RepoKey MCP servers)
echo.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install\register_all_mcp.ps1" -Mode install
echo.
echo Verifying MCP server reachability...
"%~dp0repokey-client.cmd" mcp-selfcheck
if errorlevel 1 (
  echo.
  echo [WARN] MCP self-check did not pass. See the message above.
  echo If it mentions License: open licenses\repokey-license.txt and paste the complete
  echo RK1... license text from your email, save, then run RepoKey-Setup.cmd again.
  echo Otherwise: close security software, re-extract the package, and retry.
  echo If it still fails, run: repokey-client.cmd diagnose  and send the generated zip to support.
  echo.
  pause
  exit /b 1
)
echo.
pause

echo.
echo ============================================
echo   Setup finished.
echo   IMPORTANT: fully close and restart your AI
echo   client (Codex / Claude / Cursor / Cline)
echo   so it reloads the MCP configuration.
echo ============================================
echo.
pause
exit /b 0

:stopped
echo.
echo Setup stopped by user. Re-run RepoKey-Setup.cmd to continue later.
pause
exit /b 0

:fail
echo.
echo Setup stopped due to an error. Fix the issue shown above, then re-run RepoKey-Setup.cmd.
pause
exit /b 1
