@echo off
setlocal enabledelayedexpansion
title CargoMind - Outlook Add-in Setup
color 0F

set "CM_DIR=%LOCALAPPDATA%\CargoMind"
set "IDS_FILE=!CM_DIR!\title-ids.txt"
set "INSTALLED_COUNT=0"
set "TITLE_ID="
set "GOT_401=0"

echo.
echo  =============================================
echo   CargoMind - Outlook Add-in Setup
echo  =============================================
echo.

:: -----------------------------------------------
:: Step 1: Check for Node.js
:: -----------------------------------------------
echo  [1/4] Checking for Node.js...

where node >nul 2>&1
if !errorlevel! equ 0 (
    for /f "tokens=*" %%v in ('node --version 2^>nul') do set "NODE_VER=%%v"
    echo        Found Node.js !NODE_VER!
    goto :node_ready
)

echo        Node.js not found. Installing...
echo.

:: Try winget first (built into Windows 11, available on most Windows 10)
where winget >nul 2>&1
if !errorlevel! equ 0 (
    echo        Installing via Windows Package Manager...
    echo.
    winget install OpenJS.NodeJS.LTS --accept-package-agreements --accept-source-agreements
    if !errorlevel! equ 0 (
        echo.
        echo        Node.js installed successfully.
        set "PATH=!PATH!;%ProgramFiles%\nodejs;%APPDATA%\npm"
        goto :check_node_again
    )
    echo        winget install failed, trying direct download...
)

:: Fallback: download Node.js MSI directly
echo        Downloading Node.js LTS installer...
set "NODE_MSI=%TEMP%\nodejs-setup.msi"
curl -L -s -o "!NODE_MSI!" "https://nodejs.org/dist/v22.14.0/node-v22.14.0-x64.msi"
if !errorlevel! neq 0 (
    echo.
    echo  ERROR: Failed to download Node.js.
    echo  Please install manually from https://nodejs.org
    echo.
    pause
    exit /b 1
)

echo        Running Node.js installer (may request admin permission)...
msiexec /i "!NODE_MSI!" /qb
del "!NODE_MSI!" 2>nul

set "PATH=!PATH!;%ProgramFiles%\nodejs;%APPDATA%\npm"

:check_node_again
where node >nul 2>&1
if !errorlevel! neq 0 (
    echo.
    echo  ERROR: Node.js still not found after installation.
    echo  Please close this window, install Node.js from https://nodejs.org
    echo  and run this installer again.
    echo.
    pause
    exit /b 1
)

for /f "tokens=*" %%v in ('node --version 2^>nul') do set "NODE_VER=%%v"
echo        Node.js !NODE_VER! ready.

:node_ready

:: -----------------------------------------------
:: Step 2: Download manifest
:: -----------------------------------------------
echo.
echo  [2/4] Downloading add-in manifest...

set "INSTALL_DIR=%TEMP%\cargomind-outlook-install"
if not exist "!INSTALL_DIR!" mkdir "!INSTALL_DIR!"
if not exist "!CM_DIR!" mkdir "!CM_DIR!"

curl -s -o "!INSTALL_DIR!\cargomind-manifest.xml" "https://cargomind-enhance.nextgen-bpo.com/app/outlook-ext/cargomind-manifest.xml"
if !errorlevel! neq 0 (
    echo.
    echo  ERROR: Failed to download manifest from server.
    echo  Please check your internet connection and try again.
    echo.
    pause
    exit /b 1
)
echo        Manifest downloaded.

:: Migrate old single title-id.txt to multi-account format
if exist "!CM_DIR!\title-id.txt" (
    if not exist "!IDS_FILE!" (
        copy "!CM_DIR!\title-id.txt" "!IDS_FILE!" >nul
    )
    del "!CM_DIR!\title-id.txt" 2>nul
)

cd /d "!INSTALL_DIR!"

:: -----------------------------------------------
:: Step 3: Detect Outlook accounts
:: -----------------------------------------------
echo.
echo  [3/3] Installing add-in...
echo.

set "TOTAL_ACCOUNTS=0"

