@echo off
setlocal EnableExtensions
title NL_O1 DataKubun check

set "JLTSQL=C:\Users\oshim\jrvltsql"
set "REPO=C:\work\ai-horse-race.maspis.com.gitclone"
set "SCRIPT=%REPO%\scripts\windows\check_o1_datakubun.py"
set "DB=%JLTSQL%\data\keiba.db"
set "YEAR=%~1"
if "%YEAR%"=="" set "YEAR=2026"

echo ========================================
echo  NL_O1 DataKubun check  year=%YEAR%
echo ========================================
echo.

if not exist "%JLTSQL%\venv32\Scripts\python.exe" (
  echo [ERROR] Python not found: %JLTSQL%\venv32\Scripts\python.exe
  goto :fail
)
if not exist "%DB%" (
  echo [ERROR] keiba.db not found: %DB%
  goto :fail
)

if not exist "%SCRIPT%" (
  echo [STEP A] Script missing. Updating git clone...
  if not exist "%REPO%\.git" (
    echo [ERROR] Repo not found: %REPO%
    echo Run sync_windows_scripts.bat first.
    goto :fail
  )
  cd /d "%REPO%"
  git fetch origin
  git pull origin main
  if errorlevel 1 (
    echo [ERROR] git pull failed.
    goto :fail
  )
)

if not exist "%SCRIPT%" (
  echo [STEP B] Trying scp from server...
  if not exist "%REPO%\scripts\windows" mkdir "%REPO%\scripts\windows"
  scp root@133.130.90.66:/var/www/html/ai-horse-race.maspis.com/scripts/windows/check_o1_datakubun.py "%REPO%\scripts\windows\"
)

if not exist "%SCRIPT%" (
  echo [ERROR] check_o1_datakubun.py still missing after git pull and scp.
  goto :fail
)

echo [STEP C] Running check...
cd /d "%JLTSQL%"
"%JLTSQL%\venv32\Scripts\python.exe" "%SCRIPT%" data\keiba.db %YEAR%
if errorlevel 1 goto :fail

echo.
echo Done. See "kubun in (4,5)" line above.
goto :end

:fail
echo.
echo FAILED.
pause
exit /b 1

:end
pause
exit /b 0
