@echo off
rem ===================================================================
rem RTGS 네이티브 인프라 기동 (Docker 대체 - 이 PC는 가상화 미지원).
rem   PostgreSQL(:5433)  + Kafka(:9092, KRaft 단일노드)
rem   문서저장(원전문/조회사본)도 PostgreSQL 사용(MongoDB는 EDR 파일락으로 제외).
rem 멱등: 이미 초기화/기동돼 있으면 건너뜀.
rem ===================================================================
call C:\ai-dev\scripts\env.cmd
set "JAVA_HOME=%JDK21_HOME%"
set "PGBIN=%DEV_HOME%\apps\postgresql-16.4\bin"
set "PGDATA=%DEV_HOME%\home\pgsql-data"
set "KAFKA=%DEV_HOME%\apps\kafka-3.8.1"
set "KDATA=%DEV_HOME%\home\kafka"
set "KAFKA_HEAP_OPTS=-Xmx1G -Xms1G"

rem ---------- PostgreSQL ----------
if not exist "%PGDATA%\PG_VERSION" (
  echo [infra] initdb PostgreSQL cluster...
  "%PGBIN%\initdb.exe" -D "%PGDATA%" -U rtgs -E UTF8 --locale=C -A trust
)
"%PGBIN%\pg_ctl.exe" status -D "%PGDATA%" >nul 2>&1
if errorlevel 1 (
  echo [infra] starting PostgreSQL :5433...
  "%PGBIN%\pg_ctl.exe" -D "%PGDATA%" -o "-p 5433" -l "%PGDATA%\server.log" -w start
) else (
  echo [infra] PostgreSQL already running.
)
rem create db if missing (스키마/시드는 Flyway가 담당 — LouisVuitton 기동 시 V1__baseline 부터 적용)
"%PGBIN%\psql.exe" -h localhost -p 5433 -U rtgs -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname='rtgs'" | findstr "1" >nul
if errorlevel 1 (
  echo [infra] creating empty db rtgs [schema by Flyway]...
  "%PGBIN%\createdb.exe" -h localhost -p 5433 -U rtgs rtgs
)

rem ---------- Kafka (KRaft) ----------
if not exist "%KDATA%\kraft-logs\meta.properties" (
  echo [infra] formatting Kafka KRaft storage...
  for /f "delims=" %%i in ('%KAFKA%\bin\windows\kafka-storage.bat random-uuid') do set "CID=%%i"
  "%KAFKA%\bin\windows\kafka-storage.bat" format -t %CID% -c "%KDATA%\server.properties"
)
echo [infra] starting Kafka :9092 (new window; keep it open)...
start "RTGS Kafka :9092" cmd /k "%KAFKA%\bin\windows\kafka-server-start.bat %KDATA%\server.properties"

echo.
echo [infra] PostgreSQL :5433 (db rtgs), Kafka :9092 up. (MongoDB not used - docs in PostgreSQL)
