# -*- coding: utf-8 -*-
"""
analizar_codigo_barras.py
Herramienta de inspección y análisis exhaustivo de códigos de barras (1D y 2D / GS1-128 / QR / DataMatrix / EAN-13).
Permite:
  1. Analizar imágenes de etiquetas o códigos de barras directamente desde archivo o portapapeles.
  2. Inspeccionar lecturas directas de lectores láser/2D USB.
  3. Desglosar byte a byte en formato HEX, ASCII y caracteres invisibles (BOM UTF-8, ZWNBSP, FNC1, GS, CR, LF).
  4. Validar el cumplimiento del estándar GS1 (presencia o ausencia indebida de paréntesis, identificadores de aplicación AI).
"""

import sys
import os
import cv2
import zxingcpp

def describir_byte(b):
    if b == 0x1D:
        return "<GS/FNC1 (0x1D)>"
    elif b == 0x0D:
        return "<CR (0x0D)>"
    elif b == 0x0A:
        return "<LF (0x0A)>"
    elif b == 0x09:
        return "<TAB (0x09)>"
    elif b == 0x20:
        return "<ESPACIO (0x20)>"
    elif 32 <= b <= 126:
        return f"'{chr(b)}' (0x{b:02X})"
    else:
        return f"<0x{b:02X}>"

def analizar_bytes(raw_bytes, text, symbology_id=""):
    print("=" * 70)
    print(" RESUMEN DE LA LECTURA DEL ESCÁNER")
    print("=" * 70)
    if symbology_id:
        print(f"[*] Identificador AIM (ISO/IEC 15424): {symbology_id}")
        if symbology_id == "]C1":
            print("    -> Significado: GS1-128 (Code 128 con FNC1 en 1ª posición). ¡Correcto para logística GS1 lineal!")
        elif symbology_id == "]C0":
            print("    -> Significado: Code 128 Estándar (SIN FNC1 en 1ª posición).")
        elif symbology_id == "]Q1":
            print("    -> Significado: Código QR Estándar (Modelo 2).")
        elif symbology_id == "]Q3":
            print("    -> Significado: Código QR en formato GS1 (con FNC1 inicial).")
        elif symbology_id == "]E0":
            print("    -> Significado: EAN-13 estándar.")
    
    print(f"[*] Longitud total: {len(raw_bytes)} bytes")
    print(f"[*] Texto decodificado: {repr(text)}")
    print("-" * 70)

    # 1. Detección de BOM UTF-8 (ZWNBSP)
    tiene_bom = len(raw_bytes) >= 3 and raw_bytes[0] == 0xEF and raw_bytes[1] == 0xBB and raw_bytes[2] == 0xBF
    tiene_zwnbsp_char = text.startswith("\ufeff")
    if tiene_bom or tiene_zwnbsp_char:
        print("[ALERTA CRÍTICA 1] ¡Carácter ZWNBSP (BOM UTF-8) DETECTADO!")
        print("  -> Los 3 primeros bytes son 0xEF 0xBB 0xBF (Byte Order Mark UTF-8 / U+FEFF).")
        print("  -> Esto NO debe estar en ningún código de barras ni QR estándar. Provoca fallos en ERPs y lectores.")
    else:
        print("[OK] Sin BOM UTF-8 (ZWNBSP ausente). Correcto.")

    # 2. Detección de Paréntesis
    tiene_parentesis = (0x28 in raw_bytes) or (0x29 in raw_bytes) or ("(" in text) or (")" in text)
    if tiene_parentesis:
        print("\n[ALERTA CRÍTICA 2] ¡PARÉNTESIS '(' o ')' CODIFICADOS EN LAS BARRAS/MÓDULOS!")
        print("  -> Los paréntesis NUNCA deben codificarse físicamente en los datos transmitidos.")
        print("  -> En la norma GS1, los paréntesis son ÚNICAMENTE para el texto legible impreso (HRI).")
        print("  -> En el código físico deben enviarse los identificadores puros: ej. 01...17...10...")
    else:
        print("[OK] Sin paréntesis en los datos codificados. Cumple el estándar GS1.")

    # 3. Desglose byte a byte
    print("\n" + "-" * 70)
    print(" DESGLOSE BYTE A BYTE (HEX / ASCII / CONTROL):")
    print("-" * 70)
    hex_list = " ".join(f"{b:02X}" for b in raw_bytes)
    print(f"HEX: {hex_list}\n")

    for idx, b in enumerate(raw_bytes):
        print(f" Pos {idx+1:02d}: 0x{b:02X} ({b:03d}) -> {describir_byte(b)}")

    # 4. Desglose de Identificadores de Aplicación GS1
    clean_text = text.lstrip("\ufeff")
    if clean_text.startswith("(") and clean_text.startswith("(01)"):
        # Formato con paréntesis erróneo
        print("\n" + "-" * 70)
        print(" ANÁLISIS DE IAs GS1 (DETECTADO FORMATO CON PARÉNTESIS FÍSICOS - NO RECOMENDADO):")
        print("-" * 70)
        # Parse simple
        import re
        matches = re.findall(r'\((\d{2})\)([^\(]+)', clean_text)
        for ai, val in matches:
            if ai == "01":
                print(f"  * IA (01) GTIN-14: '{val}'")
            elif ai == "17":
                print(f"  * IA (17) Fecha Caducidad (AAMMDD): '{val}'")
            elif ai == "15":
                print(f"  * IA (15) Fecha Consumo Preferente (AAMMDD): '{val}'")
            elif ai == "10":
                print(f"  * IA (10) Número de Lote: '{val}'")
            else:
                print(f"  * IA ({ai}): '{val}'")
    elif clean_text.startswith("01") and len(clean_text) >= 16:
        print("\n" + "-" * 70)
        print(" ANÁLISIS DE IAs GS1 ESTÁNDAR (PURA, SIN PARÉNTESIS - FORMATO CORRECTO):")
        print("-" * 70)
        gtin = clean_text[2:16]
        resto = clean_text[16:]
        print(f"  * IA 01 GTIN-14: {gtin}")
        if resto.startswith("17") and len(resto) >= 8:
            cad = resto[2:8]
            lote_raw = resto[8:]
            print(f"  * IA 17 Caducidad (AAMMDD): {cad} -> 20{cad[0:2]}/{cad[2:4]}/{cad[4:6]}")
            if lote_raw.startswith("10"):
                lote = lote_raw[2:]
                print(f"  * IA 10 Número de Lote: {lote}")
        elif resto.startswith("15") and len(resto) >= 8:
            cad = resto[2:8]
            lote_raw = resto[8:]
            print(f"  * IA 15 Consumo Pref. (AAMMDD): {cad} -> 20{cad[0:2]}/{cad[2:4]}/{cad[4:6]}")
            if lote_raw.startswith("10"):
                lote = lote_raw[2:]
                print(f"  * IA 10 Número de Lote: {lote}")
    print("=" * 70 + "\n")

