"""
Pre-flight: Locate and create the OCR working directory.
Outputs: OCR_DIR=<path>
Sets:    OCR_DIR environment variable
Writes:  .ocr_dir config file (so other scripts can find the path without env var)
"""
import os, shutil, string

_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_CFG_FILE = os.path.join(_THIS_DIR, ".ocr_dir")

# ── Optional: fill in a custom path, or leave blank to auto-select drive ──
custom_ocr_dir = ""   # e.g. "C:\\image-ocr" or "D:\\image-ocr"

if custom_ocr_dir and os.path.exists(os.path.dirname(custom_ocr_dir.rstrip("\\/"))) :
    ocr_dir = custom_ocr_dir
    os.makedirs(ocr_dir, exist_ok=True)
    print(f"OCR_DIR={ocr_dir} (user-specified)")
else:
    best_drive, best_free = None, -1
    for d in string.ascii_uppercase:
        root = f"{d}:\\"
        if os.path.exists(root):
            try:
                free = shutil.disk_usage(root).free
                if free > best_free:
                    best_free, best_drive = free, d
            except Exception:
                pass
    ocr_dir = os.path.join(f"{best_drive}:\\", "image-ocr")
    os.makedirs(ocr_dir, exist_ok=True)
    print(f"OCR_DIR={ocr_dir} (auto-selected drive: {best_drive})")

os.environ["OCR_DIR"] = ocr_dir

# Persist to config file so scripts work even without the env var (e.g. bash.exe on Windows)
with open(_CFG_FILE, "w", encoding="utf-8") as f:
    f.write(ocr_dir)
print(f"Config saved to: {_CFG_FILE}")
