"""
Pre-flight: Check whether llama-server.exe exists and meets the minimum build requirement.
Outputs: LLAMA_STATUS=READY | OUTDATED | MISSING
"""
import os, sys, subprocess, re
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _ocr_cfg import OCR_DIR

if not OCR_DIR:
    print("ERROR: OCR_DIR not resolved. Run preflight_workdir.py first.")
    print("LLAMA_STATUS=MISSING")
    sys.exit(1)

llama_dir  = os.path.join(OCR_DIR, "llama.cpp")
server_exe = os.path.join(llama_dir, "llama-server.exe")

if os.path.exists(server_exe):
    result = subprocess.run([server_exe, "--version"], capture_output=True, text=True)
    output = result.stdout + result.stderr
    m = re.search(r"version:\s*(\d+)", output)
    if m:
        build = int(m.group(1))
        if build >= 8400:
            print(f"OK: llama.cpp build {build} >= b8400, skip Step 1")
            print("LLAMA_STATUS=READY")
        else:
            print(f"WARN: llama.cpp build {build} < b8400, upgrade required")
            print("LLAMA_STATUS=OUTDATED")
    else:
        print("WARN: could not parse version output")
        print("LLAMA_STATUS=OUTDATED")
else:
    print("ERROR: llama-server.exe not found")
    print("LLAMA_STATUS=MISSING")
    print(f"   Checked path: {llama_dir}")
