import sys
import datetime
import subprocess # <--- NUEVO: Para ejecutar comandos del sistema
import shutil     # <--- NUEVO: Para comprobar si existe hass-cli

# Argumentos: 1. Archivo de log (entrada), 2. Archivo HTML (salida)
if len(sys.argv) < 3:
    print("Uso: python3 generar_reporte.py <log_file> <html_file>")
    sys.exit(1)

log_file = sys.argv[1]
html_file = sys.argv[2]
fecha = datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")

try:
    with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
        lines = f.readlines()
except FileNotFoundError:
    print(f"No se encuentra el archivo de log: {log_file}")
    sys.exit(1)

# Contadores
added = 0
deleted = 0
modified = 0
errors = 0

log_html = []

# Cabecera HTML
html_content = [f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
    body {{ font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; background-color: #1c1c1c; color: #e1e1e1; padding: 15px; margin: 0; }}
    h2 {{ color: #03a9f4; border-bottom: 1px solid #444; padding-bottom: 10px; margin-top: 0; font-size: 1.2rem; }}
    .summary {{ display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; }}
    .card {{ background: #2c2c2c; padding: 10px; border-radius: 8px; flex: 1; min-width: 80px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.2); }}
    .number {{ font-size: 20px; font-weight: bold; display: block; margin-bottom: 4px; }}
    .label {{ font-size: 12px; opacity: 0.8; text-transform: uppercase; }}
    .log-container {{ background: #111; padding: 10px; border-radius: 8px; height: 500px; overflow-y: auto; font-family: 'Consolas', monospace; font-size: 13px; white-space: pre-wrap; border: 1px solid #333; }}
    .line {{ padding: 3px 5px; border-bottom: 1px solid #222; display: flex; align-items: flex-start; }}
    .line:last-child {{ border-bottom: none; }}
    .icon {{ margin-right: 8px; min-width: 20px; text-align: center; }}
    .text {{ word-break: break-all; }}
    .new {{ color: #4caf50; }}
    .del {{ color: #ef5350; }}
    .mod {{ color: #ff9800; }}
    .err {{ color: #ff5252; background-color: rgba(255, 82, 82, 0.1); }}
    ::-webkit-scrollbar {{ width: 8px; }}
    ::-webkit-scrollbar-track {{ background: #111; }}
    ::-webkit-scrollbar-thumb {{ background: #444; border-radius: 4px; }}
</style>
</head>
<body>

"""]
###  ESTO IBA JUSTO DETRAS DEL BODY:   <h2>Backup: {fecha}</h2>

# Procesar líneas
for line in lines:
    line_clean = line.strip()
    if not line_clean: continue
    
    css_class = ""
    icon = ""
    is_relevant = False

    # --- LÓGICA CORREGIDA (ORDEN DE PRIORIDAD) ---

    # 1. Ignoramos explícitamente las líneas que empiezan por punto "." 
    # (Son actualizaciones de atributos sin cambios de datos, ej: .f...pog...)
    if line_clean.startswith("."):
        continue

    # 2. Borrados (*deleting)
    if "deleting" in line_clean:
        css_class = "del"
        icon = "🗑️"
        deleted += 1
        is_relevant = True
        
    # 3. Nuevos (>f+++++++++)
    elif line_clean.startswith(">f+++++++++"):
        css_class = "new"
        icon = "✨"
        added += 1
        is_relevant = True

    # 4. Modificados (>f...)
    # Si empieza por >f pero no entra en el anterior, es modificado.
    # Al entrar aquí, YA EVITAMOS que se marque como error aunque se llame "error.log"
    elif line_clean.startswith(">f") or line_clean.startswith("c"): # 'c' porsiaca carpetas
        css_class = "mod"
        icon = "📝"
        modified += 1
        is_relevant = True

    # 5. Errores (SÓLO si no ha sido clasificado arriba)
    # Aquí caerán los mensajes reales de rsync tipo "rsync: read error..." 
    # o "failed to open..." que no tienen el código >f delante.
    elif "error" in line_clean.lower() or "failed" in line_clean.lower():
        css_class = "err"
        icon = "⚠️"
        errors += 1
        is_relevant = True

    # --- FIN LÓGICA ---

    if is_relevant:
        parts = line_clean.split(' ', 1)
        if len(parts) > 1:
            texto_archivo = parts[1]
            codigo_rsync = parts[0]
        else:
            texto_archivo = line_clean
            codigo_rsync = ""
        log_html.append(f'<div class="line {css_class}" title="{codigo_rsync}"><span class="icon">{icon}</span><span class="text">{texto_archivo}</span></div>')

if not log_html:
    log_html.append('<div class="line" style="color: #888; text-align: center; padding: 20px;">✅ Sin cambios. Todo sincronizado.</div>')

###html_content.append(f"""
###    <div class="summary">
###        <div class="card" style="border-top: 3px solid #4caf50;"><span class="number">{added}</span><span class="label">Nuevos</span></div>
###        <div class="card" style="border-top: 3px solid #ff9800;"><span class="number">{modified}</span><span class="label">Editados</span></div>
###        <div class="card" style="border-top: 3px solid #ef5350;"><span class="number">{deleted}</span><span class="label">Borrados</span></div>
###        <div class="card" style="border-top: 3px solid #ff5252;"><span class="number">{errors}</span><span class="label">Errores</span></div>
###    </div>
###    <div class="log-container">
###""")

html_content.extend(log_html)
html_content.append("</div></body></html>")

try:
    with open(html_file, 'w', encoding='utf-8') as f:
        f.write("".join(html_content))
    print(f"Reporte generado: {html_file}")
except Exception as e:
    print(f"Error escribiendo HTML: {e}")

# --- ENVIAR DATOS A HOME ASSISTANT ---
# Esta sección aprovecha que hass-cli ya está configurado en el entorno
print("Enviando estadísticas a Home Assistant...")

def update_ha_entity(entity_id, value):
    # Verificamos si hass-cli está disponible
    if shutil.which("hass-cli") is None:
        print("Aviso: hass-cli no encontrado en el PATH.")
        return

    try:
        # CORRECCIÓN DEFINITIVA: 
        # Usamos --arguments y pasamos "clave=valor,clave2=valor2" todo junto
        argumentos_str = f"entity_id={entity_id},value={value}"
        
        subprocess.run(
            [
                "hass-cli", "service", "call", "input_number.set_value",
                "--arguments", argumentos_str
            ],
            check=True,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.PIPE
        )
        print(f"  -> {entity_id}: {value}")
    except subprocess.CalledProcessError as e:
        print(f"  Error actualizando {entity_id}: {e.stderr.decode().strip()}")

# Llamamos a la función para cada contador
update_ha_entity("input_number.backup_files_new", added)
update_ha_entity("input_number.backup_files_modified", modified)
update_ha_entity("input_number.backup_files_deleted", deleted)
update_ha_entity("input_number.backup_errors", errors)
