"""LipiOCR API examples.

Python 3.10+
Install: pip install requests
Set: export LIPIOCR_API_KEY=...

Usage:
  python ocr.py ocr document.pdf job-unique-id result.zip
  python ocr.py check
  python ocr.py submit document.pdf bank-job-unique-id 3600
  python ocr.py status JOB_ID
  python ocr.py download JOB_ID result.zip
  python ocr.py reason evidence.txt result.json
  python ocr.py vision document.jpg result.json --question "Summarize and extract visible fields"

Keep the same job ID for OCR retries. Do not share job IDs between documents.
"""
import argparse
import json
import mimetypes
import os
import re
import tempfile
import time
import uuid
from pathlib import Path
from urllib.parse import urlsplit

import requests

BASE_URL = os.environ.get('LIPIOCR_BASE_URL', 'https://ocr.lipi.one').rstrip('/')
API_KEY = os.environ.get('LIPIOCR_API_KEY')


def require_key():
    origin = urlsplit(BASE_URL)
    if (origin.scheme != 'https' or not origin.hostname or origin.username is not None or
            origin.password is not None or origin.path or origin.query or origin.fragment):
        raise SystemExit('LIPIOCR_BASE_URL must be a credential-free HTTPS origin.')
    if not API_KEY:
        raise SystemExit('Set LIPIOCR_API_KEY before running this example.')
    return {'Authorization': 'Bearer ' + API_KEY}


def request_with_retry(url, *, method='POST', headers=None, files=None, json_body=None,
                       timeout=(15, 900), stream=False):
    positions = [(part[1], part[1].tell()) for part in (files or {}).values()
                 if isinstance(part, tuple) and hasattr(part[1], "seek")]
    for attempt in range(3):
        for stream, position in positions:
            stream.seek(position)
        try:
            response = requests.request(method, url, headers=headers, files=files, json=json_body,
                                        timeout=timeout, allow_redirects=False, stream=stream)
        except (OSError, requests.RequestException) as exc:
            raise SystemExit(f'Connection failed ({type(exc).__name__}). Check TLS trust and proxy configuration. '
                             'For async retries reuse the same key; synchronous OCR outcome may be unknown.') from None
        if 300 <= response.status_code < 400:
            response.close()
            raise SystemExit('Redirect refused. Configure the final HTTPS origin.')
        if response.status_code == 429 and attempt < 2:
            response.close()
            time.sleep(2 ** (attempt + 1))
            continue
        return response
    return response


def request_key_for(job):
    key_file = Path(job + '.request-key')
    try:
        with key_file.open('x') as saved:
            request_key = str(uuid.uuid4())
            saved.write(request_key)
            return request_key
    except FileExistsError:
        return key_file.read_text().strip()


def ocr(args):
    headers = require_key()
    headers['Idempotency-Key'] = request_key_for(args.job)
    with open(args.source, 'rb') as document:
        response = request_with_retry(
            BASE_URL + '/v1/ocr',
            headers=headers,
            files={'file': (Path(args.source).name, document)},
        )
    if response.status_code != 200:
        raise SystemExit(f'OCR stopped (HTTP {response.status_code})')
    if 'application/zip' not in response.headers.get('content-type', ''):
        raise SystemExit('Unexpected OCR response type; output not saved.')
    Path(args.output).write_bytes(response.content)
    print('Saved OCR bundle:', args.output)


def reason(args):
    headers = require_key()
    headers['Content-Type'] = 'application/json'
    text = Path(args.evidence).read_text(encoding='utf-8')
    response = request_with_retry(
        BASE_URL + '/v1/reason',
        headers=headers,
        json_body={'document_name': Path(args.evidence).name, 'text': text},
        timeout=(15, 120),
    )
    if response.status_code != 200:
        raise SystemExit(f'Reasoning stopped (HTTP {response.status_code})')
    Path(args.output).write_text(json.dumps(response.json(), ensure_ascii=False, indent=2), encoding='utf-8')
    print('Saved reasoning JSON:', args.output)


