#!/usr/bin/env python3
"""
Decodifica el QR de una factura/boleta desde una imagen usando OpenCV.
Uso: python qr_decode.py <ruta_imagen>
Imprime el texto del QR en stdout (vacío si no encuentra).

Requiere: opencv-python-headless (cv2). Best-effort: es un fallback del decoder PHP,
mejor localizando QRs chicos/ruidosos en fotos. Si cv2 no está, sale sin imprimir.
"""
import sys

def main():
    if len(sys.argv) < 2:
        return
    try:
        import cv2
    except Exception:
        return
    img = cv2.imread(sys.argv[1])
    if img is None:
        return

    det = cv2.QRCodeDetector()
    data = ''

    try:
        data, _, _ = det.detectAndDecode(img)
    except Exception:
        data = ''

    if not data:
        try:
            ok, infos, _, _ = det.detectAndDecodeMulti(img)
            if ok:
                for s in infos:
                    if s:
                        data = s
                        break
        except Exception:
            pass

    if not data:
        try:
            g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            for scale in (1.5, 2.0, 0.7):
                gg = cv2.resize(g, None, fx=scale, fy=scale)
                d2, _, _ = det.detectAndDecode(gg)
                if d2:
                    data = d2
                    break
        except Exception:
            pass

    if data:
        sys.stdout.write(data)


if __name__ == "__main__":
    main()
