@echo off
setlocal EnableExtensions

title AI Voice Bridge Installer

echo ===============================================
echo AI Voice Bridge Installer
echo Windows Whisper Customer Build 3.1 - Icon + Shortcut + Python Pack
echo ===============================================
echo.

set "SCRIPT_DIR=%~dp0"
set "PAYLOAD=%SCRIPT_DIR%payload"
set "DEST=%USERPROFILE%\Documents\RITS-AI-Voice-Bridge"
set "OLD_UNBRANDED_DEST=%USERPROFILE%\Documents\AI-Voice-Bridge"

set "OLD_DEST_2=%USERPROFILE%\Documents\RITS-Voice-Bridge"
set "OLD_DEST=%USERPROFILE%\Documents\RITS-Local-AI-Voice-Bridge-Windows"
set "PYTHON_OK=0"
set "PYTHON_CMD="
set "CHROME_OK=0"
set "VCREDIST_OK=0"
set "BRIDGE_EXISTS=0"
set "LEGACY_EXISTS=0"

echo Installer folder:
echo %SCRIPT_DIR%
echo.

echo Checking installer payload...
if not exist "%PAYLOAD%\voice-bridge-extension\manifest.json" goto MissingPayload
if not exist "%PAYLOAD%\ai_voice_bridge_server.py" goto MissingPayload
if not exist "%PAYLOAD%\Start-AI-Voice-Bridge.bat" goto MissingPayload
if not exist "%PAYLOAD%\Setup-Local-Dictation-Windows.bat" goto MissingPayload
echo [OK] Installer payload found.
echo.

echo Checking Python 3...
py -3 -c "import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)" >nul 2>nul
if %ERRORLEVEL%==0 set "PYTHON_OK=1"
if %ERRORLEVEL%==0 set "PYTHON_CMD=py -3"

if "%PYTHON_OK%"=="1" goto PythonDone
python -c "import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)" >nul 2>nul
if %ERRORLEVEL%==0 set "PYTHON_OK=1"
if %ERRORLEVEL%==0 set "PYTHON_CMD=python"

if "%PYTHON_OK%"=="1" goto PythonDone
python3 -c "import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)" >nul 2>nul
if %ERRORLEVEL%==0 set "PYTHON_OK=1"
if %ERRORLEVEL%==0 set "PYTHON_CMD=python3"

:PythonDone
if "%PYTHON_OK%"=="1" echo [OK] Python 3 detected: %PYTHON_CMD%
if "%PYTHON_OK%"=="0" (
    echo [MISSING] Python 3 was not detected.
    if exist "%PAYLOAD%\python-3.10.11-amd64.exe" echo [OK] Included Python installer found: %PAYLOAD%\python-3.10.11-amd64.exe
)
echo.

echo Checking Google Chrome...
if exist "%ProgramFiles%\Google\Chrome\Application\chrome.exe" set "CHROME_OK=1"
if exist "%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe" set "CHROME_OK=1"
if exist "%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe" set "CHROME_OK=1"

