@echo off
:: ─── Oom helper — one-double-click installer (Windows) ────────────────────
:: What this does (≈60 seconds first run, ~5 sec subsequent runs, no admin):
::   1. Installs Anthropic Claude Code CLI (native installer, user-scope ~/.local/bin)
::   2. Installs Python 3.12 user-scope if missing (via winget)
::   3. Locates the `tcs-chrome-extension` repo OR clones it via `gh` if missing
::   4. Installs Miras's Python dependencies (pip --user)
::   5. Registers a logon scheduled task so MIRAS starts on every login
::   6. Starts Miras right now (`python -m data_sources.miras.server`, port 8765)
::   7. Reopens https://oom-v13.pages.dev in the default browser
::
:: After this runs once, the user never opens a terminal again. Miras
:: auto-starts on login. The browser auto-detects localhost:8765.
:: No admin elevation needed — every step is user-scope.

setlocal ENABLEDELAYEDEXPANSION
title Oom helper installer

echo.
echo ════════════════════════════════════════════════════════════════
echo   Oom helper installer
echo   ~30 seconds. No admin. No terminal usage after this.
echo ════════════════════════════════════════════════════════════════
echo.

set "OOM_DIR=%LOCALAPPDATA%\Oom"
if not exist "%OOM_DIR%" mkdir "%OOM_DIR%"

:: ── 1. Claude Code (native installer, no Node.js needed) ─────────
where claude >NUL 2>&1
if %ERRORLEVEL% EQU 0 (
    echo [1/5] Claude Code already installed.
) else (
    echo [1/5] Installing Claude Code (Anthropic native installer)...
    powershell -NoProfile -ExecutionPolicy Bypass -Command "iwr https://claude.ai/install.ps1 -UseBasicParsing | iex" || (
        echo   ! Anthropic installer failed. Retrying via npm fallback.
        where npm >NUL 2>&1 || (
            echo   ! npm not found either. Installing Node.js via winget...
            winget install -e --id OpenJS.NodeJS --silent --accept-source-agreements --accept-package-agreements
        )
        call npm i -g @anthropic-ai/claude-code
    )
)

:: Add ~/.local/bin to PATH for this session (Anthropic installer puts claude there)
set "PATH=%USERPROFILE%\.local\bin;%PATH%"

:: ── 2. Python 3.12 (only if missing) ─────────────────────────────
where py >NUL 2>&1 || where python >NUL 2>&1
if %ERRORLEVEL% EQU 0 (
    echo [2/5] Python already installed.
) else (
    echo [2/5] Installing Python 3.12 (user-scope, no admin)...
    winget install -e --id Python.Python.3.12 --silent --scope user --accept-source-agreements --accept-package-agreements
    set "PATH=%LOCALAPPDATA%\Programs\Python\Python312;%LOCALAPPDATA%\Programs\Python\Python312\Scripts;%PATH%"
)

:: ── 2b. Bake Oom credentials (Cloudflare + GitHub tokens) if bundled ──
:: The operator drops oom-secrets.json next to this installer (gitignored, never committed).
:: This lets Publish + team-sync work with ZERO tokens for the teammate to create or paste.
echo [2b/9] Baking Oom credentials (if bundled)...
python "%~dp0bake_keys.py" 2>NUL || py -3 "%~dp0bake_keys.py" 2>NUL

