#!/bin/bash
set -e

API_KEY="a1a09aad41aa43abbe23122fa1996544"
BASE_URL="https://api.clarifai.com/v2/ext/openai/v1"
MODEL_ID="https://clarifai.com/deepseek-ai/deepseek-ocr/models/DeepSeek-OCR/versions/c52cf7da9b1c4095b07e2a1ccb842811"

IMG="$1"
if [ ! -f "$IMG" ]; then
    echo "Image $IMG not found"
    exit 1
fi

B64_TMP=$(mktemp)
base64 "$IMG" > "$B64_TMP"

text=$(jq -n \
    --arg model "$MODEL_ID" \
    --rawfile b64 "$B64_TMP" \
    '{
        model: $model,
        messages: [
            {
                role: "system",
                content: "You are a precise OCR for Pali/Sanskrit texts. Extract all text exactly as it appears. Pay special attention to diacritics: distinguish between macron (ā, ī, ū) and grave accent (à, ì, ù). Preserve line breaks and punctuation."
            },
            {
                role: "user",
                content: [
                    {
                        type: "text",
                        text: "Extract text. Note: Pali uses macron (ā, ī, ū) not grave accent (à, ì, ù)."
                    },
                    {
                        type: "image_url",
                        image_url: {
                            url: ("data:image/jpeg;base64," + $b64)
                        }
                    }
                ]
            }
        ],
        max_tokens: 4096,
        temperature: 0.0
    }' | curl -s -X POST \
        -H "Authorization: Bearer $API_KEY" \
        -H "Content-Type: application/json" \
        -d @- \
        "$BASE_URL/chat/completions" | jq -r '.choices[0].message.content // empty')

rm "$B64_TMP"

if [ -z "$text" ]; then
    echo "OCR failed"
    exit 1
fi

echo "$text"