@echo off
rem =====================================================================
rem SMF2290 Pensum - Start.bat
rem Universal launcher for Windows: setter opp alt og starter studie-appen.
rem Fungerer selv pa et helt nytt Windows-system (10/11).
rem =====================================================================

setlocal enabledelayedexpansion
title SMF2290 Pensum
color 0F
cd /d "%~dp0"

set "SCRIPT_DIR=%~dp0"
set "APP_DIR=%SCRIPT_DIR%app"
set "VENDOR_DIR=%APP_DIR%\vendor"
set "PS_SERVER=%SCRIPT_DIR%server.ps1"
set DEFAULT_PORT=8765
set PORT=%DEFAULT_PORT%

echo.
echo   SMF . 2290    Etikk, baerekraft og samfunnsansvar
echo   Pensum        studie-app . v1.0
echo.

rem --- Sanity check ----------------------------------------------------
if not exist "%APP_DIR%\index.html" (
  echo   [x] Fant ikke %APP_DIR%\index.html
  echo       Kjor Start.bat fra SMF-prosjektmappen.
  pause
  exit /b 1
)

rem --- Detect server runtime -------------------------------------------
set "SERVER_CMD="
set "SERVER_NAME="

rem 1. Python via py launcher (best paa Windows)
py -3 --version >nul 2>&1
if not errorlevel 1 (
  for /f "tokens=2" %%v in ('py -3 --version 2^>^&1') do set "SERVER_NAME=Python %%v"
  set "SERVER_CMD=py -3 -m http.server %PORT% --bind 127.0.0.1"
  goto :have_server
)

rem 2. python (could be Win Store alias - check it actually works)
python --version >nul 2>&1
if not errorlevel 1 (
  python --version 2>&1 | findstr /R /C:"^Python 3" >nul
  if not errorlevel 1 (
    for /f "tokens=2" %%v in ('python --version 2^>^&1') do set "SERVER_NAME=Python %%v"
    set "SERVER_CMD=python -m http.server %PORT% --bind 127.0.0.1"
    goto :have_server
  )
)

rem 3. Node.js
where node >nul 2>&1
if not errorlevel 1 (
  for /f "delims=" %%v in ('node --version 2^>^&1') do set "SERVER_NAME=Node.js %%v"
  set "SERVER_CMD=npx --yes http-server -p %PORT% -a 127.0.0.1 --silent"
  goto :have_server
)

rem 4. PowerShell HttpListener (innebygd i Windows)
where powershell >nul 2>&1
if not errorlevel 1 (
  if exist "%PS_SERVER%" (
    set "SERVER_NAME=PowerShell HttpListener"
    set "SERVER_CMD=powershell -NoProfile -ExecutionPolicy Bypass -File ""%PS_SERVER%"" -Port %PORT% -Root ""%APP_DIR%"""
    echo   [!] Python/Node ikke funnet - bruker innebygd PowerShell-server
    goto :have_server
  )
)

rem --- No runtime found - try winget ----------------------------------
echo   [!] Ingen Python/Node funnet pa systemet.
echo.
where winget >nul 2>&1
if not errorlevel 1 (
  echo   [?] Vil du installere Python 3 via winget? [J/N]
  set /p "INSTALL_CHOICE="
  if /i "!INSTALL_CHOICE!"=="J" (
    echo   [.] Installerer Python 3.12 via winget ...
    winget install --id Python.Python.3.12 --silent --accept-package-agreements --accept-source-agreements
    if not errorlevel 1 (
      echo   [v] Python installert. Starter pa nytt ...
      timeout /t 3 >nul
      start "" cmd /c "%~f0"
      exit /b 0
    )
  )
)

echo.
echo   Installer en av disse manuelt:
echo     . Python 3:    https://www.python.org/downloads/
echo                    eller via Microsoft Store ^(sok etter "Python 3"^)
echo     . Node.js:     https://nodejs.org/
echo.
echo   Trykk en tast for a apne Microsoft Store ...
pause >nul
start ms-windows-store://search/?query=Python%%203
exit /b 1