:: ── 3. Locate or clone the tcs-chrome-extension repo ─────────────
:: Miras only runs from inside this repo (it auto-bootstraps from the
:: repo's git config + .githooks). If the user already has it, find it;
:: otherwise clone to %USERPROFILE%\Improvado\tcs-chrome-extension.
echo [3/7] Locating tcs-chrome-extension repo...
set "REPO_DIR="

:: Try common locations + check `git config --get` for any clone the user uses
for %%P in (
    "%USERPROFILE%\Improvado\tcs-chrome-extension"
    "%USERPROFILE%\code\tcs-chrome-extension"
    "%USERPROFILE%\source\repos\tcs-chrome-extension"
    "%USERPROFILE%\Desktop\Organization\Improvado\tcs-chrome-extension"
    "%USERPROFILE%\Documents\tcs-chrome-extension"
) do (
    if exist %%P\.git\config (
        findstr /C:"tekliner/tcs-chrome-extension" %%P\.git\config >NUL 2>&1
        if not errorlevel 1 (
            set "REPO_DIR=%%~P"
            goto :repo_found
        )
    )
)

:: Not found — clone via gh CLI (auto-uses user's GitHub auth, no PAT paste)
echo   Repo not found locally. Cloning to %USERPROFILE%\Improvado\tcs-chrome-extension ...
where gh >NUL 2>&1 || winget install -e --id GitHub.cli --silent --accept-source-agreements --accept-package-agreements
if not exist "%USERPROFILE%\Improvado" mkdir "%USERPROFILE%\Improvado"
gh repo clone tekliner/tcs-chrome-extension "%USERPROFILE%\Improvado\tcs-chrome-extension" -- -b oom-live 2>NUL || (
    echo   ! gh clone failed - falling back to https clone
    git clone -b oom-live https://github.com/tekliner/tcs-chrome-extension.git "%USERPROFILE%\Improvado\tcs-chrome-extension"
)
set "REPO_DIR=%USERPROFILE%\Improvado\tcs-chrome-extension"
:repo_found
echo   Repo: %REPO_DIR%

:: ── 3b. GitHub sign-in (so self-build can push branches + open PRs) ──────────
echo [3b/9] Checking GitHub sign-in (needed for self-build to open PRs)...
where gh >NUL 2>&1 || winget install -e --id GitHub.cli --silent --accept-source-agreements --accept-package-agreements
gh auth status >NUL 2>&1 && (
    echo   GitHub already signed in.
) || (
    echo   Not signed in. Opening one-time GitHub sign-in...
    gh auth login -w -h github.com -p https -s repo 2>NUL || echo   ! Sign-in skipped. Self-build will still work, but commit locally without a PR until you run: gh auth login
)

:: ── 4. Miras Python dependencies ─────────────────────────────────
echo [4/7] Installing Miras Python dependencies...
pushd "%REPO_DIR%"
if exist data_sources\miras\server\requirements.txt (
    python -m pip install --user --quiet -r data_sources\miras\server\requirements.txt
) else if exist requirements.txt (
    python -m pip install --user --quiet -r requirements.txt
) else (
    :: Minimal set if no requirements file: just what __main__.py imports
    python -m pip install --user --quiet python-dotenv httpx flask
)
popd

:: ── 5. Logon-triggered scheduled task → MIRAS (no admin) ─────────
echo [5/7] Registering Miras auto-start on login...
set "TASK_CMD=cmd /c cd /d \"%REPO_DIR%\" && pythonw.exe -m data_sources.miras.server"
schtasks /Query /TN "Miras" >NUL 2>&1 && schtasks /Delete /TN "Miras" /F >NUL 2>&1
schtasks /Create /SC ONLOGON /TN "Miras" /TR "%TASK_CMD%" /RL LIMITED /F >NUL || (
    echo   ! schtasks registration failed. Falling back to Startup folder.
    echo Set s = CreateObject("WScript.Shell"^^) > "%TEMP%\miras_shortcut.vbs"
    echo Set lnk = s.CreateShortcut("%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\Miras.lnk"^^) >> "%TEMP%\miras_shortcut.vbs"
    echo lnk.TargetPath = "pythonw.exe" >> "%TEMP%\miras_shortcut.vbs"
    echo lnk.Arguments = "-m data_sources.miras.server" >> "%TEMP%\miras_shortcut.vbs"
    echo lnk.WorkingDirectory = "%REPO_DIR%" >> "%TEMP%\miras_shortcut.vbs"
    echo lnk.Save >> "%TEMP%\miras_shortcut.vbs"
    cscript //nologo "%TEMP%\miras_shortcut.vbs"
    del "%TEMP%\miras_shortcut.vbs"
)

:: ── 5b. Logon-triggered scheduled task → OOM-BROKER (no admin) ───
:: Loopback credential broker for the Oom v13 SPA. Standalone sidecar — keeps
:: Notion/GitHub PAT handling out of the shared Miras server so teammates not
:: running Oom never load this code path. Port 8790 (outside Miras's
:: 8765-8775 discovery range so the SPA's two backends never collide).
echo [5b/7] Registering Oom-Broker auto-start on login...
set "OOM_BROKER_DIR=%REPO_DIR%\algorithms\revenue_div\marketing_dpt\01_projects\content_and_creative\oom"
set "BROKER_TASK_CMD=cmd /c cd /d \"%OOM_BROKER_DIR%\" && pythonw.exe -m oom_runner.broker"
schtasks /Query /TN "OomBroker" >NUL 2>&1 && schtasks /Delete /TN "OomBroker" /F >NUL 2>&1
schtasks /Create /SC ONLOGON /TN "OomBroker" /TR "%BROKER_TASK_CMD%" /RL LIMITED /F >NUL || (
    echo   ! schtasks registration failed. Falling back to Startup folder.
    echo Set s = CreateObject("WScript.Shell"^^) > "%TEMP%\oombroker_shortcut.vbs"
    echo Set lnk = s.CreateShortcut("%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\OomBroker.lnk"^^) >> "%TEMP%\oombroker_shortcut.vbs"
    echo lnk.TargetPath = "pythonw.exe" >> "%TEMP%\oombroker_shortcut.vbs"
    echo lnk.Arguments = "-m oom_runner.broker" >> "%TEMP%\oombroker_shortcut.vbs"
    echo lnk.WorkingDirectory = "%OOM_BROKER_DIR%" >> "%TEMP%\oombroker_shortcut.vbs"
    echo lnk.Save >> "%TEMP%\oombroker_shortcut.vbs"
    cscript //nologo "%TEMP%\oombroker_shortcut.vbs"
    del "%TEMP%\oombroker_shortcut.vbs"
)

:: ── 5c. Logon-triggered scheduled task → OOM-RUNNER (self-build serve) ───────
:: Local HTTP server on 127.0.0.1:8791 that the Oom v13 "Self-build" tab calls to
:: run the user's OWN Claude Code against their OWN clone. Compute + cost stay on
:: this PC. Port 8791 sits outside Miras's 8765-8775 scan and the broker's 8790.
echo [5c/9] Registering Oom-Runner (self-build) auto-start on login...
set "RUNNER_TASK_CMD=cmd /c cd /d \"%OOM_BROKER_DIR%\" && pythonw.exe -m oom_runner.runner serve --repo \"%REPO_DIR%\" --port 8791"
schtasks /Query /TN "OomRunner" >NUL 2>&1 && schtasks /Delete /TN "OomRunner" /F >NUL 2>&1
schtasks /Create /SC ONLOGON /TN "OomRunner" /TR "%RUNNER_TASK_CMD%" /RL LIMITED /F >NUL || (
    echo   ! schtasks registration failed. Falling back to Startup folder.
    echo Set s = CreateObject("WScript.Shell"^^) > "%TEMP%\oomrunner_shortcut.vbs"
    echo Set lnk = s.CreateShortcut("%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\OomRunner.lnk"^^) >> "%TEMP%\oomrunner_shortcut.vbs"
    echo lnk.TargetPath = "pythonw.exe" >> "%TEMP%\oomrunner_shortcut.vbs"
    echo lnk.Arguments = "-m oom_runner.runner serve --repo ""%REPO_DIR%"" --port 8791" >> "%TEMP%\oomrunner_shortcut.vbs"
    echo lnk.WorkingDirectory = "%OOM_BROKER_DIR%" >> "%TEMP%\oomrunner_shortcut.vbs"
    echo lnk.Save >> "%TEMP%\oomrunner_shortcut.vbs"
    cscript //nologo "%TEMP%\oomrunner_shortcut.vbs"
    del "%TEMP%\oomrunner_shortcut.vbs"
)

:: ── 6. Start Miras right now ─────────────────────────────────────
echo [6/7] Starting Miras (port 8765)...
pushd "%REPO_DIR%"
start "" /B pythonw.exe -m data_sources.miras.server
popd
timeout /t 3 /nobreak >NUL

:: ── 6b. Start Oom-Broker right now ───────────────────────────────
echo [6b/7] Starting Oom-Broker (port 8790)...
pushd "%OOM_BROKER_DIR%"
start "" /B pythonw.exe -m oom_runner.broker
popd
timeout /t 2 /nobreak >NUL

:: ── 6c. Start Oom-Runner self-build server right now ─────────────
echo [6c/9] Starting Oom-Runner self-build server (port 8791)...
pushd "%OOM_BROKER_DIR%"
start "" /B pythonw.exe -m oom_runner.runner serve --repo "%REPO_DIR%" --port 8791
popd
timeout /t 2 /nobreak >NUL

:: ── 7. Register tcs:// URL protocol (HKCU, no admin) ──────────────
:: Added: session 1458297f-1eb7-453e-999c-ac4d86045e66 — lets the SPA fire
:: `<a href="tcs://start">` to launch Miras headlessly from a single click,
:: without the user typing anything. wscript.exe + miras_launcher.vbs is the
:: same handler the scheduled task uses. The "%%1" placeholder passes the
:: full URL so future sub-commands like `tcs://restart` are possible.
echo [7/8] Registering tcs:// URL protocol...
set "VBS_PATH=%USERPROFILE%\.miras\miras_launcher.vbs"
set "CMD_VALUE=wscript.exe //B //Nologo \"%VBS_PATH%\" \"%%1\""
reg add "HKCU\Software\Classes\tcs" /ve /d "URL:TCS Protocol" /f >NUL
reg add "HKCU\Software\Classes\tcs" /v "URL Protocol" /d "" /f >NUL
reg add "HKCU\Software\Classes\tcs\DefaultIcon" /ve /d "wscript.exe,1" /f >NUL
reg add "HKCU\Software\Classes\tcs\shell\open\command" /ve /d "%CMD_VALUE%" /f >NUL
echo   tcs:// → wscript.exe %VBS_PATH%

:: ── 8. Open Oom in the browser ───────────────────────────────────
echo [8/8] Opening Oom in your browser...
start "" "https://oom-v13.pages.dev?installed=1"

echo.
echo ════════════════════════════════════════════════════════════════
echo   Done. The browser should be opening with Oom v13 now.
echo   Miras       is running on http://localhost:8765 (shared agent server)
echo   Oom-Broker  is running on http://localhost:8790 (Oom credential proxy)
echo   Oom-Runner  is running on http://localhost:8791 (self-build via your Claude Code)
echo   All three auto-start every time you log in. No more terminal.
echo.
echo   Self-build: open Oom, go to the Self-build tab. It should say
echo   "Connected to your Claude Code". Type a change, click "Build it now",
echo   and your own Claude Code makes it + opens a PR. Runs on THIS PC.
echo.
echo   Repo location: %REPO_DIR%
echo.
echo   On first sign-in Oom asks for an OAuth App Client ID (30 seconds,
echo   in-app wizard). After that one-time step, every user clicks one button.
echo.
echo   Optional: Notion one-click sign-in: register a public integration at
echo             notion.so/profile/integrations, set NOTION_OAUTH_CLIENT_ID
echo             + NOTION_OAUTH_CLIENT_SECRET in the broker env. Whitelist:
echo             http://localhost:8790/api/oom/notion/oauth/callback
echo ════════════════════════════════════════════════════════════════
echo.
pause
exit /b 0
