"""Example: download an arXiv paper and run OCR via the AIR SDK.

Usage::

    export AIR_API_KEY="air_k1_..."
    python examples/ocr.py [ARXIV_URL]

By default this connects to http://localhost:8000.  Override with::

    export AIR_BASE_URL="https://your-backend.example.com"
"""

import os
import sys
from dotenv import load_dotenv
import air

load_dotenv()

API_KEY = os.environ.get("AIR_API_KEY")
BASE_URL = os.environ.get("AIR_BASE_URL", "http://localhost:8000")

if not API_KEY:
    sys.exit("Set AIR_API_KEY first:  export AIR_API_KEY='air_k1_...'")

ARXIV_URL = sys.argv[1] if len(sys.argv) > 1 else "https://arxiv.org/abs/2301.12345"

with air.AIR(api_key=API_KEY, base_url=BASE_URL) as client:
    # 1. Download paper from arXiv
    print(f"Downloading {ARXIV_URL} ...")
    arxiv_result = client.arxiv(ARXIV_URL)

    downloaded = arxiv_result.get("downloaded_files", [])
    if not downloaded:
        sys.exit(f"No files downloaded. Server response: {arxiv_result}")

    pdf_path = downloaded[0]
    print(f"Downloaded: {pdf_path}")

    # 2. Run OCR on the downloaded PDF
    print("Running OCR ...")
    ocr_result = client.ocr(pdf_path)

    full_text = ocr_result.get("full_text", "")
    if full_text:
        print(f"\n--- OCR result ({len(full_text)} chars) ---")
        print(full_text[:2000])
        if len(full_text) > 2000:
            print(f"\n... ({len(full_text) - 2000} more chars)")
    else:
        print(f"OCR returned no text. Full response: {ocr_result}")
