@echo off
chcp 65001 > nul
setlocal enabledelayedexpansion

echo.
echo ================================================
echo  MoveStudio One-Click Install
echo  AI Video Studio - Server Auto Setup
echo ================================================
echo.

set "INSTALL_DIR=%USERPROFILE%\MoveStudio"
set "BASE_URL=https://web-azure-kappa-89.vercel.app"
set "ZIP_URL=%BASE_URL%/downloads/MoveStudio_Servers.zip"
set "ZIP_FILE=%TEMP%\MoveStudio_Servers.zip"

:: 1. Create install folder
echo [1/4] Creating install folder...
echo   Path: %INSTALL_DIR%
mkdir "%INSTALL_DIR%" 2>nul
echo.

:: 2. Download server files
echo [2/4] Downloading server files...
echo   URL: %ZIP_URL%
powershell -NoProfile -ExecutionPolicy Bypass -Command "[Net.ServicePointManager]::SecurityProtocol='Tls12,Tls13'; try { (New-Object Net.WebClient).DownloadFile('%ZIP_URL%','%ZIP_FILE%'); Write-Host '  [OK] Download complete' } catch { Write-Host ('  [ERROR] '+$_.Exception.Message); exit 1 }"

if not exist "%ZIP_FILE%" (
    echo.
    echo [ERROR] Download failed.
    echo   Check your internet connection and try again.
    echo.
    pause
    exit /b 1
)
echo.

:: 3. Extract zip
echo [3/4] Extracting files to %INSTALL_DIR%...
powershell -NoProfile -ExecutionPolicy Bypass -Command "try { Expand-Archive -Path '%ZIP_FILE%' -DestinationPath '%INSTALL_DIR%' -Force; Write-Host '  [OK] Extraction complete' } catch { Write-Host ('  [ERROR] '+$_.Exception.Message); exit 1 }"
set "_EXTRACT_ERR=!errorlevel!"
del "%ZIP_FILE%" > nul 2>&1

:: Check extraction errorlevel first, then verify key file exists
if !_EXTRACT_ERR! neq 0 (
    echo.
    echo [ERROR] Extraction failed (errorlevel !_EXTRACT_ERR!).
    echo   Please check your internet connection and try again.
    echo.
    pause
    exit /b 1
)
if not exist "%INSTALL_DIR%\setup_install.bat" (
    echo.
    echo [ERROR] setup_install.bat not found after extraction in:
    echo   %INSTALL_DIR%
    echo.
    pause
    exit /b 1
)
echo.

:: 4. Run initial setup
echo [4/4] Running initial setup...
echo ------------------------------------------------
echo.
:: Use cmd /c to isolate the child process — if setup_install.bat (or start_all.bat)
:: calls bare "exit" it only kills the child cmd.exe, not this installer window.
cmd /c ""%INSTALL_DIR%\setup_install.bat""

echo.
echo ================================================
echo  Install process finished.
echo  You can close this window.
echo ================================================
echo.
pause
