@echo off
setlocal EnableExtensions
title Bayan GlassCaption - one-time setup
cd /d "%~dp0"

set "LOG=%~dp0resources\install-log.txt"

echo.
echo  ==============================================
echo    Bayan GlassCaption  -  one-time setup
echo  ==============================================
echo.

rem ---- Zip preview? Then EXTRACT FOR THE USER instead of lecturing --------
rem (Double-clicking me inside the downloaded zip is the natural instinct.
rem  Explorer runs zip-preview files from a temp path containing ".zip";
rem  detect that and unpack the real folder ourselves, then continue there.)
echo "%~dp0" | findstr /i /l /c:".zip" >nul
if not errorlevel 1 goto :from_zip

rem Remove Windows' "this came from the internet" flags from every file so
rem nothing warns again after this one time. Silent, best-effort.
powershell -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem -LiteralPath '%~dp0.' -Recurse | Unblock-File" >nul 2>nul

call :mark "install started"

rem ---- STEP 1 of 4: find Python -------------------------------------------
echo  [step 1 of 4]  Checking the app's built-in Python...
set "PYEXE=%~dp0resources\python\python.exe"
if exist "%PYEXE%" (
  echo                 Found it - nothing for you to install.
  call :mark "using bundled python"
  goto :have_python
)

rem ---- Fallback: no bundled python - use the PC's own ---------------------
rem Windows ships a FAKE "python" that just opens the Store; test it runs,
rem then resolve to the real python.exe path so quoting works everywhere.
call :find_system_python
if defined PYEXE (
  echo                 Using this PC's own Python.
  call :mark "using system python"
  goto :have_python
)

:store_loop
echo  Python is not on this PC yet. Opening the Microsoft Store for you...
start "" "ms-windows-store://search/?query=Python+3.13"
echo.
echo  In the Store window that just opened, install "Python 3.13"
echo  by Python Software Foundation. It is free.
echo.
echo  If the Store did not open or is blocked, go to  python.org/downloads
echo  run the installer, and TICK "Add python.exe to PATH".
echo.
echo  When the install has finished, come back here and
pause
call :find_system_python
if not defined PYEXE (
  echo.
  echo  Still not finding Python - no problem, checking again.
  goto :store_loop
)
call :mark "using system python"

:have_python

rem If we're on the PC's own python (no bundled copy), keep everything
rem inside a private venv in resources\ instead of the system install.
if not exist "%~dp0resources\python\python.exe" (
  if not exist "%~dp0resources\venv\Scripts\python.exe" (
    "%PYEXE%" -m venv "%~dp0resources\venv"
    if errorlevel 1 (
      echo  Couldn't create a private Python environment.
      call :mark "FAILED: venv create"
      pause
      exit /b 1
    )
  )
  set "PYEXE=%~dp0resources\venv\Scripts\python.exe"
)

rem ---- STEP 2 of 4: download the app's components --------------------------
echo.
echo  [step 2 of 4]  Downloading the app's components.
echo                 This needs internet and can take a few minutes.
echo                 Nothing else for you to do - just wait.
echo.
call :mark "pip install starting"

rem Make sure pip exists (bundled python has it; belt and braces)
"%PYEXE%" -m pip --version >nul 2>nul || "%PYEXE%" -m ensurepip >nul 2>nul

:pip_loop
"%PYEXE%" -m pip install --disable-pip-version-check --no-warn-script-location -r "%~dp0resources\requirements.txt"
if errorlevel 1 (
  echo.
  echo  The download was interrupted - usually just the wifi hiccuping.
  echo  Check the internet connection, then
  pause
  goto :pip_loop
)
call :mark "pip install done"

rem ---- STEP 3 of 4: self-test ----------------------------------------------
echo.
echo  [step 3 of 4]  Checking every component...
"%PYEXE%" -c "import tkinter, sounddevice, faster_whisper, numpy" >nul 2>nul
if errorlevel 1 (
  echo.
  echo  Setup finished but a component failed its check.
  echo  Please take a photo of this window and send it to David.
  "%PYEXE%" -c "import tkinter, sounddevice, faster_whisper, numpy"
  call :mark "FAILED: self-test"
  pause
  exit /b 1
)
echo                 All good.
call :mark "self-test passed"

