@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "ROOT=%~dp0"
if "%ROOT:~-1%"=="\" set "ROOT=%ROOT:~0,-1%"

set "CHAT_LOG=%~1"
if "%CHAT_LOG%"=="" (
  echo.
  echo Drag a WeChat export txt/html/json/zip or folder into this window.
  set /p "CHAT_LOG=Chat log path: "
)

set "CHAT_LOG=%CHAT_LOG:"=%"
if "%CHAT_LOG%"=="" (
  echo Canceled.
  pause
  exit /b 1
)

if not exist "%CHAT_LOG%" (
  echo.
  echo [ERROR] Path not found:
  echo   %CHAT_LOG%
  echo.
  echo Supported: .txt / .html / .json / .zip, or an export folder.
  pause
  exit /b 1
)

set "PYTHON_EXE="
if defined PET_PYTHON_EXE if exist "%PET_PYTHON_EXE%" set "PYTHON_EXE=%PET_PYTHON_EXE%"
if not defined PYTHON_EXE if exist "%ROOT%\venv\Scripts\python.exe" set "PYTHON_EXE=%ROOT%\venv\Scripts\python.exe"
if not defined PYTHON_EXE (
  for /f "delims=" %%P in ('where python 2^>nul') do (
    if not defined PYTHON_EXE (
      set "CAND=%%P"
      if /I "!CAND:WindowsApps=!"=="!CAND!" set "PYTHON_EXE=%%P"
    )
  )
)
if not defined PYTHON_EXE (
  echo.
  echo [ERROR] Python not found. Install Python 3.10+ and add it to PATH.
  pause
  exit /b 1
)

set "SELF_NAME=%PET_CHAT_SELF%"
echo.
set /p "INPUT_SELF=Your name in the chat log (Enter to auto-detect): "
if not "%INPUT_SELF%"=="" set "SELF_NAME=%INPUT_SELF%"

set "PARTNER_NAME=%PET_CHAT_PARTNER%"
set /p "INPUT_PARTNER=Partner name in the chat log (Enter to auto-detect): "
if not "%INPUT_PARTNER%"=="" set "PARTNER_NAME=%INPUT_PARTNER%"

"%PYTHON_EXE%" "%ROOT%\set_wechat_chat_config.py" --config "%ROOT%\pet_config.ini" --chat-log "%CHAT_LOG%" --self-name "%SELF_NAME%" --partner-name "%PARTNER_NAME%"
if errorlevel 1 (
  echo.
  echo [ERROR] Failed to save chat config.
  pause
  exit /b 1
)

echo.
echo [OK] Chat config saved.
echo.

if /i "%PET_IMPORT_ONLY%"=="1" exit /b 0
if /i "%PET_IMPORT_ONLY%"=="true" exit /b 0

set "PET_CHAT_SELF=%SELF_NAME%"
set "PET_CHAT_PARTNER=%PARTNER_NAME%"
set "PET_FORCE_FOREGROUND=1"
set "PET_FORCE_BACKGROUND=0"

call "%ROOT%\start_desktop_pet.bat" bibi "%CHAT_LOG%" 160
exit /b %ERRORLEVEL%
