#!/bin/bash
set -e

IMAGE_PATH="$1"
if [ ! -f "$IMAGE_PATH" ]; then
    echo "File not found: $IMAGE_PATH"
    exit 1
fi

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"

# Encode image to base64
B64=$(base64 "$IMAGE_PATH" | tr -d '\n')

# Construct JSON payload using jq
PAYLOAD=$(jq -n \
    --arg model "$MODEL_ID" \
    --arg b64 "$B64" \
    '{
        model: $model,
        messages: [
            {
                role: "user",
                content: [
                    {
                        type: "text",
                        text: "Extract all text from this image. Keep original formatting, including line breaks. Preserve all special characters, diacritics, and Pali/Sanskrit letters exactly as they appear."
                    },
                    {
                        type: "image_url",
                        image_url: {
                            url: ("data:image/jpeg;base64," + $b64)
                        }
                    }
                ]
            }
        ],
        max_tokens: 4096
    }')

# Call API
response=$(curl -s -X POST \
    -H "Authorization: Bearer $API_KEY" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD" \
    "$BASE_URL/chat/completions")

# Extract text
text=$(echo "$response" | jq -r '.choices[0].message.content // empty')
if [ -z "$text" ]; then
    echo "OCR failed or no text extracted."
    echo "Response: $response"
    exit 1
fi

echo "$text"