def vision(args):
    headers = require_key()
    with open(args.image, 'rb') as image:
        response = request_with_retry(
            BASE_URL + '/v1/vision/reason',
            headers=headers,
            files={
                'file': (Path(args.image).name, image, mimetypes.guess_type(args.image)[0] or 'application/octet-stream'),
                'question': (None, args.question),
                'language_mode': (None, args.language_mode),
            },
            timeout=(15, 180),
        )
    if response.status_code != 200:
        raise SystemExit(f'Vision reasoning stopped (HTTP {response.status_code})')
    Path(args.output).write_text(json.dumps(response.json(), ensure_ascii=False, indent=2), encoding='utf-8')
    print('Saved vision reasoning JSON:', args.output)


def bank(args):
    headers = require_key()
    url = BASE_URL + '/v1/jobs'
    if args.command == 'submit':
        if not 60 <= args.ttl <= 86400:
            raise SystemExit('Retention must be 60 to 86400 seconds.')
        headers.update({'X-Retention-Seconds': str(args.ttl), 'Idempotency-Key': request_key_for(args.job)})
        with open(args.source, 'rb') as source:
            response = request_with_retry(url, headers=headers, files={'file': (Path(args.source).name, source)})
        if response.status_code not in (200, 202):
            raise SystemExit(f'Submit failed (HTTP {response.status_code})')
        print(json.dumps(response.json()))
        return
    jid = uuid.uuid4().hex if args.command == 'check' else args.id
    if not re.fullmatch('[0-9a-f]{32}', jid):
        raise SystemExit('Expected a 32-character lowercase hex job ID.')
    download = args.command == 'download'
    url += '/' + jid + ('/download' if download else '')
    with request_with_retry(url, method='GET', headers=headers, timeout=(15, 120), stream=download) as response:
        if args.command == 'check' and response.status_code == 404 and response.json().get('detail') == 'Job not found':
            print('Verified HTTPS, authentication, and bank job lookup. No upload or charge.')
            return
        if args.command == 'check' or response.status_code != 200:
            raise SystemExit(f'Bank {args.command} failed (HTTP {response.status_code})')
        if not download:
            print(json.dumps(response.json()))
            return
        if response.headers.get('content-type', '').split(';')[0] != 'application/zip':
            raise SystemExit('Unexpected response type; output not saved.')
        path = Path(args.output)
        with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as target:
            tmp = Path(target.name)
        try:
            with tmp.open('wb') as output:
                for chunk in response.iter_content(256 * 1024):
                    output.write(chunk)
            tmp.replace(path)
        finally:
            tmp.unlink(missing_ok=True)
        print('Saved OCR bundle:', path)


def main():
    parser = argparse.ArgumentParser(description='LipiOCR API examples')
    sub = parser.add_subparsers(dest='command', required=True)

    p = sub.add_parser('ocr', help='Process a PDF or image and save the ZIP bundle')
    p.add_argument('source')
    p.add_argument('job')
    p.add_argument('output')
    p.set_defaults(func=ocr)

    sub.add_parser('check', help='Verify authenticated HTTPS job lookup without uploading').set_defaults(func=bank)
    p = sub.add_parser('submit', help='Queue OCR with explicit retention (seconds)')
    p.add_argument('source')
    p.add_argument('job')
    p.add_argument('ttl', type=int)
    p.set_defaults(func=bank)
    for name in ('status', 'download'):
        p = sub.add_parser(name)
        p.add_argument('id')
        if name == 'download':
            p.add_argument('output')
        p.set_defaults(func=bank)

    p = sub.add_parser('reason', help='Reason over existing OCR text and save JSON')
    p.add_argument('evidence')
    p.add_argument('output')
    p.set_defaults(func=reason)

    p = sub.add_parser('vision', help='Reason directly over an image and save JSON')
    p.add_argument('image')
    p.add_argument('output')
    p.add_argument('--question', default='Summarize this document and extract visible fields')
    p.add_argument('--language-mode', choices=['auto', 'en', 'ne'], default='auto')
    p.set_defaults(func=vision)

    args = parser.parse_args()
    args.func(args)


if __name__ == '__main__':
    main()