def analizar_imagen(ruta_imagen):
    if not os.path.exists(ruta_imagen):
        print(f"Error: El archivo '{ruta_imagen}' no existe.")
        return

    print(f"\nAnalizando imagen: {ruta_imagen}")
    img = cv2.imread(ruta_imagen)
    if img is None:
        print("Error: No se pudo cargar la imagen.")
        return

    barcodes = zxingcpp.read_barcodes(img)
    if not barcodes:
        # Intentar con upscale / contraste si es pequeña
        h, w = img.shape[:2]
        if w < 600:
            scale = 600 / w
            resized = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_CUBIC)
            barcodes = zxingcpp.read_barcodes(resized)

    if not barcodes:
        print("No se detectó ningún código de barras o QR en la imagen.")
        return

    print(f"Se encontraron {len(barcodes)} código(s) en la imagen:\n")
    for i, b in enumerate(barcodes, 1):
        print(f">>> CÓDIGO #{i}: Formato={b.format.name} | Posición={b.position}")
        analizar_bytes(list(b.bytes), b.text, b.symbology_identifier)

def main():
    if len(sys.argv) > 1:
        ruta = sys.argv[1]
        analizar_imagen(ruta)
    else:
        print("=== ANALIZADOR DE CÓDIGOS DE BARRAS GS1-128 / QR / EAN ===")
        print("Modo de uso:")
        print("  1. Analizar imagen:   python scripts\\analizar_codigo_barras.py <ruta_imagen.jpg/png/bmp>")
        print("  2. Modo texto directo: Introduce una cadena o lectura de pistola para analizarla.")
        print("")
        try:
            linea = input("Pega o escanea aquí el código (o arrastra un archivo y pulsa Enter): ").strip().strip('"')
            if os.path.exists(linea):
                analizar_imagen(linea)
            elif linea:
                raw_bytes = [ord(c) for c in linea]
                analizar_bytes(raw_bytes, linea, "")
            else:
                print("No se introdujo ningún dato.")
        except (KeyboardInterrupt, EOFError):
            pass

if __name__ == "__main__":
    main()

