@echo off
setlocal EnableDelayedExpansion
REM build_windows.bat -- TranscribeStation v1.0.1
REM A executer sur une machine Windows avec Python 3.12+
echo.
echo *** Build TranscribeStation v1.0.1 pour Windows ***
echo.

REM -- Localisation du projet
set "SCRIPT_DIR=%~dp0"
for %%I in ("%SCRIPT_DIR%\..") do set "PROJECT_ROOT=%%~fI\"
if exist "%PROJECT_ROOT%transcribe_station.py" goto ROOT_FOUND
for %%I in ("%SCRIPT_DIR%\..\..") do set "PROJECT_ROOT=%%~fI\"
if exist "%PROJECT_ROOT%transcribe_station.py" goto ROOT_FOUND
echo [XX] transcribe_station.py introuvable.
pause & exit /b 1

:ROOT_FOUND
echo [OK] Dossier projet : %PROJECT_ROOT%
echo.

REM -- Localisation d'un vrai Python (evite le stub Windows Store)
set "REAL_PYTHON="

REM Essai 1 : py launcher (installe avec Python officiel)
where py >nul 2>&1
if not errorlevel 1 (
    py -3 -c "import sys; print(sys.executable)" >nul 2>&1
    if not errorlevel 1 (
        for /f "delims=" %%P in ('py -3 -c "import sys; print(sys.executable)"') do set "REAL_PYTHON=%%P"
    )
)

REM Essai 2 : emplacements standard Python 3.x
if not defined REAL_PYTHON (
    for %%V in (313 312 311 310 39) do (
        if not defined REAL_PYTHON (
            if exist "C:\Python%%V\python.exe" set "REAL_PYTHON=C:\Python%%V\python.exe"
        )
    )
)
REM Essai 3 : AppData\Local\Programs\Python
if not defined REAL_PYTHON (
    for %%V in (313 312 311 310 39) do (
        if not defined REAL_PYTHON (
            set "_CANDIDATE=%LOCALAPPDATA%\Programs\Python\Python%%V\python.exe"
            if exist "!_CANDIDATE!" set "REAL_PYTHON=!_CANDIDATE!"
        )
    )
)

if not defined REAL_PYTHON (
    echo [XX] Python 3 introuvable. Installez Python depuis https://www.python.org/downloads/
    echo [XX] Assurez-vous de cocher "Add python.exe to PATH" lors de l'installation.
    pause & exit /b 1
)
echo [OK] Python trouve : %REAL_PYTHON%

REM -- Venv a chemin court pour eviter MAX_PATH avec PySide6
set "VENV=C:\ts\.venv"
set "VPYTHON=%VENV%\Scripts\python.exe"
set "VPIP=%VENV%\Scripts\pip.exe"
echo [1/5] Preparation venv dans %VENV%...
if exist "%VENV%" (
    "%VPYTHON%" -c "import sys" >nul 2>&1
    if errorlevel 1 (
        echo [!!] Venv existant invalide - recreation...
        rmdir /S /Q "%VENV%"
    )
)
if not exist "%VPYTHON%" (
    mkdir C:\ts 2>nul
    "%REAL_PYTHON%" -m venv "%VENV%"
    if errorlevel 1 ( echo ERREUR venv & pause & exit /b 1 )
)
echo [OK] Venv pret.

echo [2/5] Installation des dependances Python...
"%VPIP%" install --quiet --upgrade pip
"%VPIP%" install --quiet pyinstaller PySide6 numpy soundfile hid Pillow
if errorlevel 1 ( echo ERREUR pip & pause & exit /b 1 )
"%VPYTHON%" -c "from PySide6.QtMultimedia import QMediaPlayer; print('[OK] PySide6 + QtMultimedia OK')"
if errorlevel 1 ( echo ERREUR PySide6.QtMultimedia & pause & exit /b 1 )

echo [3/5] Generation des icones...
copy /Y "%SCRIPT_DIR%_build_icons.py" "%PROJECT_ROOT%_build_icons.py" > nul
"%VPYTHON%" "%PROJECT_ROOT%_build_icons.py"
if errorlevel 1 ( echo ERREUR icones & pause & exit /b 1 )
del "%PROJECT_ROOT%_build_icons.py" > nul 2>&1

REM -- Build dans C:\ts (chemin local court) pour eviter les erreurs reseau/MAX_PATH
set "LOCAL_DIST=C:\ts\dist"
set "LOCAL_BUILD=C:\ts\build"

