#!/usr/bin/env python3
"""
extract_pattern.py
Extrae el texto de la línea que contiene el rectángulo seleccionado por el usuario.
Retorna JSON con texto_monto y/o texto_fecha, que PHP usa para aprender patrones.

Uso: python3 extract_pattern.py <img_path> <rect_monto_json|null> <rect_fecha_json|null>
Coords normalizadas 0-1: {"x1":0.1,"y1":0.2,"x2":0.5,"y2":0.3}
"""
import sys, json
import pytesseract
from PIL import Image


def get_band_text(img, rect_norm):
    """
    Extrae texto de una banda horizontal completa (ancho = 100%) en el rango Y
    del rectángulo seleccionado + padding. Así captura la etiqueta que precede
    al valor aunque quede fuera del rectángulo.
    """
    if not rect_norm:
        return ''

    w, h = img.size
    y1 = rect_norm['y1'] * h
    y2 = rect_norm['y2'] * h

    # Padding vertical generoso para no cortar texto
    pad = max(int((y2 - y1) * 1.0), 20)
    y1_band = max(0, int(y1) - pad)
    y2_band = min(h, int(y2) + pad)

    band = img.crop((0, y1_band, w, y2_band))

    # PSM 6 = bloque uniforme; PSM 7 = línea única
    text = pytesseract.image_to_string(band, config='--oem 3 --psm 6 -l spa+eng').strip()
    if len(text) < 3:
        text = pytesseract.image_to_string(band, config='--oem 3 --psm 7 -l spa+eng').strip()

    return text


def main():
    if len(sys.argv) < 4:
        print(json.dumps({'error': 'Argumentos insuficientes'}))
        sys.exit(1)

    img_path   = sys.argv[1]
    raw_monto  = sys.argv[2]
    raw_fecha  = sys.argv[3]

    rect_monto = json.loads(raw_monto) if raw_monto != 'null' else None
    rect_fecha = json.loads(raw_fecha) if raw_fecha != 'null' else None

    try:
        img = Image.open(img_path)
    except Exception as e:
        print(json.dumps({'error': f'No se pudo abrir imagen: {e}'}))
        sys.exit(1)

    result = {}

    if rect_monto:
        result['texto_monto'] = get_band_text(img, rect_monto)

    if rect_fecha:
        result['texto_fecha'] = get_band_text(img, rect_fecha)

    print(json.dumps(result, ensure_ascii=False))


if __name__ == '__main__':
    main()
