@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
title ComfyUI Yonetim Paneli - RTX 4090

set "BASE_DIR=D:\__sistem__\ProgramFiles\ComfyUi"
set "COMFY_DIR=%BASE_DIR%\ComfyUI"

:menu
cls
echo.
echo  ╔══════════════════════════════════════════════════════════════╗
echo  ║           ComfyUI YONETIM PANELI  -  RTX 4090              ║
echo  ╚══════════════════════════════════════════════════════════════╝
echo.
echo   ──── TEMEL ────────────────────────────────────────────────
echo   [1] ComfyUI Baslat              (http://127.0.0.1:8188)
echo   [2] ComfyUI + Node Guncelle     (git pull)
echo.
echo   ──── KURULUM ──────────────────────────────────────────────
echo   [3] Sifirdan Tam Kurulum        (ComfyUI + Nodes + PyTorch)
echo   [4] Model Indir                 (~200 GB checkpoint/video/face)
echo   [5] Optimize Kurulum            (~70 GB karakter/reklam odakli)
echo   [6] LoRA Egitim Araci (Kohya)   (~20 GB)
echo.
echo   ──── ONARIM ───────────────────────────────────────────────
echo   [7] CUDA / PyTorch Onarim
echo   [8] Eksik Node Duzelt           (ReActor, InstantID)
echo   [9] PuLID Model + Temizlik
echo.
echo   ──── DIGER ────────────────────────────────────────────────
echo   [0] Sistem Kontrolu             (Git, Python, NVIDIA, Disk)
echo   [K] Kohya_ss Baslat             (LoRA egitim GUI)
echo   [Q] Cikis
echo.
set /p "choice=  Seciminiz: "

if /i "%choice%"=="1" goto start_comfy
if /i "%choice%"=="2" goto update
if /i "%choice%"=="3" goto full_install
if /i "%choice%"=="4" goto download_models
if /i "%choice%"=="5" goto optimize_install
if /i "%choice%"=="6" goto kohya_install
if /i "%choice%"=="7" goto fix_cuda
if /i "%choice%"=="8" goto fix_nodes
if /i "%choice%"=="9" goto fix_pulid
if /i "%choice%"=="0" goto syscheck
if /i "%choice%"=="K" goto kohya_start
if /i "%choice%"=="Q" exit /b 0
goto menu

:: ================================================================
:: [1] COMFYUI BASLAT
:: ================================================================
:start_comfy
cls
if not exist "%COMFY_DIR%\main.py" (
    echo [HATA] ComfyUI bulunamadi. Once [3] Tam Kurulum yapin.
    pause
    goto menu
)
cd /d "%COMFY_DIR%"
call venv\Scripts\activate.bat
echo.
echo  ================================================================
echo    ComfyUI baslatiliyor - RTX 4090 (24GB VRAM) optimize
echo    Arayuz: http://127.0.0.1:8188
echo    Kapatmak icin bu pencereyi kapatin veya Ctrl+C
echo  ================================================================
echo.
python main.py --highvram --fast --preview-method auto --front-end-version Comfy-Org/ComfyUI_frontend@latest
pause
goto menu

:: ================================================================
:: [2] GUNCELLE
:: ================================================================
:update
cls
echo.
echo  ════════════════════════════════════════════
echo    ComfyUI + Custom Nodes Guncelleme
echo  ════════════════════════════════════════════
echo.
cd /d "%COMFY_DIR%"
echo [1/3] ComfyUI ana kod...
git pull
echo.
echo [2/3] Custom node'lar...
for /d %%D in ("%COMFY_DIR%\custom_nodes\*") do (
    if exist "%%D\.git" (
        echo   -^> %%~nxD
        cd /d "%%D" && git pull --quiet
    )
)
echo.
echo [3/3] Python bagimliliklari...
cd /d "%COMFY_DIR%"
call venv\Scripts\activate.bat
pip install -r requirements.txt --upgrade --quiet
for /d %%D in ("%COMFY_DIR%\custom_nodes\*") do (
    if exist "%%D\requirements.txt" (
        pip install -r "%%D\requirements.txt" --upgrade --quiet >nul 2>&1
    )
)
echo.
echo [OK] Guncelleme tamamlandi!
pause
goto menu

:: ================================================================
:: [3] SIFIRDAN TAM KURULUM
:: ================================================================
:full_install
cls
echo.
echo  ════════════════════════════════════════════
echo    ComfyUI TAM KURULUM - RTX 4090
echo  ════════════════════════════════════════════
echo.
echo  Kurulacaklar:
echo   - ComfyUI + ComfyUI Manager
echo   - PyTorch + CUDA 12.6 + xformers
echo   - 20+ custom node (ReActor, IPAdapter, InstantID, PuLID, Wan, vs.)
echo.
pause

net session >nul 2>&1
if %errorLevel% neq 0 (
    echo [UYARI] Yonetici olarak calistirin.
    pause
    goto menu
)

:: Klasor hazirla
if not exist "%COMFY_DIR%" (
    cd /d "%BASE_DIR%"
    echo [1/5] ComfyUI klonlaniyor...
    git clone https://github.com/comfyanonymous/ComfyUI.git
) else (
    echo [1/5] ComfyUI zaten var, guncelleniyor...
    cd /d "%COMFY_DIR%" && git pull
)

:: venv + PyTorch
echo.
echo [2/5] Python ortami + PyTorch CUDA 12.6...
cd /d "%COMFY_DIR%"
if not exist "venv" python -m venv venv
call venv\Scripts\activate.bat
python -m pip install --upgrade pip wheel setuptools
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
pip install -r requirements.txt
pip install xformers --index-url https://download.pytorch.org/whl/cu126

:: Custom nodes
echo.
echo [3/5] Custom node'lar kuruluyor...
cd "%COMFY_DIR%\custom_nodes"

:: Manager
if not exist "ComfyUI-Manager" git clone https://github.com/ltdrdata/ComfyUI-Manager.git

:: Yardimcilar
for %%R in (
    "rgthree-comfy=https://github.com/rgthree/rgthree-comfy.git"
    "was-node-suite-comfyui=https://github.com/WASasquatch/was-node-suite-comfyui.git"
    "ComfyUI-Custom-Scripts=https://github.com/pythongosssss/ComfyUI-Custom-Scripts.git"
    "ComfyUI-Crystools=https://github.com/crystian/ComfyUI-Crystools.git"
    "efficiency-nodes-comfyui=https://github.com/jags111/efficiency-nodes-comfyui.git"
) do (
    for /f "tokens=1,2 delims==" %%A in (%%R) do (
        if not exist "%%A" git clone %%B
    )
)

:: Face/Detail/Upscale
for %%R in (
    "ComfyUI-Impact-Pack=https://github.com/ltdrdata/ComfyUI-Impact-Pack.git"
    "ComfyUI-Impact-Subpack=https://github.com/ltdrdata/ComfyUI-Impact-Subpack.git"
    "ComfyUI_UltimateSDUpscale=https://github.com/ssitu/ComfyUI_UltimateSDUpscale.git"
    "ComfyUI_essentials=https://github.com/cubiq/ComfyUI_essentials.git"
) do (
    for /f "tokens=1,2 delims==" %%A in (%%R) do (
        if not exist "%%A" git clone %%B
    )
)

:: IPAdapter + ControlNet
for %%R in (
    "ComfyUI_IPAdapter_plus=https://github.com/cubiq/ComfyUI_IPAdapter_plus.git"
    "comfyui_controlnet_aux=https://github.com/Fannovel16/comfyui_controlnet_aux.git"
    "ComfyUI-Advanced-ControlNet=https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet.git"
) do (
    for /f "tokens=1,2 delims==" %%A in (%%R) do (
        if not exist "%%A" git clone %%B
    )
)

:: Face Swap + Identity
if not exist "ComfyUI-ReActor" git clone https://github.com/Gourieff/ComfyUI-ReActor.git
if not exist "ComfyUI_InstantID" git clone https://github.com/cubiq/ComfyUI_InstantID.git
if not exist "PuLID_ComfyUI" git clone https://github.com/cubiq/PuLID_ComfyUI.git

:: Video
for %%R in (
    "ComfyUI-VideoHelperSuite=https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite.git"
    "ComfyUI-AnimateDiff-Evolved=https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved.git"
    "ComfyUI-HunyuanVideoWrapper=https://github.com/kijai/ComfyUI-HunyuanVideoWrapper.git"
    "ComfyUI-LTXVideo=https://github.com/Lightricks/ComfyUI-LTXVideo.git"
    "ComfyUI-WanVideoWrapper=https://github.com/kijai/ComfyUI-WanVideoWrapper.git"
    "ComfyUI-Frame-Interpolation=https://github.com/Fannovel16/ComfyUI-Frame-Interpolation.git"
) do (
    for /f "tokens=1,2 delims==" %%A in (%%R) do (
        if not exist "%%A" git clone %%B
    )
)

:: GGUF
if not exist "ComfyUI-GGUF" git clone https://github.com/city96/ComfyUI-GGUF.git

:: Node bagimliliklari
echo.
echo [4/5] Node bagimliliklari yukleniyor...
cd /d "%COMFY_DIR%"
for /d %%D in ("%COMFY_DIR%\custom_nodes\*") do (
    if exist "%%D\requirements.txt" (
        echo   -^> %%~nxD
        pip install -r "%%D\requirements.txt" --quiet --no-warn-script-location >nul 2>&1
    )
    if exist "%%D\install.py" (
        python "%%D\install.py" >nul 2>&1
    )
)
pip install insightface==0.7.3 onnx onnxruntime-gpu --quiet --no-warn-script-location

:: Model klasorleri
echo.
echo [5/5] Model klasor yapisi...
cd "%COMFY_DIR%\models"
for %%F in (checkpoints loras vae controlnet upscale_models embeddings ipadapter clip_vision diffusion_models insightface facerestore_models sams pulid instantid) do (
    if not exist "%%F" mkdir "%%F"
)
if not exist "ultralytics\bbox" mkdir "ultralytics\bbox"
if not exist "ultralytics\segm" mkdir "ultralytics\segm"

echo.
echo ════════════════════════════════════════════
echo [OK] Tam kurulum tamamlandi!
echo Sonraki adim: [4] Model Indir veya [5] Optimize Kurulum
echo ════════════════════════════════════════════
pause
goto menu

:: ================================================================
:: [4] MODEL INDIR (~200 GB)
:: ================================================================
:download_models
cls
echo.
echo  ════════════════════════════════════════════
echo    MODEL INDIRME (~200 GB)
echo  ════════════════════════════════════════════
echo.
if not exist "%COMFY_DIR%\models" (
    echo [HATA] ComfyUI bulunamadi. Once [3] Tam Kurulum yapin.
    pause
    goto menu
)

where aria2c >nul 2>&1
if %errorLevel%==0 (
    set "USE_ARIA=1"
    echo [OK] aria2c bulundu - hizli indirme aktif
) else (
    set "USE_ARIA=0"
    echo [NOT] aria2c yok, curl kullanilacak
)
echo.
echo Indirmek icin ENTER'a basin...
pause

:: --- CHECKPOINTS ---
echo.
echo === [1/6] CHECKPOINT modelleri ===
cd /d "%COMFY_DIR%\models\checkpoints"

call :download "juggernautXL_v9.safetensors" "https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/resolve/main/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors"
call :download "ponyDiffusionV6XL.safetensors" "https://huggingface.co/AstraliteHeart/pony-diffusion-v6/resolve/main/v6.safetensors"
call :download "illustriousXL_v01.safetensors" "https://huggingface.co/OnomaAIResearch/Illustrious-xl-early-release-v0/resolve/main/Illustrious-XL-v0.1.safetensors"
call :download "realvisxlV40.safetensors" "https://huggingface.co/SG161222/RealVisXL_V4.0/resolve/main/RealVisXL_V4.0.safetensors"
call :download "flux1-schnell-fp8.safetensors" "https://huggingface.co/Comfy-Org/flux1-schnell/resolve/main/flux1-schnell-fp8.safetensors"

:: --- VAE ---
echo.
echo === [2/6] VAE modelleri ===
cd /d "%COMFY_DIR%\models\vae"
call :download "sdxl_vae.safetensors" "https://huggingface.co/stabilityai/sdxl-vae/resolve/main/sdxl_vae.safetensors"
call :download "flux_ae.safetensors" "https://huggingface.co/Comfy-Org/Lumina_Image_2.0_Repackaged/resolve/main/split_files/vae/ae.safetensors"

:: --- TEXT ENCODERS ---
echo.
echo === [3/6] CLIP/T5 text encoders ===
cd /d "%COMFY_DIR%\models\clip"
call :download "t5xxl_fp8_e4m3fn.safetensors" "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/t5xxl_fp8_e4m3fn.safetensors"
call :download "clip_l.safetensors" "https://huggingface.co/comfyanonymous/flux_text_encoders/resolve/main/clip_l.safetensors"

:: --- VIDEO ---
echo.
echo === [4/6] Video modelleri ===
cd /d "%COMFY_DIR%\models\diffusion_models"
call :download "hunyuan_video_t2v_720p_bf16.safetensors" "https://huggingface.co/Kijai/HunyuanVideo_comfy/resolve/main/hunyuan_video_720_cfgdistill_fp8_e4m3fn.safetensors"
call :download "ltx-video-2b-v0.9.1.safetensors" "https://huggingface.co/Lightricks/LTX-Video/resolve/main/ltx-video-2b-v0.9.1.safetensors"
call :download "wan2.1_i2v_480p_14B_fp8.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Wan2_1-I2V-14B-480P_fp8_e4m3fn.safetensors"

:: --- UPSCALERS ---
echo.
echo === [5/6] Upscale modelleri ===
cd /d "%COMFY_DIR%\models\upscale_models"
curl -L -o "4x-UltraSharp.pth" "https://huggingface.co/Kim2091/UltraSharp/resolve/main/4x-UltraSharp.pth"
curl -L -o "RealESRGAN_x4plus.pth" "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth"
curl -L -o "4x_NMKD-Siax_200k.pth" "https://huggingface.co/gemasai/4x_NMKD-Siax_200k/resolve/main/4x_NMKD-Siax_200k.pth"

:: --- CONTROLNET + FACE ---
echo.
echo === [6/6] ControlNet + Face modelleri ===
cd /d "%COMFY_DIR%\models\controlnet"
call :download "controlnet_union_sdxl_promax.safetensors" "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors"

cd /d "%COMFY_DIR%\models\ipadapter"
curl -L -o "ip-adapter-plus_sdxl_vit-h.safetensors" "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors"
curl -L -o "ip-adapter-faceid_sdxl.bin" "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid_sdxl.bin"

cd /d "%COMFY_DIR%\models\clip_vision"
curl -L -o "CLIP-ViT-H-14.safetensors" "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors"

cd /d "%COMFY_DIR%\models\ultralytics\bbox"
curl -L -o "face_yolov8m.pt" "https://huggingface.co/Bingsu/adetailer/resolve/main/face_yolov8m.pt"
curl -L -o "hand_yolov8s.pt" "https://huggingface.co/Bingsu/adetailer/resolve/main/hand_yolov8s.pt"

cd /d "%COMFY_DIR%\models\ultralytics\segm"
curl -L -o "person_yolov8m-seg.pt" "https://huggingface.co/Bingsu/adetailer/resolve/main/person_yolov8m-seg.pt"

cd /d "%COMFY_DIR%\models\facerestore_models"
curl -L -o "GFPGANv1.4.pth" "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth"
curl -L -o "codeformer-v0.1.0.pth" "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth"

cd /d "%COMFY_DIR%\models\insightface"
curl -L -o "inswapper_128.onnx" "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"

cd /d "%COMFY_DIR%\models\sams"
curl -L -o "sam_vit_b_01ec64.pth" "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"

echo.
echo ════════════════════════════════════════════
echo [OK] Tum modeller indirildi!
echo ════════════════════════════════════════════
pause
goto menu

:: ================================================================
:: [5] OPTIMIZE KURULUM (~70 GB karakter/reklam odakli)
:: ================================================================
:optimize_install
cls
echo.
echo  ════════════════════════════════════════════
echo    OPTIMIZE KURULUM - Karakter/Reklam Paketi
echo    (~70 GB indirme)
echo  ════════════════════════════════════════════
echo.
if not exist "%COMFY_DIR%\models" (
    echo [HATA] ComfyUI bulunamadi. Once [3] Tam Kurulum yapin.
    pause
    goto menu
)

cd /d "%COMFY_DIR%"
call venv\Scripts\activate.bat

:: Eksik node'lar
echo [1/4] Eksik node'lar kontrol ediliyor...
cd "%COMFY_DIR%\custom_nodes"
if not exist "ComfyUI-ReActor" git clone https://github.com/Gourieff/ComfyUI-ReActor.git
if not exist "ComfyUI_InstantID" git clone https://github.com/cubiq/ComfyUI_InstantID.git
if not exist "PuLID_ComfyUI" git clone https://github.com/cubiq/PuLID_ComfyUI.git

for %%N in (ComfyUI-ReActor ComfyUI_InstantID PuLID_ComfyUI) do (
    if exist "custom_nodes\%%N\requirements.txt" (
        pip install -r "custom_nodes\%%N\requirements.txt" --quiet --no-warn-script-location
    )
)
pip install insightface==0.7.3 onnx onnxruntime-gpu --quiet --no-warn-script-location

:: Checkpoints
echo.
echo [2/4] Checkpoint modelleri...
cd /d "%COMFY_DIR%\models\checkpoints"
call :download "juggernautXL_v9.safetensors" "https://huggingface.co/RunDiffusion/Juggernaut-XL-v9/resolve/main/Juggernaut-XL_v9_RunDiffusionPhoto_v2.safetensors"
call :download "realvisxlV40.safetensors" "https://huggingface.co/SG161222/RealVisXL_V4.0/resolve/main/RealVisXL_V4.0.safetensors"

:: IP-Adapter + InstantID + PuLID + ControlNet
echo.
echo [3/4] IP-Adapter / InstantID / PuLID modelleri...
cd /d "%COMFY_DIR%\models\ipadapter"
call :download "ip-adapter-plus-face_sdxl_vit-h.safetensors" "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus-face_sdxl_vit-h.safetensors"
call :download "ip-adapter-plus_sdxl_vit-h.safetensors" "https://huggingface.co/h94/IP-Adapter/resolve/main/sdxl_models/ip-adapter-plus_sdxl_vit-h.safetensors"
call :download "ip-adapter-faceid-plusv2_sdxl.bin" "https://huggingface.co/h94/IP-Adapter-FaceID/resolve/main/ip-adapter-faceid-plusv2_sdxl.bin"

cd /d "%COMFY_DIR%\models\instantid"
call :download "ip-adapter.bin" "https://huggingface.co/InstantX/InstantID/resolve/main/ip-adapter.bin"

cd /d "%COMFY_DIR%\models\controlnet"
call :download "instantid-controlnet.safetensors" "https://huggingface.co/InstantX/InstantID/resolve/main/ControlNetModel/diffusion_pytorch_model.safetensors"
call :download "controlnet_union_sdxl_promax.safetensors" "https://huggingface.co/xinsir/controlnet-union-sdxl-1.0/resolve/main/diffusion_pytorch_model_promax.safetensors"

if not exist "%COMFY_DIR%\models\pulid" mkdir "%COMFY_DIR%\models\pulid"
cd /d "%COMFY_DIR%\models\pulid"
call :download "ip-adapter_pulid_sdxl_fp16.safetensors" "https://huggingface.co/huchenlei/ipadapter_pulid/resolve/main/ip-adapter_pulid_sdxl_fp16.safetensors"

cd /d "%COMFY_DIR%\models\clip_vision"
call :download "CLIP-ViT-H-14-laion2B-s32B-b79K.safetensors" "https://huggingface.co/h94/IP-Adapter/resolve/main/models/image_encoder/model.safetensors"

:: InsightFace antelopev2
set "ANTE_DIR=%COMFY_DIR%\models\insightface\models\antelopev2"
if not exist "%ANTE_DIR%" mkdir "%ANTE_DIR%"
cd /d "%ANTE_DIR%"
for %%M in (1k3d68 2d106det genderage glintr100 scrfd_10g_bnkps) do (
    if not exist "%%M.onnx" curl -L -o "%%M.onnx" "https://huggingface.co/MonsterMMORPG/tools/resolve/main/%%M.onnx"
)

:: Video
echo.
echo [4/4] Video modelleri (Wan 2.1)...
cd /d "%COMFY_DIR%\models\diffusion_models"
call :download "wan2.1_i2v_480p_14B_fp8.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Wan2_1-I2V-14B-480P_fp8_e4m3fn.safetensors"
call :download "wan2.1_t2v_14B_fp8.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Wan2_1-T2V-14B_fp8_e4m3fn.safetensors"

cd /d "%COMFY_DIR%\models\vae"
call :download "wan_2.1_vae.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Wan2.1_VAE.safetensors"

cd /d "%COMFY_DIR%\models\clip"
call :download "umt5-xxl-enc-bf16.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/umt5-xxl-enc-bf16.safetensors"

cd /d "%COMFY_DIR%\models\clip_vision"
call :download "clip_vision_h_wan.safetensors" "https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/clip_vision_h.safetensors"

:: Face/Upscale
cd /d "%COMFY_DIR%\models\facerestore_models"
if not exist "GFPGANv1.4.pth" curl -L -o "GFPGANv1.4.pth" "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/GFPGANv1.4.pth"
if not exist "codeformer-v0.1.0.pth" curl -L -o "codeformer-v0.1.0.pth" "https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth"

cd /d "%COMFY_DIR%\models\ultralytics\bbox"
if not exist "face_yolov8m.pt" curl -L -o "face_yolov8m.pt" "https://huggingface.co/Bingsu/adetailer/resolve/main/face_yolov8m.pt"

cd /d "%COMFY_DIR%\models\upscale_models"
if not exist "4x-UltraSharp.pth" curl -L -o "4x-UltraSharp.pth" "https://huggingface.co/Kim2091/UltraSharp/resolve/main/4x-UltraSharp.pth"

cd /d "%COMFY_DIR%\models\insightface"
if not exist "inswapper_128.onnx" curl -L -o "inswapper_128.onnx" "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"

cd /d "%COMFY_DIR%\models\sams"
if not exist "sam_vit_b_01ec64.pth" curl -L -o "sam_vit_b_01ec64.pth" "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth"

echo.
echo ════════════════════════════════════════════
echo [OK] Optimize kurulum tamamlandi!
echo ════════════════════════════════════════════
pause
goto menu

:: ================================================================
:: [6] KOHYA KURULUM
:: ================================================================
:kohya_install
cls
echo.
echo  ════════════════════════════════════════════
echo    Kohya_ss LoRA Egitim Araci Kurulumu
echo  ════════════════════════════════════════════
echo.
set "KOHYA_DIR=%BASE_DIR%\kohya_ss"
cd /d "%BASE_DIR%"

if exist "%KOHYA_DIR%\.git" (
    echo Kohya_ss guncelleniyor...
    cd "%KOHYA_DIR%" && git pull
) else (
    echo Kohya_ss klonlaniyor...
    git clone --recursive https://github.com/bmaltais/kohya_ss.git
)

cd /d "%KOHYA_DIR%"
if not exist "venv" python -m venv venv
call venv\Scripts\activate.bat
python -m pip install --upgrade pip wheel
pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121
pip install -r requirements_windows_torch2.txt
pip install bitsandbytes

echo.
echo [OK] Kohya_ss kuruldu! Baslatmak icin menuye donup [K] secin.
pause
goto menu

:: ================================================================
:: [7] CUDA ONARIM
:: ================================================================
:fix_cuda
cls
echo.
echo  ════════════════════════════════════════════
echo    CUDA / PyTorch Onarim
echo  ════════════════════════════════════════════
echo.
cd /d "%COMFY_DIR%"
call venv\Scripts\activate.bat

echo [1/4] NVIDIA Driver kontrolu...
nvidia-smi
if %errorlevel% neq 0 (
    echo [HATA] nvidia-smi calismadi! Driver kurun: https://www.nvidia.com/drivers
    pause
    goto menu
)
echo.
echo [2/4] Mevcut PyTorch kaldiriliyor...
pip uninstall torch torchvision torchaudio xformers -y
echo.
echo [3/4] PyTorch + CUDA 12.6 yukleniyor...
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
pip install xformers --index-url https://download.pytorch.org/whl/cu126
echo.
echo [4/4] CUDA testi...
python -c "import torch; print('CUDA:', torch.cuda.is_available()); print('GPU:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'YOK')"
echo.
echo [OK] Onarim tamamlandi!
pause
goto menu

:: ================================================================
:: [8] EKSIK NODE DUZELT
:: ================================================================
:fix_nodes
cls
echo.
echo  ════════════════════════════════════════════
echo    Eksik Node Duzeltme
echo  ════════════════════════════════════════════
echo.
cd /d "%COMFY_DIR%\custom_nodes"

if not exist "ComfyUI-ReActor" (
    echo ReActor kuruluyor...
    git clone https://github.com/Gourieff/ComfyUI-ReActor.git
) else (
    echo [OK] ReActor zaten kurulu
)

if not exist "ComfyUI_InstantID" (
    echo InstantID kuruluyor...
    git clone https://github.com/cubiq/ComfyUI_InstantID.git
) else (
    echo [OK] InstantID zaten kurulu
)

if not exist "PuLID_ComfyUI" (
    echo PuLID kuruluyor...
    git clone https://github.com/cubiq/PuLID_ComfyUI.git
) else (
    echo [OK] PuLID zaten kurulu
)

:: Yanlis isimli klasorleri temizle
if exist "comfyui-reactor-node" rmdir /s /q "comfyui-reactor-node"

cd /d "%COMFY_DIR%"
call venv\Scripts\activate.bat
for %%N in (ComfyUI-ReActor ComfyUI_InstantID PuLID_ComfyUI) do (
    if exist "custom_nodes\%%N\requirements.txt" (
        echo   -^> %%N bagimliliklar
        pip install -r "custom_nodes\%%N\requirements.txt" --quiet --no-warn-script-location
    )
)
pip install insightface==0.7.3 onnx onnxruntime-gpu --quiet --no-warn-script-location

echo.
echo [OK] Node'lar duzeltildi!
pause
goto menu

:: ================================================================
:: [9] PULID MODEL + TEMIZLIK
:: ================================================================
:fix_pulid
cls
echo.
echo  ════════════════════════════════════════════
echo    PuLID Model + Temizlik
echo  ════════════════════════════════════════════
echo.

:: NVIDIA Corporation temizle
if exist "%COMFY_DIR%\custom_nodes\NVIDIA Corporation" (
    echo Gereksiz NVIDIA Corporation klasoru siliniyor...
    rmdir /s /q "%COMFY_DIR%\custom_nodes\NVIDIA Corporation" 2>nul
)

:: PuLID model
if not exist "%COMFY_DIR%\models\pulid" mkdir "%COMFY_DIR%\models\pulid"
cd /d "%COMFY_DIR%\models\pulid"
echo PuLID model indiriliyor (~1GB)...
call :download "ip-adapter_pulid_sdxl_fp16.safetensors" "https://huggingface.co/huchenlei/ipadapter_pulid/resolve/main/ip-adapter_pulid_sdxl_fp16.safetensors"

:: antelopev2
set "ANTE_DIR=%COMFY_DIR%\models\insightface\models\antelopev2"
if not exist "%ANTE_DIR%" (
    echo InsightFace antelopev2 indiriliyor...
    mkdir "%ANTE_DIR%"
    cd /d "%ANTE_DIR%"
    for %%M in (1k3d68 2d106det genderage glintr100 scrfd_10g_bnkps) do (
        curl -L -o "%%M.onnx" "https://huggingface.co/MonsterMMORPG/tools/resolve/main/%%M.onnx"
    )
) else (
    echo [OK] antelopev2 zaten kurulu
)

echo.
echo [OK] Temizlik ve PuLID tamamlandi!
pause
goto menu

:: ================================================================
:: [0] SISTEM KONTROLU
:: ================================================================
:syscheck
cls
echo.
echo  ════════════════════════════════════════════
echo    SISTEM KONTROLU
echo  ════════════════════════════════════════════
echo.

where git >nul 2>&1
if %errorLevel%==0 (echo  [OK]   Git yuklu) else (echo  [EKSIK] Git - https://git-scm.com/download/win)

where python >nul 2>&1
if %errorLevel%==0 (
    echo  [OK]   Python:
    python --version
) else (
    echo  [EKSIK] Python - https://python.org
)

where nvidia-smi >nul 2>&1
if %errorLevel%==0 (
    echo  [OK]   NVIDIA GPU:
    nvidia-smi --query-gpu=name,driver_version,memory.total --format=csv,noheader
) else (
    echo  [EKSIK] NVIDIA driver
)

where aria2c >nul 2>&1
if %errorLevel%==0 (echo  [OK]   aria2c yuklu) else (echo  [ONERI] aria2c yok - https://aria2.github.io/)

echo.
if exist "%COMFY_DIR%\main.py" (echo  [OK]   ComfyUI kurulu) else (echo  [EKSIK] ComfyUI kurulu degil)
if exist "%COMFY_DIR%\venv" (echo  [OK]   Python venv mevcut) else (echo  [EKSIK] venv yok)

echo.
echo  Disk durumu:
wmic logicaldisk where "DeviceID='D:'" get Size,FreeSpace /format:value 2>nul

echo.
pause
goto menu

:: ================================================================
:: [K] KOHYA BASLAT
:: ================================================================
:kohya_start
cls
set "KOHYA_DIR=%BASE_DIR%\kohya_ss"
if not exist "%KOHYA_DIR%\kohya_gui.py" (
    echo [HATA] Kohya_ss kurulu degil. Once [6] ile kurun.
    pause
    goto menu
)
cd /d "%KOHYA_DIR%"
call venv\Scripts\activate.bat
echo Kohya_ss baslatiliyor... http://127.0.0.1:7860
python kohya_gui.py --listen 127.0.0.1 --server_port 7860 --inbrowser
pause
goto menu

:: ================================================================
:: YARDIMCI: Indirme fonksiyonu (aria2c veya curl)
:: ================================================================
:download
set "FNAME=%~1"
set "URL=%~2"
if exist "%FNAME%" (
    echo   [MEVCUT] %FNAME%
    goto :eof
)
echo   -^> %FNAME%
if "%USE_ARIA%"=="1" (
    aria2c -x 16 -s 16 --continue=true --dir="." --out="%FNAME%" "%URL%"
) else (
    curl -L -o "%FNAME%" "%URL%"
)
goto :eof

endlocal