if "%CHROME_OK%"=="1" echo [OK] Google Chrome detected.
if "%CHROME_OK%"=="0" echo [MISSING] Google Chrome was not detected.
echo.
echo Checking Microsoft Visual C++ Redistributable x64...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$items = @(Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*,HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Visual C++*' -and $_.DisplayName -like '*x64*' -and $_.DisplayVersion -like '14.*' }); if ($items.Count -gt 0) { exit 0 } else { exit 1 }" >nul 2>nul
if %ERRORLEVEL%==0 set "VCREDIST_OK=1"
if "%VCREDIST_OK%"=="1" echo [OK] Microsoft Visual C++ x64 runtime detected.
if "%VCREDIST_OK%"=="0" (
    echo [WARNING] Microsoft Visual C++ x64 runtime was not detected.
    echo If local dictation crashes with server exit code -1073741819, install/update Microsoft Visual C++ 2015-2022 Redistributable x64, reboot, and try again.
    echo Command: winget install --id Microsoft.VCRedist.2015+.x64 --source winget --accept-package-agreements --accept-source-agreements
)
echo.

if "%PYTHON_OK%"=="0" goto MissingPython
if "%CHROME_OK%"=="0" goto MissingChrome

echo Checking existing installation...
if exist "%DEST%\ai_voice_bridge_server.py" set "BRIDGE_EXISTS=1"
if exist "%DEST%\Start-AI-Voice-Bridge.bat" set "BRIDGE_EXISTS=1"
if exist "%OLD_DEST%\speaker_server_windows.py" set "LEGACY_EXISTS=1"
if exist "%OLD_DEST%\Start-RITS-Local-AI-Voice-Bridge.bat" set "LEGACY_EXISTS=1"
if exist "%OLD_DEST_2%\rits_voice_bridge_server.py" set "LEGACY_EXISTS=1"
if exist "%OLD_DEST_2%\Start-RITS-Voice-Bridge.bat" set "LEGACY_EXISTS=1"

if "%BRIDGE_EXISTS%"=="1" echo [FOUND] Existing AI Voice Bridge installation detected. Packaged app files will be refreshed. Existing dictation model will be preserved.
if "%BRIDGE_EXISTS%"=="0" echo [NEW] No existing AI Voice Bridge installation detected. New install will be created.
if "%LEGACY_EXISTS%"=="1" echo [FOUND] Legacy RITS Local AI Voice Bridge folder detected. App files will still install cleanly.
echo.

echo Installing to:
echo %DEST%
echo.

if not exist "%DEST%" if exist "%OLD_UNBRANDED_DEST%" (
    echo [FOUND] Previous unbranded install detected at: %OLD_UNBRANDED_DEST%
    echo Migrating existing files to: %DEST%
    move "%OLD_UNBRANDED_DEST%" "%DEST%" >nul 2>nul
    if exist "%DEST%" (
        echo [OK] Previous install migrated.
    ) else (
        echo [WARN] Migration could not move old folder automatically. A fresh app folder will be created.
    )
    echo.
)

if not exist "%DEST%" mkdir "%DEST%"
if not exist "%DEST%" goto InstallFolderFailed

echo Copying/refreshing packaged AI Voice Bridge files...
xcopy "%PAYLOAD%\*" "%DEST%\" /E /I /Y >nul
if errorlevel 1 goto CopyFailed

copy /Y "%SCRIPT_DIR%README.txt" "%DEST%\README.txt" >nul
if errorlevel 1 goto CopyFailed

if not exist "%DEST%\voice-bridge-extension\manifest.json" goto CopyFailed
if not exist "%DEST%\ai_voice_bridge_server.py" goto CopyFailed
if not exist "%DEST%\Start-AI-Voice-Bridge.bat" goto CopyFailed


if not exist "%DEST%\assets\app-icon.ico" goto ShortcutStep

set "DESKTOP_SHORTCUT=%USERPROFILE%\Desktop\RITS AI Voice Bridge.lnk"
set "STARTMENU_DIR=%APPDATA%\Microsoft\Windows\Start Menu\Programs"
set "STARTMENU_SHORTCUT=%STARTMENU_DIR%\RITS AI Voice Bridge.lnk"
set "OLD_DESKTOP_SHORTCUT=%USERPROFILE%\Desktop\AI Voice Bridge.lnk"
set "OLD_STARTMENU_SHORTCUT=%STARTMENU_DIR%\AI Voice Bridge.lnk"
if exist "%OLD_DESKTOP_SHORTCUT%" del /q "%OLD_DESKTOP_SHORTCUT%" >nul 2>nul
if exist "%OLD_STARTMENU_SHORTCUT%" del /q "%OLD_STARTMENU_SHORTCUT%" >nul 2>nul

echo Creating/updating app shortcuts...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ws = New-Object -ComObject WScript.Shell; $target = '%DEST%\Start-AI-Voice-Bridge.bat'; $icon = '%DEST%\assets\app-icon.ico'; $desktop = '%DESKTOP_SHORTCUT%'; $startm = '%STARTMENU_SHORTCUT%'; foreach ($path in @($desktop,$startm)) { $s = $ws.CreateShortcut($path); $s.TargetPath = $target; $s.WorkingDirectory = '%DEST%'; $s.IconLocation = $icon; $s.Description = 'Launch RITS AI Voice Bridge'; $s.Save() }" >nul 2>nul
if errorlevel 1 (
    echo [WARN] Shortcut creation did not complete.
) else (
    echo [OK] Desktop shortcut created: %DESKTOP_SHORTCUT%
    echo [OK] Start Menu shortcut created: %STARTMENU_SHORTCUT%
)

:ShortcutStep
echo.
echo ===============================================
echo AI VOICE BRIDGE FILE REFRESH COMPLETE
echo ===============================================
echo.
echo App folder:
echo %DEST%
echo.
echo Checking local dictation dependencies...
echo Default backend: Whisper accuracy backend.
echo Local app Python environment will be created/reused. Missing Whisper files will be downloaded.
echo.
call "%DEST%\Setup-Local-Dictation-Windows.bat" /auto
if errorlevel 1 (
    echo.
    echo WARNING: Local dictation setup did not complete.
    echo The main bridge is installed, but private local dictation will not work until setup succeeds.
    echo Manual retry:
    echo %DEST%\Setup-Local-Dictation-Windows.bat
    echo %DEST%\LOCAL_DICTATION_SETUP_WINDOWS.txt
) else (
    echo.
    echo [OK] Local dictation setup/check complete.
)

echo.
echo Next steps:
echo 1. Open Google Chrome.
echo 2. Go to chrome://extensions
echo 3. Turn Developer mode ON.
echo 4. Click Load unpacked.
echo 5. Select this folder:
echo %DEST%\voice-bridge-extension
echo.
echo Then start the server:
echo %DEST%\Start-AI-Voice-Bridge.bat
echo or use the Desktop / Start Menu shortcut:
echo RITS AI Voice Bridge
echo.
echo App icon files were installed to:
echo %DEST%\assets
echo.
echo Troubleshooting note: if the Mic/Dictate button fails with Failed to fetch and the server exits with -1073741819, update/reinstall Microsoft Visual C++ 2015-2022 Redistributable x64 and reboot.
echo.
echo Setup finished. Press any key to exit.
echo.
pause
exit /b 0

:MissingPayload
echo.
echo ERROR: Installer payload was not found or is incomplete.
echo.
echo This usually means the ZIP was not fully extracted.
echo Extract the entire ZIP first, then run this BAT from the extracted folder.
echo.
echo Expected folder:
echo %PAYLOAD%
echo.
pause
exit /b 1

:MissingPython
echo.
echo ERROR: Python 3 was not detected.
echo.
if exist "%PAYLOAD%\python-3.10.11-amd64.exe" (
    echo An included Python installer is available here:
    echo %PAYLOAD%\python-3.10.11-amd64.exe
    echo.
    echo Run that Python installer, make sure Add python.exe to PATH is checked if shown,
    echo then rerun Run-AI-Voice-Bridge-Windows-Installer.bat.
) else (
    echo Install Python 3, then rerun this installer.
)
echo.
pause
exit /b 1

:MissingChrome
echo.
echo ERROR: Google Chrome was not detected.
echo Install Google Chrome, then rerun this installer.
echo.
pause
exit /b 1

:InstallFolderFailed
echo.
echo ERROR: Could not create install folder:
echo %DEST%
echo.
pause
exit /b 1

:CopyFailed
echo.
echo ERROR: File copy failed.
echo Source:
echo %PAYLOAD%
echo.
echo Destination:
echo %DEST%
echo.
echo Try extracting the ZIP to Desktop first, then rerun the installer.
echo.
pause
exit /b 1