:have_server
echo   [v] Server-runtime: %SERVER_NAME%

rem --- Verify marked.js ------------------------------------------------
if not exist "%VENDOR_DIR%\marked.min.js" (
  echo   [.] marked.min.js mangler - laster ned ...
  if not exist "%VENDOR_DIR%" mkdir "%VENDOR_DIR%"
  powershell -NoProfile -Command "try { Invoke-WebRequest -UseBasicParsing -Uri 'https://cdn.jsdelivr.net/npm/marked/marked.min.js' -OutFile '%VENDOR_DIR%\marked.min.js' } catch { exit 1 }"
  if not exist "%VENDOR_DIR%\marked.min.js" (
    echo   [x] Klarte ikke laste ned marked.js. Trenger internett ved forste kjoring.
    pause
    exit /b 1
  )
  echo   [v] marked.js lastet ned
) else (
  echo   [v] marked.js OK
)

rem --- Ensure app\notes is a real directory with current notes --------
rem  Git lagrer app/notes som en symlink. Pa Windows uten symlink-stotte
rem  materialiseres den som en STRAY TEKSTFIL (innhold: "../notes"), som
rem  bryter appen. Vi normaliserer alltid: fjern fil, lag mappe, kopier.
rem  ("if exist sti\" med etterfolgende backslash er sant kun for mapper.)
if exist "%APP_DIR%\notes" if not exist "%APP_DIR%\notes\" (
  echo   [.] Fjerner ugyldig notes-fil ^(git-symlink pa Windows^) ...
  del /f /q "%APP_DIR%\notes" >nul 2>&1
)
if not exist "%APP_DIR%\notes\" mkdir "%APP_DIR%\notes" >nul 2>&1
xcopy /Y /Q "%SCRIPT_DIR%notes\*.md" "%APP_DIR%\notes\" >nul 2>&1
if exist "%APP_DIR%\notes\fast-track.md" (
  echo   [v] Notes OK
) else (
  echo   [x] Klarte ikke kopiere notes/ fra "%SCRIPT_DIR%notes"
  echo       Sjekk at notes-mappen finnes i prosjektroten.
  pause
  exit /b 1
)

rem --- Find a free port -----------------------------------------------
:try_port
netstat -an | findstr ":%PORT% " | findstr "LISTENING" >nul
if not errorlevel 1 (
  echo   [!] Port %PORT% er opptatt - prover %PORT%+1
  set /a PORT=%PORT%+1
  if %PORT% gtr 8800 (
    echo   [x] Fant ingen ledig port. Lukk noen prosesser og prov igjen.
    pause
    exit /b 1
  )
  rem Recompute SERVER_CMD with new port
  set "SERVER_CMD=!SERVER_CMD:%DEFAULT_PORT%=%PORT%!"
  goto :try_port
)

rem --- Banner ----------------------------------------------------------
echo.
echo   +----------------------------------------------+
echo   ^|  SMF2290 . Pensum                            ^|
echo   ^|                                              ^|
echo   ^|  -^> http://localhost:%PORT%                       ^|
echo   ^|                                              ^|
echo   ^|  Trykk Ctrl+C for a stoppe                   ^|
echo   +----------------------------------------------+
echo.

rem --- Open browser after short delay (in detached process) ----------
start "" /min cmd /c "timeout /t 2 >nul & start http://localhost:%PORT%"

rem --- Start server ----------------------------------------------------
cd /d "%APP_DIR%"
%SERVER_CMD%
set "SERVER_EXIT=%errorlevel%"

rem --- Server stoppet: hold vinduet apent sa feil kan leses -----------
echo.
if not "%SERVER_EXIT%"=="0" (
  echo   [x] Serveren avsluttet med feilkode %SERVER_EXIT%.
  echo       Les meldingen over. Vanlige arsaker: porten var opptatt,
  echo       eller runtime ^(%SERVER_NAME%^) mangler rettigheter.
) else (
  echo   Serveren ble stoppet.
)
echo   Trykk en tast for a lukke vinduet ...
pause >nul

endlocal
