@echo off
setlocal

REM Kindle Key Finder V2 Launcher

REM Prevent Python from generating __pycache__ folders
set PYTHONDONTWRITEBYTECODE=1

REM Change to batch file's directory
cd /d "%~dp0"

REM =========================================================================
REM REQUIRE ADMIN RIGHTS - auto-elevate via UAC if not already elevated
REM =========================================================================
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo.
    echo  [*] Administrator rights are required.
    echo      A UAC prompt will appear - click Yes to continue.
    echo.
    wscript.exe "%~dp0Run_keyfinder_admin.vbs"
    exit /b
)

REM -------------------------------------------------------------------------
REM PYTHON DETECTION
REM
REM Windows 11 always places the WindowsApps folder FIRST in the PATH.
REM This means "where python" returns the WindowsApps stub BEFORE any
REM real Python installation.  The old code took the first result and
REM hard-blocked - falsely flagging users who had uninstalled MS Store
REM Python (leaving behind the harmless WindowsApps stub) but also had
REM a proper python.org install further down the PATH.
REM
REM NEW APPROACH:
REM   1. Iterate ALL results from "where python"
REM   2. Skip any result that lives in WindowsApps (stubs / aliases)
REM   3. Skip any result that lives in a PythonSoftwareFoundation
REM      Packages folder (actual MS Store sandbox install)
REM   4. Accept the FIRST path that passes both checks as the real Python
REM   5. Launch key_finder.py using that ABSOLUTE path so the stub can
REM      never intercept it even after launch
REM -------------------------------------------------------------------------

set "REAL_PYTHON="

REM Collect every python.exe on PATH and pick the first non-stub one
for /f "delims=" %%i in ('where python 2^>nul') do (
    REM Skip WindowsApps stubs (these are App Execution Aliases, not real Python)
    echo %%i | findstr /i "WindowsApps" >nul
    if errorlevel 1 (
        REM Skip actual MS Store sandbox installs (Packages\PythonSoftwareFoundation path)
        echo %%i | findstr /i "PythonSoftwareFoundation" >nul
        if errorlevel 1 (
            REM This path passed both filters - it is a real python.org install
            if not defined REAL_PYTHON (
                set "REAL_PYTHON=%%i"
            )
        )
    )
)

REM If no real Python found, check whether ONLY WindowsApps stubs exist
REM (user may have installed python.org but its PATH entry comes after WindowsApps
REM  - try a direct registry / well-known path fallback before giving up)
if not defined REAL_PYTHON (
    REM Fallback 1: check common python.org default install locations
    for %%d in (
        "%LOCALAPPDATA%\Programs\Python"
        "%ProgramFiles%\Python"
        "%ProgramFiles(x86)%\Python"
        "C:\Python313"
        "C:\Python312"
        "C:\Python311"
        "C:\Python310"
        "C:\Python39"
        "C:\Python38"
    ) do (
        if not defined REAL_PYTHON (
            for /d %%v in ("%%~d\Python3*" "%%~d") do (
                if not defined REAL_PYTHON (
                    if exist "%%~v\python.exe" (
                        set "REAL_PYTHON=%%~v\python.exe"
                    )
                )
            )
        )
    )
)

if not defined REAL_PYTHON (
    REM No real Python found anywhere - check if a WindowsApps stub exists
    REM (means python.org is not installed at all, only the Store/stub)
    for /f "delims=" %%i in ('where python 2^>nul') do (
        set "STUB_PYTHON=%%i"
        goto :check_stub
    )
    REM where python returned nothing at all
    goto :python_not_found

    :check_stub
    echo %STUB_PYTHON% | findstr /i "WindowsApps" >nul
    if not errorlevel 1 (
        goto :store_python_warning
    )
    echo %STUB_PYTHON% | findstr /i "PythonSoftwareFoundation" >nul
    if not errorlevel 1 (
        goto :store_python_warning
    )
    REM Should not reach here but just in case
    goto :python_not_found
)

REM Real Python found - proceed
set "PYTHON_EXE=%REAL_PYTHON%"
goto :run_script

:python_not_found
echo.
echo [ERROR] Python is not installed or not in your PATH.
echo.
echo  To fix this:
echo    1. Go to  https://www.python.org/downloads/
echo    2. Download the latest Python installer (e.g. python-3.x.x-amd64.exe)
echo    3. Run the installer
echo    4. IMPORTANT: Check "Add Python to PATH" on the first screen
echo    5. IMPORTANT: Choose "Install for all users" for best results
echo    6. Re-run this script
echo.
echo  NOTE: Do NOT install Python from the Microsoft Store.
echo        The Microsoft Store version is sandboxed and will
echo        cause all Kindle key extractions to fail.
echo.
pause
goto :eof

:store_python_warning
echo.
echo [ERROR] Microsoft Store Python Detected - Script Will Fail
echo ======================================================================
echo.
echo  Python found at: %STUB_PYTHON%
echo.
echo  The Microsoft Store version of Python runs inside a sandbox that
echo  prevents it from accessing Kindle.exe memory. This causes:
echo    - ALL book extractions to fail (STATUS_ACCESS_VIOLATION)
echo    - Temp folder cleanup to fail (locked file handles)
echo    - Log files saved to unexpected hidden locations
echo.
echo  HOW TO FIX:
echo    1. Open Settings - Apps
echo    2. Search for "Python" and uninstall the Microsoft Store version
echo    3. Go to  https://www.python.org/downloads/
echo    4. Download the latest Python installer
echo    5. Run the installer
echo    6. CHECK "Add Python to PATH" on the first screen
echo    7. Choose "Install for all users" for best results
echo    8. Re-run this script
echo.
echo ======================================================================
echo.
pause
goto :eof