for /f "tokens=1,2,3,4" %%a in ('reg query "HKCU\Software\Microsoft\Office\16.0\Outlook\Profiles" /s /v "Account Name" 2^>nul ^| findstr "@"') do (
    set /a TOTAL_ACCOUNTS+=1
    set "ACCOUNT_!TOTAL_ACCOUNTS!=%%d"
)

if !TOTAL_ACCOUNTS! leq 1 goto :run_install

:pick_account
echo  Outlook account(s):
echo.
for /l %%i in (1,1,!TOTAL_ACCOUNTS!) do (
    echo    [%%i] !ACCOUNT_%%i!
)
echo.
set "PICK="
set /p "PICK=  Select account number: "

call set "CUR_EMAIL=%%ACCOUNT_!PICK!%%"
if not defined CUR_EMAIL (
    echo  Invalid selection.
    goto :pick_account
)

echo.
echo  Selected: !CUR_EMAIL!

:: Check if personal Microsoft account (cannot use atk install)
echo !CUR_EMAIL! | findstr /i "@outlook.com @hotmail.com @live.com @msn.com" >nul 2>&1
if !errorlevel! neq 0 goto :work_account

echo.
echo  =============================================
echo   Personal Microsoft Account Detected
echo  =============================================
echo   !CUR_EMAIL! is a personal account.
echo   Automatic installation is only supported
echo   for work/school M365 accounts.
echo.
echo   To install on this account manually:
echo   1. Open https://aka.ms/olksideload
echo   2. Upload the manifest XML file from:
echo      !CM_DIR!\cargomind-manifest.xml
echo  =============================================
:: Copy manifest to CargoMind dir for manual upload
if not exist "!CM_DIR!" mkdir "!CM_DIR!"
copy "!INSTALL_DIR!\cargomind-manifest.xml" "!CM_DIR!\cargomind-manifest.xml" >nul 2>&1
goto :done

:work_account
:: Clear cached auth so atk re-authenticates for the chosen account
echo  Clearing cached session...
call npx -y -p @microsoft/m365agentstoolkit-cli atk auth logout >nul 2>&1

:: Delete atk/teamsfx token cache to force fresh login
if exist "%USERPROFILE%\.fx\account" (
    rmdir /s /q "%USERPROFILE%\.fx\account" 2>nul
)

echo  A browser will open - please sign in as: !CUR_EMAIL!
echo.

:run_install
set "TITLE_ID="
set "GOT_401=0"
set "ATK_OUT=%TEMP%\cargomind-atk-output.txt"
call npx -y -p @microsoft/m365agentstoolkit-cli atk install --xml-path cargomind-manifest.xml > "!ATK_OUT!" 2>&1
type "!ATK_OUT!"
for /f "tokens=2 delims= " %%t in ('findstr "TitleId:" "!ATK_OUT!" 2^>nul') do set "TITLE_ID=%%t"
findstr /i "401" "!ATK_OUT!" >nul 2>&1 && set "GOT_401=1"
del "!ATK_OUT!" 2>nul

if defined TITLE_ID echo !TITLE_ID!>>"!IDS_FILE!"

:done
cd /d "%TEMP%"
rmdir /s /q "!INSTALL_DIR!" 2>nul

echo.
if defined TITLE_ID goto :msg_success
if !GOT_401! equ 1 goto :msg_401
goto :msg_failed

:msg_success
echo  =============================================
echo   Installation Complete!
echo  =============================================
echo   TitleId: !TITLE_ID!
echo   Please restart Outlook to see the add-in.
echo   Run installer again for other accounts.
echo  =============================================
goto :msg_end

:msg_401
echo  =============================================
echo   Installation Failed (401 Unauthorized)
echo  =============================================
echo   This account does not support automatic
echo   add-in installation. Personal Microsoft
echo   accounts (outlook.com, hotmail.com, etc.)
echo   require manual installation instead:
echo.
echo   1. Open https://aka.ms/olksideload
echo   2. Upload the manifest XML file
echo.
echo   Work/school (M365) accounts can use this
echo   installer.
echo  =============================================
goto :msg_end

:msg_failed
echo  =============================================
echo   Installation Failed
echo  =============================================
echo   Please try running the installer again.
echo  =============================================

:msg_end
echo.

pause
exit /b 0
