"""
Step 2 Option A: Download GLM-OCR model files via huggingface_hub.
Outputs: MODEL_DOWNLOAD=DONE
"""
import os, subprocess, sys
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.")
    sys.exit(1)

model_dir = os.path.join(OCR_DIR, "models", "GLM-OCR-GGUF")
os.makedirs(model_dir, exist_ok=True)

subprocess.run([sys.executable, "-m", "pip", "install", "huggingface_hub", "-q"], check=True)

# For users in China: uncomment the next line to use the HF mirror
# os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"

from huggingface_hub import hf_hub_download

for filename in ["GLM-OCR-Q8_0.gguf", "mmproj-GLM-OCR-Q8_0.gguf"]:
    print(f"Downloading {filename} ...")
    hf_hub_download(
        repo_id="ggml-org/GLM-OCR-GGUF",
        filename=filename,
        local_dir=model_dir,
    )

print("MODEL_DOWNLOAD=DONE")