echo [4/5] Compilation PyInstaller (sortie locale C:\ts\dist)...
"%VENV%\Scripts\pyinstaller.exe" --onedir --windowed --clean --noconfirm ^
    --name TranscribeStation ^
    --distpath "%LOCAL_DIST%" ^
    --workpath "%LOCAL_BUILD%" ^
    --specpath "%LOCAL_BUILD%" ^
    --icon "%PROJECT_ROOT%icon.ico" ^
    --hidden-import PySide6.QtMultimedia ^
    --hidden-import PySide6.QtCore ^
    --hidden-import PySide6.QtGui ^
    --hidden-import PySide6.QtWidgets ^
    --hidden-import soundfile ^
    --hidden-import numpy ^
    --hidden-import hid ^
    --hidden-import cffi ^
    --hidden-import _cffi_backend ^
    --collect-all hid ^
    "%PROJECT_ROOT%transcribe_station.py"
if errorlevel 1 ( echo ERREUR PyInstaller & pause & exit /b 1 )

REM -- Ajout de hidapi.dll (absent du package pip hid)
set "HIDAPI_URL=https://github.com/libusb/hidapi/releases/download/hidapi-0.14.0/hidapi-win.zip"
set "HIDAPI_ZIP=C:\ts\hidapi-win.zip"
set "HIDAPI_DLL=%LOCAL_DIST%\TranscribeStation\_internal\hidapi.dll"
if not exist "%HIDAPI_DLL%" (
    echo    Telechargement hidapi.dll...
    powershell -NoProfile -Command "Invoke-WebRequest -Uri '%HIDAPI_URL%' -OutFile '%HIDAPI_ZIP%'"
    if not errorlevel 1 (
        powershell -NoProfile -Command "Expand-Archive -Force '%HIDAPI_ZIP%' 'C:\\ts\\hidapi_tmp'; $dll = Get-ChildItem 'C:\\ts\\hidapi_tmp' -Recurse -Filter hidapi.dll | Where-Object { $_.FullName -match 'x64' } | Select-Object -First 1; if ($dll) { Copy-Item $dll.FullName '%HIDAPI_DLL%'; Write-Host '[OK] hidapi.dll installe' } else { Write-Host '[!!] hidapi.dll x64 introuvable dans archive' }; Remove-Item 'C:\\ts\\hidapi_tmp' -Recurse -Force"
    ) else (
        echo [!!] Echec telechargement hidapi.dll - le pedalier ne fonctionnera pas.
    )
) else (
    echo [OK] hidapi.dll deja present.
)

echo    Copie du binaire vers le dossier projet...
if exist "%PROJECT_ROOT%dist\windows\TranscribeStation" rmdir /S /Q "%PROJECT_ROOT%dist\windows\TranscribeStation"
xcopy /E /I /Y "%LOCAL_DIST%\TranscribeStation" "%PROJECT_ROOT%dist\windows\TranscribeStation\"
if errorlevel 1 ( echo ERREUR copie xcopy & pause & exit /b 1 )
echo [OK] Binaire copie dans %PROJECT_ROOT%dist\windows\TranscribeStation\

echo [5/5] Installation des raccourcis...
REM Raccourci vers binaire LOCAL (WScript.Shell refuse les chemins reseau/partages)
set "LOCAL_EXE=%LOCAL_DIST%\TranscribeStation\TranscribeStation.exe"
if exist "%PROJECT_ROOT%dist\windows\install_shortcut.ps1" (
    powershell -NoProfile -ExecutionPolicy Bypass ^
      -File "%PROJECT_ROOT%dist\windows\install_shortcut.ps1" ^
      -ExePath "%LOCAL_EXE%"
) else (
    echo [!!] Script PowerShell introuvable
)

copy /Y "%PROJECT_ROOT%icon.ico" "C:\ts\icon.ico" > nul

echo [6/6] Creation de l'installeur (Inno Setup)...
set "ISCC_EXE="
if exist "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" set "ISCC_EXE=C:\Program Files (x86)\Inno Setup 6\ISCC.exe"
if exist "C:\Program Files\Inno Setup 6\ISCC.exe" set "ISCC_EXE=C:\Program Files\Inno Setup 6\ISCC.exe"
if not defined ISCC_EXE (
    echo [!!] Inno Setup 6 non installe - installeur ignore.
    echo [!!] Telecharger gratuitement : https://jrsoftware.org/isdl.php
    echo [!!] Puis relancez ce script pour generer l'installeur.
    goto BUILD_DONE
)
mkdir C:\ts\installer 2>nul
echo    Compilation Inno Setup...
"%ISCC_EXE%" "%SCRIPT_DIR%TranscribeStation.iss"
if errorlevel 1 ( echo [!!] Erreur Inno Setup & goto BUILD_DONE )
echo [OK] Installeur : C:\ts\installer\TranscribeStation_Setup_v1.0.1.exe

:BUILD_DONE
echo.
echo *** Build termine ! ***
echo Binaire    : %PROJECT_ROOT%dist\windows\TranscribeStation\TranscribeStation.exe
echo Installeur : C:\ts\installer\TranscribeStation_Setup_v1.0.1.exe (si Inno Setup installe)
echo.
pause
