@echo off
chcp 65001 >nul
title Humapi Plugin Installer for ZiZi Donghua
setlocal EnableDelayedExpansion

set "BASE=https://humapi.top/downloads"
set "IMG=hb-image-plugin.zip"
set "VID=hb-video-plugin.zip"
set "WORK=%TEMP%\humapi-plugins"

echo ============================================
echo   Humapi Plugin Installer
echo   for ZiZi Donghua
echo ============================================
echo.

if not exist "%WORK%" mkdir "%WORK%"

echo [1/3] Downloading plugins from %BASE% ...
powershell -NoProfile -Command "Invoke-WebRequest -Uri '%BASE%/%IMG%' -OutFile '%WORK%\%IMG%' -UseBasicParsing"
if errorlevel 1 ( echo [ERR] download failed & goto :manual )
powershell -NoProfile -Command "Invoke-WebRequest -Uri '%BASE%/%VID%' -OutFile '%WORK%\%VID%' -UseBasicParsing"
if errorlevel 1 ( echo [ERR] download failed & goto :manual )

echo [2/3] Extracting ...
powershell -NoProfile -Command "Expand-Archive -Path '%WORK%\%IMG%' -DestinationPath '%WORK%\img' -Force"
powershell -NoProfile -Command "Expand-Archive -Path '%WORK%\%VID%' -DestinationPath '%WORK%\vid' -Force"

echo [3/3] Locating ZiZi Donghua install directory ...
set "TARGET="
for %%D in ("%ProgramFiles%" "%LOCALAPPDATA%" "%USERPROFILE%\Desktop" "%USERPROFILE%\Downloads") do (
  if not defined TARGET (
    for /f "delims=" %%P in ('powershell -NoProfile -Command "Get-ChildItem -Path '%%~D' -Recurse -Directory -Filter '_internal' -ErrorAction SilentlyContinue | Select-Object -First 1 | ForEach-Object { $_.Parent.FullName }"') do set "TARGET=%%P"
  )
)
REM also check if this bat sits inside the install folder
if not defined TARGET (
  if exist "%~dp0_internal\plugins" set "TARGET=%~dp0"
)

if defined TARGET (
  echo Found: !TARGET!
  if not exist "!TARGET!_internal\plugins\images_plugins" mkdir "!TARGET!_internal\plugins\images_plugins"
  if not exist "!TARGET!_internal\plugins\video_plugins" mkdir "!TARGET!_internal\plugins\video_plugins"
  xcopy /E /Y /I "%WORK%\img\hb-image" "!TARGET!_internal\plugins\images_plugins\hb-image" >nul
  xcopy /E /Y /I "%WORK%\vid\hb-video" "!TARGET!_internal\plugins\video_plugins\hb-video" >nul
  echo.
  echo [OK] Plugins installed. Restart ZiZi Donghua to use them.
  goto :end
)

:manual
echo.
echo [!] Could not auto-detect ZiZi Donghua install directory.
echo     Plugins were extracted to: %WORK%
echo     Please copy these folders manually into:
echo       ZiZi Donghua\_internal\plugins\
echo        - img\hb-image  -> images_plugins\hb-image
echo        - vid\hb-video  -> video_plugins\hb-video
echo     Then restart ZiZi Donghua.

:end
echo.
pause
