# -*- coding: utf-8 -*-
"""
analizador_gui.py
Herramienta con Interfaz Gráfica (GUI) para Inspección y Verificación de Códigos de Barras y QR (GS1-128 / EAN-13 / QR).
Diseñada para ser compilada como .EXE autónomo para cualquier usuario.
"""

import sys
import os
import re
import cv2
import zxingcpp
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk, ImageGrab

# Colores Corporativos y UI Moderna
COLOR_PRIMARY = "#A12B2D"      # Rojo Corporativo Raúl Asencio
COLOR_PRIMARY_HOVER = "#852123"
COLOR_BG = "#F4F6F9"
COLOR_CARD_BG = "#FFFFFF"
COLOR_SUCCESS = "#2E7D32"
COLOR_SUCCESS_BG = "#E8F5E9"
COLOR_DANGER = "#C62828"
COLOR_DANGER_BG = "#FFEBEE"
COLOR_WARNING = "#EF6C00"
COLOR_WARNING_BG = "#FFF3E0"
COLOR_TEXT = "#212121"
COLOR_MUTED = "#616161"
COLOR_BORDER = "#CFD8DC"

class AnalizadorGS1App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Analizador e Inspector de Códigos de Barras GS1 / QR - Raúl Asencio")
        self.geometry("960x780")
        self.minsize(800, 650)
        self.configure(bg=COLOR_BG)

        # Configurar icono si existe
        self._init_styles()
        self._build_ui()

    def _init_styles(self):
        self.style = ttk.Style(self)
        self.style.theme_use("clam")

        # Configurar estilos de widgets
        self.style.configure(".", background=COLOR_BG, font=("Segoe UI", 10))
        self.style.configure("TNotebook", background=COLOR_BG, tabmargins=[4, 4, 4, 0])
        self.style.configure("TNotebook.Tab", background="#E0E0E0", foreground=COLOR_TEXT, padding=[16, 8], font=("Segoe UI", 10, "bold"))
        self.style.map("TNotebook.Tab", background=[("selected", COLOR_CARD_BG)], foreground=[("selected", COLOR_PRIMARY)])

        self.style.configure("Card.TFrame", background=COLOR_CARD_BG, relief="solid", borderwidth=1)
        self.style.configure("Danger.TLabel", background=COLOR_DANGER_BG, foreground=COLOR_DANGER, font=("Segoe UI", 10, "bold"), padding=8)
        self.style.configure("Success.TLabel", background=COLOR_SUCCESS_BG, foreground=COLOR_SUCCESS, font=("Segoe UI", 10, "bold"), padding=8)
        self.style.configure("Warning.TLabel", background=COLOR_WARNING_BG, foreground=COLOR_WARNING, font=("Segoe UI", 10, "bold"), padding=8)

    def _build_ui(self):
        # Cabecera
        header_frame = tk.Frame(self, bg=COLOR_PRIMARY, height=70)
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)

        lbl_title = tk.Label(header_frame, text="🔍 INSPECTOR Y VERIFICADOR DE CÓDIGOS GS1-128 / QR",
                             bg=COLOR_PRIMARY, fg="white", font=("Segoe UI", 14, "bold"))
        lbl_title.pack(anchor="w", padx=20, pady=(12, 2))

        lbl_sub = tk.Label(header_frame, text="Verificación de cumplimiento GS1, Identificadores AIM, detección de bytes parásitos (BOM/ZWNBSP) y paréntesis",
                           bg=COLOR_PRIMARY, fg="#FCE4EC", font=("Segoe UI", 9))
        lbl_sub.pack(anchor="w", padx=20)

        # Contenedor Principal con pestañas
        main_container = tk.Frame(self, bg=COLOR_BG)
        main_container.pack(fill=tk.BOTH, expand=True, padx=15, pady=10)

        notebook = ttk.Notebook(main_container)
        notebook.pack(fill=tk.BOTH, expand=True)

        # Pestaña 1: Escanear con Pistola o Pegar Texto
        tab_scanner = tk.Frame(notebook, bg=COLOR_BG)
        notebook.add(tab_scanner, text="  🔫 Lectura de Pistola / Texto  ")
        self._build_tab_scanner(tab_scanner)

        # Pestaña 2: Cargar Imagen de Etiqueta / Código
        tab_image = tk.Frame(notebook, bg=COLOR_BG)
        notebook.add(tab_image, text="  🖼️ Analizar Imagen de Etiqueta  ")
        self._build_tab_image(tab_image)

        # Barra de estado inferior
        status_bar = tk.Frame(self, bg="#E0E0E0", height=26)
        status_bar.pack(fill=tk.X, side=tk.BOTTOM)
        lbl_info = tk.Label(status_bar, text="Raúl Asencio Pastelerías · Norma GS1 General Specifications · ISO/IEC 15424",
                            bg="#E0E0E0", fg=COLOR_MUTED, font=("Segoe UI", 8))
        lbl_info.pack(side=tk.LEFT, padx=10)

    def _build_tab_scanner(self, parent):
        card = tk.Frame(parent, bg=COLOR_CARD_BG, relief="solid", borderwidth=1, padx=15, pady=12)
        card.pack(fill=tk.X, padx=5, pady=(10, 5))

        lbl_instr = tk.Label(card, text="Dispara con tu pistola lectora en el campo o pega una lectura directamente (Ctrl+V):",
                             bg=COLOR_CARD_BG, fg=COLOR_TEXT, font=("Segoe UI", 10, "bold"))
        lbl_instr.pack(anchor="w", pady=(0, 6))

        input_frame = tk.Frame(card, bg=COLOR_CARD_BG)
        input_frame.pack(fill=tk.X)

        self.txt_input = tk.Entry(input_frame, font=("Consolas", 12), relief="solid", borderwidth=1)
        self.txt_input.pack(side=tk.LEFT, fill=tk.X, expand=True, ipady=4, padx=(0, 10))
        self.txt_input.bind("<Return>", lambda e: self._on_analyze_text())
        self.txt_input.focus_set()

        btn_analyze = tk.Button(input_frame, text="🔍 Analizar", bg=COLOR_PRIMARY, fg="white",
                                font=("Segoe UI", 10, "bold"), relief="flat", padx=15, pady=4, cursor="hand2",
                                command=self._on_analyze_text)
        btn_analyze.pack(side=tk.LEFT, padx=(0, 6))

        btn_paste = tk.Button(input_frame, text="📋 Pegar", bg="#ECEFF1", fg=COLOR_TEXT,
                              font=("Segoe UI", 9), relief="solid", borderwidth=1, padx=10, pady=4, cursor="hand2",
                              command=self._on_paste_text)
        btn_paste.pack(side=tk.LEFT, padx=(0, 6))

        btn_clear = tk.Button(input_frame, text="🗑️ Limpiar", bg="#ECEFF1", fg=COLOR_TEXT,
                              font=("Segoe UI", 9), relief="solid", borderwidth=1, padx=10, pady=4, cursor="hand2",
                              command=self._on_clear_text)
        btn_clear.pack(side=tk.LEFT)

        # Panel de Resultados
        self._build_results_panel(parent, is_tab_scanner=True)

    def _build_tab_image(self, parent):
        card = tk.Frame(parent, bg=COLOR_CARD_BG, relief="solid", borderwidth=1, padx=15, pady=12)
        card.pack(fill=tk.X, padx=5, pady=(10, 5))

        lbl_instr = tk.Label(card, text="Carga una imagen de etiqueta (JPG, PNG, BMP) o pega una captura del portapapeles:",
                             bg=COLOR_CARD_BG, fg=COLOR_TEXT, font=("Segoe UI", 10, "bold"))
        lbl_instr.pack(anchor="w", pady=(0, 8))

        btn_frame = tk.Frame(card, bg=COLOR_CARD_BG)
        btn_frame.pack(fill=tk.X)

        btn_open = tk.Button(btn_frame, text="📂 Abrir Archivo de Imagen...", bg=COLOR_PRIMARY, fg="white",
                             font=("Segoe UI", 10, "bold"), relief="flat", padx=16, pady=5, cursor="hand2",
                             command=self._on_open_image_file)
        btn_open.pack(side=tk.LEFT, padx=(0, 10))

        btn_paste_img = tk.Button(btn_frame, text="📋 Pegar Captura del Portapapeles", bg="#ECEFF1", fg=COLOR_TEXT,
                                  font=("Segoe UI", 9), relief="solid", borderwidth=1, padx=12, pady=5, cursor="hand2",
                                  command=self._on_paste_image)
        btn_paste_img.pack(side=tk.LEFT, padx=(0, 10))

        self.lbl_image_status = tk.Label(btn_frame, text="Sin imagen cargada", bg=COLOR_CARD_BG, fg=COLOR_MUTED, font=("Segoe UI", 9, "italic"))
        self.lbl_image_status.pack(side=tk.LEFT, padx=10)

        # Panel de Resultados de Imagen
        self._build_results_panel(parent, is_tab_scanner=False)

    def _build_results_panel(self, parent, is_tab_scanner=True):
        container = tk.Frame(parent, bg=COLOR_BG)
        container.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # Tarjetas de Semáforo / Diagnóstico rápido
        banner_frame = tk.Frame(container, bg=COLOR_BG)
        banner_frame.pack(fill=tk.X, pady=(0, 6))

        if is_tab_scanner:
            self.lbl_alert_bom = tk.Label(banner_frame, text="Estado ZWNBSP: Esperando lectura...",
                                          bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_bom.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))

            self.lbl_alert_paren = tk.Label(banner_frame, text="Estado Paréntesis: Esperando lectura...",
                                            bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_paren.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))

            self.lbl_alert_aim = tk.Label(banner_frame, text="Simbología / AIM: -",
                                          bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_aim.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 0))
        else:
            self.lbl_alert_bom_img = tk.Label(banner_frame, text="Estado ZWNBSP: Esperando imagen...",
                                              bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_bom_img.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 5))

            self.lbl_alert_paren_img = tk.Label(banner_frame, text="Estado Paréntesis: Esperando imagen...",
                                                bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_paren_img.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 5))

            self.lbl_alert_aim_img = tk.Label(banner_frame, text="Simbología / AIM: -",
                                              bg="#EEEEEE", fg=COLOR_MUTED, font=("Segoe UI", 9, "bold"), padx=10, pady=6)
            self.lbl_alert_aim_img.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(5, 0))

        # Cuadro de Texto de Diagnóstico Detallado
        txt_frame = tk.Frame(container, bg=COLOR_CARD_BG, relief="solid", borderwidth=1)
        txt_frame.pack(fill=tk.BOTH, expand=True)

        scroll_y = tk.Scrollbar(txt_frame, orient=tk.VERTICAL)
        scroll_y.pack(side=tk.RIGHT, fill=tk.Y)

        txt_widget = tk.Text(txt_frame, yscrollcommand=scroll_y.set, font=("Consolas", 10),
                             bg=COLOR_CARD_BG, fg=COLOR_TEXT, relief="flat", padx=12, pady=10)
        txt_widget.pack(fill=tk.BOTH, expand=True)
        scroll_y.config(command=txt_widget.yview)

        # Barra de botones del informe
        action_bar = tk.Frame(container, bg=COLOR_BG)
        action_bar.pack(fill=tk.X, pady=(6, 0))

        btn_copy = tk.Button(action_bar, text="📋 Copiar Informe de Diagnóstico al Portapapeles", bg="#ECEFF1",
                             fg=COLOR_TEXT, font=("Segoe UI", 9, "bold"), relief="solid", borderwidth=1, padx=12, pady=3,
                             cursor="hand2", command=lambda: self._on_copy_report(txt_widget))
        btn_copy.pack(side=tk.RIGHT)

        if is_tab_scanner:
            self.txt_report_scanner = txt_widget
        else:
            self.txt_report_img = txt_widget

    # --- Acciones de la Interfaz ---

    def _on_paste_text(self):
        try:
            clipboard = self.clipboard_get()
            self.txt_input.delete(0, tk.END)
            self.txt_input.insert(0, clipboard)
            self._on_analyze_text()
        except Exception as e:
            messagebox.showwarning("Portapapeles", "No se encontró texto en el portapapeles.")

    def _on_clear_text(self):
        self.txt_input.delete(0, tk.END)
        self.txt_report_scanner.delete("1.0", tk.END)
        self.lbl_alert_bom.config(text="Estado ZWNBSP: Esperando lectura...", bg="#EEEEEE", fg=COLOR_MUTED)
        self.lbl_alert_paren.config(text="Estado Paréntesis: Esperando lectura...", bg="#EEEEEE", fg=COLOR_MUTED)
        self.lbl_alert_aim.config(text="Simbología / AIM: -", bg="#EEEEEE", fg=COLOR_MUTED)

    def _on_analyze_text(self):
        raw_text = self.txt_input.text = self.txt_input.get().strip()
        if not raw_text:
            messagebox.showinfo("Analizador", "Por favor, introduce o escanea una cadena de código de barras.")
            return

        raw_bytes = list(raw_text.encode("utf-8"))
        self._render_diagnostic(self.txt_report_scanner, self.lbl_alert_bom,
                                self.lbl_alert_paren, self.lbl_alert_aim,
                                raw_bytes, raw_text, "")

    def _on_open_image_file(self):
        file_path = filedialog.askopenfilename(
            title="Seleccionar imagen de etiqueta o código de barras",
            filetypes=[("Imágenes", "*.jpg *.jpeg *.png *.bmp *.webp *.tif *.tiff"), ("Todos los archivos", "*.*")]
        )
        if file_path:
            self.lbl_image_status.config(text=f"Archivo: {os.path.basename(file_path)}", fg=COLOR_PRIMARY)
            self._analyze_image_file(file_path)

    def _on_paste_image(self):
        try:
            img_clip = ImageGrab.grabclipboard()
            if img_clip and isinstance(img_clip, Image.Image):
                temp_path = os.path.join(os.environ.get("TEMP", "."), "_temp_clip_barcode.png")
                img_clip.save(temp_path)
                self.lbl_image_status.config(text="Captura pegada desde el portapapeles", fg=COLOR_PRIMARY)
                self._analyze_image_file(temp_path)
            else:
                messagebox.showinfo("Portapapeles", "No hay ninguna imagen en el portapapeles. Haz una captura con Win+Shift+S y pulsa este botón.")
        except Exception as e:
            messagebox.showerror("Error", f"Error al leer imagen del portapapeles: {e}")

    def _analyze_image_file(self, file_path):
        img = cv2.imread(file_path)
        if img is None:
            messagebox.showerror("Error", "No se pudo decodificar la imagen seleccionada.")
            return

        barcodes = zxingcpp.read_barcodes(img)
        if not barcodes:
            # Reintentar con escalado si la imagen es pequeña o baja resolución
            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:
            self.txt_report_img.delete("1.0", tk.END)
            self.txt_report_img.insert(tk.END, "❌ No se detectó ningún código de barras (1D) ni bidimensional (QR/DataMatrix) en la imagen.\n\nConsejos:\n - Asegúrate de que la foto esté enfocada y las barras no estén borrosas.\n - Para códigos lineales de alta densidad, prueba a recortar la zona exacta de las barras.")
            self.lbl_alert_bom_img.config(text="Sin códigos detectados", bg="#EEEEEE", fg=COLOR_MUTED)
            self.lbl_alert_paren_img.config(text="-", bg="#EEEEEE", fg=COLOR_MUTED)
            self.lbl_alert_aim_img.config(text="-", bg="#EEEEEE", fg=COLOR_MUTED)
            return

        # Renderizar cada código encontrado
        self.txt_report_img.delete("1.0", tk.END)
        for idx, b in enumerate(barcodes, 1):
            header = f"\n{'='*75}\n >>> CÓDIGO #{idx} DETECTADO: Formato = {b.format.name} | AIM ID = {b.symbology_identifier}\n{'='*75}\n"
            self.txt_report_img.insert(tk.END, header)
            raw_bytes = list(b.bytes)
            self._render_diagnostic(self.txt_report_img, self.lbl_alert_bom_img,
                                    self.lbl_alert_paren_img, self.lbl_alert_aim_img,
                                    raw_bytes, b.text, b.symbology_identifier, append=(idx > 1))

    def _render_diagnostic(self, txt_widget, lbl_bom, lbl_paren, lbl_aim, raw_bytes, text, symbology_id="", append=False):
        if not append:
            txt_widget.delete("1.0", tk.END)

        # 1. Comprobación de ZWNBSP (BOM UTF-8)
        tiene_bom = (len(raw_bytes) >= 3 and raw_bytes[0] == 0xEF and raw_bytes[1] == 0xBB and raw_bytes[2] == 0xBF) or text.startswith("\ufeff")
        if tiene_bom:
            lbl_bom.config(text="❌ ¡DETECTADO ZWNBSP (BOM UTF-8)!", bg=COLOR_DANGER_BG, fg=COLOR_DANGER)
        else:
            lbl_bom.config(text="✅ Sin BOM UTF-8 (ZWNBSP ausente)", bg=COLOR_SUCCESS_BG, fg=COLOR_SUCCESS)

        # 2. Comprobación de Paréntesis en datos físicos
        tiene_paren = (0x28 in raw_bytes) or (0x29 in raw_bytes)
        es_efecto_teclado_us = (")" in text and "=" in text and not tiene_bom) and re.search(r'\)\d{2}=', text)
        if es_efecto_teclado_us:
            lbl_paren.config(text="⚠️ ¡PISTOLA EN MODO TECLADO US / PARÉNTESIS ACTIVADOS!", bg=COLOR_WARNING_BG, fg=COLOR_WARNING)
        elif tiene_paren:
            lbl_paren.config(text="❌ ¡CONTIENE PARÉNTESIS FÍSICOS '()'!", bg=COLOR_DANGER_BG, fg=COLOR_DANGER)
        else:
            lbl_paren.config(text="✅ Sin paréntesis en datos físicos (Estándar GS1)", bg=COLOR_SUCCESS_BG, fg=COLOR_SUCCESS)

        # 3. Comprobación de AIM
        aim_desc = "-"
        if symbology_id:
            if symbology_id == "]C1":
                aim_desc = "]C1: GS1-128 (Correcto)"
                lbl_aim.config(text=aim_desc, bg=COLOR_SUCCESS_BG, fg=COLOR_SUCCESS)
            elif symbology_id == "]C0":
                aim_desc = "]C0: Code 128 Estándar (Sin FNC1)"
                lbl_aim.config(text=aim_desc, bg=COLOR_WARNING_BG, fg=COLOR_WARNING)
            elif symbology_id == "]Q1":
                aim_desc = "]Q1: Código QR Estándar"
                lbl_aim.config(text=aim_desc, bg="#E1F5FE", fg="#0277BD")
            elif symbology_id == "]Q3":
                aim_desc = "]Q3: Código QR GS1 (con FNC1)"
                lbl_aim.config(text=aim_desc, bg=COLOR_SUCCESS_BG, fg=COLOR_SUCCESS)
            elif symbology_id == "]E0":
                aim_desc = "]E0: EAN-13 Estándar"
                lbl_aim.config(text=aim_desc, bg="#E1F5FE", fg="#0277BD")
            else:
                aim_desc = symbology_id
                lbl_aim.config(text=f"AIM: {aim_desc}", bg="#EEEEEE", fg=COLOR_TEXT)

        # Generar texto del informe
        lines = []
        lines.append(f"• Texto decodificado  : {repr(text)}")
        lines.append(f"• Longitud total      : {len(raw_bytes)} bytes")
        if symbology_id:
            lines.append(f"• Identificador AIM   : {symbology_id} ({aim_desc})")

        lines.append("\n" + "="*75)
        lines.append(" EVALUACIÓN DE CUMPLIMIENTO GS1:")
        lines.append("="*75)
        if tiene_bom:
            lines.append(" [!] ALERTA CRÍTICA: Carácter ZWNBSP (Byte Order Mark UTF-8 / U+FEFF)")
            lines.append("     Los primeros 3 bytes son 0xEF 0xBB 0xBF. Esto hace que ERPs, lectores y")
            lines.append("     sistemas de almacén fallen al interpretar el código como datos corruptos.")
        else:
            lines.append(" [✓] OK: No se detecta ningún BOM UTF-8 (ZWNBSP ausente).")

        if tiene_paren:
            if es_efecto_teclado_us:
                lines.append(" [!] AVISO ESPECIAL (DIAGNÓSTICO DE LA PISTOLA):")
                lines.append("     Se ha detectado el patrón ')XX=' al disparar con la pistola.")
                lines.append("     CAUSA:")
                lines.append("       La pistola lectora está configurada de fábrica con emulación de 'TECLADO USA (US Keyboard)'")
                lines.append("       y tiene activada la opción de formateo para insertar paréntesis '(' y ')' en los IAs.")
                lines.append("       - Al emitir '(' (Shift+9 en teclado US), en Windows con teclado Español se escribe ')'.")
                lines.append("       - Al emitir ')' (Shift+0 en teclado US), en Windows con teclado Español se escribe '='.")
                lines.append("       Por eso la pistola escribe: ')01=...' en lugar de '(01)...' o '01...'.")
                lines.append("     SOLUCIÓN:")
                lines.append("       1) Configurar el idioma de teclado de la pistola en 'Spanish / Español' (escaneando el código")
                lines.append("          de barras correspondiente en el manual de la pistola).")
                lines.append("       2) O mejor aún: desactivar en la pistola el 'GS1 Application Identifier Formatting'")
                lines.append("          para que envíe los datos limpios estándar sin añadir paréntesis artificiales.")
            else:
                lines.append(" [!] ALERTA CRÍTICA: Paréntesis '(' o ')' (0x28 / 0x29) presentes en los datos físicos.")
                lines.append("     En la norma internacional GS1, los paréntesis son EXCLUSIVAMENTE para la lectura")
                lines.append("     humana (HRI) impresa. En las barras o módulos físicos se deben omitir.")
        else:
            lines.append(" [✓] OK: Los datos físicos no contienen paréntesis (0x28 / 0x29 ausentes).")
            lines.append("     Cumple con el estándar internacional GS1 (las barras/módulos codifican solo datos).")

        # Desglose de IAs GS1
        clean = text.lstrip("\ufeff")
        lines.append("\n" + "-"*75)
        lines.append(" IDENTIFICADORES DE APLICACIÓN (IAs) DETECTADOS:")
        lines.append("-" * 75)
        if clean.startswith("(") and "(01)" in clean:
            if tiene_paren:
                lines.append(" Forma de codificación física: CON PARÉNTESIS FÍSICOS (0x28/0x29) (NO RECOMENDADO)")
            else:
                lines.append(" Forma de codificación física: ESTÁNDAR GS1-128 (FNC1, sin paréntesis en barras)")
                lines.append(" (Nota: Los paréntesis mostrados abajo los formatea el decodificador para facilitar la lectura)")
            matches = re.findall(r'\((\d{2})\)([^\(]+)', clean)
            for ai, val in matches:
                if ai == "01": lines.append(f"  • (01) GTIN-14 del Producto  : {val}")
                elif ai == "17": lines.append(f"  • (17) Fecha Caducidad (AAMMDD): {val} -> 20{val[0:2]}/{val[2:4]}/{val[4:6]}")
                elif ai == "15": lines.append(f"  • (15) Consumo Preferente    : {val} -> 20{val[0:2]}/{val[2:4]}/{val[4:6]}")
                elif ai == "10": lines.append(f"  • (10) Número de Lote        : {val}")
                elif ai == "37": lines.append(f"  • (37) Cantidad de Unidades  : {val}")
                else: lines.append(f"  • ({ai}) IA Desconocido        : {val}")
        elif clean.startswith("01") and len(clean) >= 16:
            lines.append(" Forma de codificación: PURA SIN PARÉNTESIS (ESTÁNDAR CORRECTO GS1)")
            gtin = clean[2:16]
            resto = clean[16:]
            lines.append(f"  • IA 01 GTIN-14 del Producto : {gtin}")
            if (resto.startswith("17") or resto.startswith("15")) and len(resto) >= 8:
                tipo_cad = "Caducidad (17)" if resto.startswith("17") else "Consumo Pref. (15)"
                cad = resto[2:8]
                lote_raw = resto[8:]
                lines.append(f"  • IA {tipo_cad}: {cad} -> 20{cad[0:2]}/{cad[2:4]}/{cad[4:6]}")
                if lote_raw.startswith("10"):
                    lines.append(f"  • IA 10 Número de Lote       : {lote_raw[2:]}")
                elif lote_raw:
                    lines.append(f"  • Resto de datos             : {lote_raw}")
        else:
            lines.append("  (No se reconoce una estructura estándar GS1 AI 01 al inicio de la cadena)")

        # Desglose Byte a Byte
        lines.append("\n" + "-"*75)
        lines.append(" DESGLOSE BYTE A BYTE (HEX / DECIMAL / CARÁCTER):")
        lines.append("-" * 75)
        hex_str = " ".join(f"{b:02X}" for b in raw_bytes)
        lines.append(f"Secuencia HEX: {hex_str}\n")

        for i, b in enumerate(raw_bytes, 1):
            if b == 0x1D: desc = "<FNC1 / GS Separador (0x1D)>"
            elif b == 0x0D: desc = "<CR / Retorno de carro (0x0D)>"
            elif b == 0x0A: desc = "<LF / Salto de línea (0x0A)>"
            elif b == 0x20: desc = "<ESPACIO (0x20)>"
            elif b == 0x28: desc = "'(' (0x28) [¡Paréntesis de apertura!]"
            elif b == 0x29: desc = "')' (0x29) [¡Paréntesis de cierre!]"
            elif b == 0xEF or b == 0xBB or b == 0xBF: desc = f"<0x{b:02X}> [Byte componente de BOM UTF-8]"
            elif 32 <= b <= 126: desc = f"'{chr(b)}'"
            else: desc = f"<0x{b:02X}>"
            lines.append(f" [{i:02d}] 0x{b:02X} ({b:03d}) -> {desc}")

        txt_widget.insert(tk.END, "\n".join(lines) + "\n")

    def _on_copy_report(self, txt_widget):
        report = txt_widget.get("1.0", tk.END).strip()
        if report:
            self.clipboard_clear()
            self.clipboard_append(report)
            messagebox.showinfo("Copiado", "Informe de diagnóstico copiado al portapapeles con éxito.")
        else:
            messagebox.showinfo("Copiar", "No hay ningún informe para copiar.")

def main():
    app = AnalizadorGS1App()
    app.mainloop()

if __name__ == "__main__":
    main()

