#!/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"

B64=$(base64 "$IMAGE_PATH" | tr -d '\n')

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 exactly as it appears, preserving all characters, diacritics, punctuation, and line breaks. Do not add any commentary, explanations, or formatting instructions. Output only the extracted text."
                    },
                    {
                        type: "image_url",
                        image_url: {
                            url: ("data:image/jpeg;base64," + $b64)
                        }
                    }
                ]
            }
        ],
        max_tokens: 4096
    }')

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

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

echo "$text"