#!/usr/bin/env bash

set -u

json_probe() {
    local tesseract_ready=false
    local zbar_ready=false
    local english_ready=false

    command -v tesseract >/dev/null 2>&1 && tesseract_ready=true
    command -v zbarimg >/dev/null 2>&1 && zbar_ready=true
    if [[ "$tesseract_ready" == true ]] && tesseract --list-langs 2>/dev/null | grep -qx 'eng'; then
        english_ready=true
    fi

    jq -cn \
        --argjson tesseract "$tesseract_ready" \
        --argjson zbar "$zbar_ready" \
        --argjson english "$english_ready" \
        '{tesseract: $tesseract, zbar: $zbar, english: $english}'
}

json_error() {
    jq -cn --arg error "$1" '{ok: false, text: "", codeType: "", codeValue: "", error: $error}'
}

analyze_file() {
    local image="${1:-}"
    if [[ -z "$image" || ! -f "$image" || ! -r "$image" ]]; then
        json_error 'The captured image is unavailable.'
        return 2
    fi
    if ! command -v tesseract >/dev/null 2>&1; then
        json_error 'Local text recognition is not installed. Install tesseract and zbar.'
        return 3
    fi
    if ! tesseract --list-langs 2>/dev/null | grep -qx 'eng'; then
        json_error 'The English Tesseract language pack is not installed.'
        return 4
    fi

    local work_dir
    work_dir="$(mktemp -d)" || {
        json_error 'Panama could not create recognition workspace.'
        return 5
    }
    trap 'rm -rf "$work_dir"' RETURN

    local text=''
    local ocr_error=''
    local ocr_status=0
    text="$(tesseract "$image" stdout -l eng --psm 3 2>"$work_dir/tesseract.err")" || ocr_status=$?
    ocr_error="$(<"$work_dir/tesseract.err")"

    # ZBar is additive: OCR remains useful when the optional code reader is
    # absent. The first symbol is surfaced because the result sheet is designed
    # for one deliberate screen selection, not bulk barcode inventory.
    local code_line=''
    local code_type=''
    local code_value=''
    if command -v zbarimg >/dev/null 2>&1; then
        code_line="$(zbarimg --quiet "$image" 2>/dev/null | sed -n '1p')"
        if [[ -n "$code_line" ]]; then
            code_type="${code_line%%:*}"
            code_value="${code_line#*:}"
        fi
    fi

    if ((ocr_status != 0)) && [[ -z "$code_value" ]]; then
        [[ -n "$ocr_error" ]] || ocr_error='Tesseract could not read the captured image.'
        json_error "$ocr_error"
        return 6
    fi

    jq -cn \
        --arg text "$text" \
        --arg codeType "$code_type" \
        --arg codeValue "$code_value" \
        '{ok: true, text: $text, codeType: $codeType, codeValue: $codeValue, error: ""}'
}

case "${1:-}" in
    probe)
        json_probe
        ;;
    analyze-file)
        analyze_file "${2:-}"
        ;;
    *)
        json_error 'Usage: screen-intelligence probe | analyze-file IMAGE'
        exit 64
        ;;
esac
