#!/usr/bin/env python3
"""
convert_with_ocr.py — markitdown wrapper with OCR support

Usage:
    python convert_with_ocr.py <file_path> [--base-url URL] [--api-key KEY] [--model MODEL] [--ocr-prompt PROMPT]

Reads LLM config from env vars if not provided:
  LLM_BASE_URL, LLM_API_KEY, LLM_MODEL

Outputs markdown to stdout. Errors go to stderr.
"""

import argparse
import os
import sys


def main():
    parser = argparse.ArgumentParser(description="Convert document to Markdown with OCR")
    parser.add_argument("file_path", help="Path to the file to convert")
    parser.add_argument("--base-url", default=os.environ.get("LLM_BASE_URL", ""))
    parser.add_argument("--api-key", default=os.environ.get("LLM_API_KEY", ""))
    parser.add_argument("--model", default=os.environ.get("LLM_MODEL", "glm-4v-plus"))
    parser.add_argument("--ocr-prompt", default=os.environ.get("OCR_PROMPT", ""))
    args = parser.parse_args()

    from markitdown import MarkItDown

    llm_client = None
    llm_model = None
    ocr_prompt = (args.ocr_prompt or "").strip()

    if args.base_url and args.api_key:
        try:
            from openai import OpenAI

            if ocr_prompt:
                llm_client = OpenAI(base_url=args.base_url, api_key=args.api_key)
                llm_model = args.model or "glm-4v-plus"
                print(f"[OCR] LLM configured: model={llm_model}", file=sys.stderr)
            else:
                print("[OCR] OCR prompt missing, OCR disabled for images", file=sys.stderr)
        except ImportError:
            print("[OCR] openai package not installed, OCR disabled", file=sys.stderr)
    else:
        print("[OCR] No LLM_BASE_URL/LLM_API_KEY, OCR disabled for images", file=sys.stderr)

    md_kwargs = {
        "enable_plugins": True,
        "llm_client": llm_client,
        "llm_model": llm_model,
    }
    if ocr_prompt:
        md_kwargs["llm_prompt"] = ocr_prompt

    md = MarkItDown(**md_kwargs)

    result = md.convert(args.file_path)
    sys.stdout.write(result.text_content or "")


if __name__ == "__main__":
    main()