rem ---- STEP 4 of 4: gold icons (VISIBLE - if it fails, we see why) ---------
echo.
echo  [step 4 of 4]  Creating your gold "Bayan GlassCaption" icons...
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0resources\make-shortcuts.ps1"
if errorlevel 1 (
  echo.
  echo  Windows would not let the installer create shortcuts - some school
  echo  PCs block this. Making a simple launcher in this folder instead.
  call :mark "shortcuts FAILED - writing bat launcher"
  > "%~dp0Bayan GlassCaption.bat" (
    echo @echo off
    echo set "PYW=%%~dp0resources\python\pythonw.exe"
    echo if not exist "%%PYW%%" set "PYW=%%~dp0resources\venv\Scripts\pythonw.exe"
    echo start "" "%%PYW%%" "%%~dp0resources\app\main.py"
  )
  echo  Done: double-click "Bayan GlassCaption" in this folder to start it.
) else (
  call :mark "shortcuts created"
)

rem ---- Launch the app directly - no scripts in between ---------------------
set "PYW=%~dp0resources\python\pythonw.exe"
if not exist "%PYW%" set "PYW=%~dp0resources\venv\Scripts\pythonw.exe"

echo.
echo  ==============================================
echo    ALL DONE!
echo.
echo    Look for the gold "Bayan GlassCaption" icon:
echo      - on your DESKTOP
echo      - in the Start Menu
echo      - and right here in this folder
echo.
echo    Want it on the taskbar at the bottom?
echo    Right-click the DESKTOP icon and choose
echo    "Pin to taskbar". Windows only allows a
echo    person to do that, not a program.
echo.
echo    The app is opening now - its very first
echo    launch downloads the speech models, so give
echo    it a few minutes on good wifi.
echo  ==============================================
echo.
call :mark "install complete - launching app"
start "" "%PYW%" "%~dp0resources\app\main.py"
echo  This window is safe to close. Or
pause
exit /b 0

rem ---- clicked inside the zip: unpack properly, hand over, exit ------------
:from_zip
echo  You clicked me from inside the downloaded zip - that's fine!
echo  Unpacking the app properly for you now... this takes a minute.
echo.
set "ZIP="
for /f "delims=" %%z in ('dir /b /o-d "%USERPROFILE%\Downloads\Bayan-GlassCaption-Windows*.zip" 2^>nul') do if not defined ZIP set "ZIP=%USERPROFILE%\Downloads\%%z"
if not defined ZIP for /f "delims=" %%z in ('dir /b /o-d "%USERPROFILE%\Desktop\Bayan-GlassCaption-Windows*.zip" 2^>nul') do if not defined ZIP set "ZIP=%USERPROFILE%\Desktop\%%z"
if not defined ZIP goto :manual_extract
echo  Found: %ZIP%
echo  Unpacking to your Downloads folder...
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Expand-Archive -LiteralPath '%ZIP%' -DestinationPath '%USERPROFILE%\Downloads' -Force; Get-ChildItem -LiteralPath '%USERPROFILE%\Downloads\Bayan GlassCaption' -Recurse | Unblock-File"
if errorlevel 1 goto :manual_extract
if not exist "%USERPROFILE%\Downloads\Bayan GlassCaption\INSTALL - CLICK ME FIRST.bat" goto :manual_extract
echo.
echo  Done! Setup now continues in a NEW window.
echo  You can close this window and any open zip windows.
start "" cmd /c ""%USERPROFILE%\Downloads\Bayan GlassCaption\INSTALL - CLICK ME FIRST.bat""
exit /b 0

:manual_extract
echo  Couldn't unpack automatically on this PC. No problem - do it by hand:
echo    1. Close this window
echo    2. In Downloads, right-click the Bayan zip and choose "Extract All"
echo    3. Click Extract, then open the new "Bayan GlassCaption" folder
echo    4. Double-click "INSTALL - CLICK ME FIRST" in there
echo.
pause
exit /b 1

rem ---- resolve a REAL system python.exe into PYEXE (or leave unset) --------
:find_system_python
set "PYEXE="
py -3 -c "import sys" >nul 2>nul
if not errorlevel 1 (
  for /f "delims=" %%i in ('py -3 -c "import sys;print(sys.executable)"') do set "PYEXE=%%i"
  goto :eof
)
python -c "import sys" >nul 2>nul
if not errorlevel 1 (
  for /f "delims=" %%i in ('python -c "import sys;print(sys.executable)"') do set "PYEXE=%%i"
)
goto :eof

rem ---- breadcrumb into resources\install-log.txt (never blocks install) ----
:mark
(echo %date% %time%  %~1)>>"%LOG%" 2>nul
goto :eof