:run_script

REM =========================================================================
REM ONE-TIME DESKTOP SHORTCUT OFFER
REM =========================================================================
set "SHORTCUT_PATH=%USERPROFILE%\Desktop\Kindle Key Finder.lnk"
set "NO_SHORTCUT_MARKER=%~dp0.no_shortcut"

if exist "%NO_SHORTCUT_MARKER%" goto :skip_shortcut
if exist "%SHORTCUT_PATH%" goto :skip_shortcut

echo.
echo ========================================================
echo  Create Desktop Shortcut for Kindle Key Finder?
echo ========================================================
echo.
echo  A shortcut on your Desktop lets you pin this app to
echo  the Windows Taskbar for one-click access.
echo.
echo  (Auto-selects NO in 15 seconds)
echo.
choice /C YN /M "Create Desktop shortcut?" /T 15 /D N
if errorlevel 2 (
    echo.
    echo [*] Shortcut skipped - won't ask again.
    echo     To create one manually, delete: .no_shortcut
    type nul > "%NO_SHORTCUT_MARKER%"
    echo.
    echo  Press any key to continue, or script will auto-continue in 15 seconds...
    timeout /t 15 >nul
    goto :skip_shortcut
)

echo.
echo [*] Creating Desktop shortcut...
set "PS_SCRIPT=%TEMP%\kkf_shortcut_%RANDOM%.ps1"
(
    echo $WS = New-Object -COM WScript.Shell
    echo $SC = $WS.CreateShortcut^('%SHORTCUT_PATH%'^)
    echo $SC.TargetPath = 'C:\Windows\System32\cmd.exe'
    echo $SC.Arguments = '/c "%~dp0Run_keyfinder_admin.vbs"'
    echo $SC.WorkingDirectory = '%~dp0'
    echo $SC.Description = 'Kindle Key Finder'
    echo $SC.IconLocation = '%~dp0code\Logo.ico,0'
    echo $SC.Save^(^)
) > "%PS_SCRIPT%"
powershell -NoProfile -ExecutionPolicy Bypass -File "%PS_SCRIPT%"
set "SC_RESULT=%errorlevel%"
del "%PS_SCRIPT%" >nul 2>&1
if "%SC_RESULT%"=="0" (
    echo [OK] Shortcut created on Desktop!
    echo      You can now pin it to the Taskbar by right-clicking it.
) else (
    echo [!] Shortcut could not be created (PowerShell error %SC_RESULT%)
    echo     This does not affect the script - continuing normally.
    echo     You can create the shortcut manually later if needed.
)
echo  Press any key to continue, or script will auto-continue in 15 seconds...
timeout /t 15 >nul
echo.

:skip_shortcut

REM Check for script
set "SCRIPT_PATH=%~dp0key_finder.py"
if not exist "%SCRIPT_PATH%" (
    echo [ERROR] Script not found: "%SCRIPT_PATH%"
    pause
    goto :eof
)

REM =========================================================================
REM ONE-TIME WINDOW MODE PREFERENCE
REM =========================================================================
set "WINDOW_MODE_FILE=%~dp0.window_mode"
set "WINDOW_MODE=/NORMAL"

if exist "%WINDOW_MODE_FILE%" (
    set /p WINDOW_MODE=<"%WINDOW_MODE_FILE%"
    goto :launch_script
)

echo.
echo ========================================================
echo  Window Size Preference  (One-Time Setup)
echo ========================================================
echo.
echo  Would you like Kindle Key Finder to launch maximized
echo  (full screen) or in a normal-sized window?
echo.
echo  NOTE: This is a ONE-TIME question - your answer will
echo  be saved. To change it later, delete: .window_mode
echo.
echo  (Auto-selects NORMAL in 15 seconds)
echo.
choice /C YN /M "Launch maximized (full screen)?" /T 15 /D N
if errorlevel 2 (
    echo /NORMAL>"%WINDOW_MODE_FILE%"
    set "WINDOW_MODE=/NORMAL"
    echo.
    echo [*] Normal window saved as preference.
) else (
    echo /MAX>"%WINDOW_MODE_FILE%"
    set "WINDOW_MODE=/MAX"
    echo.
    echo [OK] Maximized window saved as preference.
)
echo.
echo  Press any key to continue, or script will auto-continue in 15 seconds...
timeout /t 15 >nul
echo.

:launch_script

REM Create temporary wrapper script to avoid quote nesting issues
REM Use the absolute PYTHON_EXE path found during detection so Windows
REM cannot intercept the launch via the WindowsApps stub in PATH.
set "WRAPPER=%TEMP%\keyfinder_wrapper.bat"
(
    echo @echo off
    echo cd /d "%~dp0"
    echo "%PYTHON_EXE%" "%SCRIPT_PATH%"
) > "%WRAPPER%"

REM Launch wrapper using saved window mode preference
start "Kindle Key Finder" %WINDOW_MODE% cmd /k "call "%WRAPPER%" & del /f /q "%WRAPPER%" 2>nul"
