Spaces:
Sleeping

File size: 22,261 Bytes
27668fc
d8dc99e
5bab0e1
c026a8e
 
3c623b2
c026a8e
 
 
3c623b2
88034dc
 
c026a8e
 
 
 
 
 
 
 
 
1976e2e
 
c026a8e
1976e2e
c026a8e
 
d914408
a347233
88034dc
a347233
 
 
88034dc
c026a8e
 
88034dc
 
 
 
 
c026a8e
 
 
 
 
 
 
 
 
88034dc
c026a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a347233
 
88034dc
 
 
 
 
c026a8e
 
 
 
88034dc
 
 
 
 
 
 
 
 
 
 
 
 
c026a8e
88034dc
c026a8e
 
88034dc
 
 
c026a8e
88034dc
c026a8e
88034dc
 
 
c026a8e
 
5154d37
88034dc
5154d37
88034dc
5154d37
 
 
 
c026a8e
88034dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c026a8e
 
 
 
 
 
 
 
88034dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c026a8e
 
 
 
 
2648ae8
e285e3c
c026a8e
88034dc
 
 
 
 
 
 
 
 
 
 
 
 
 
27668fc
88034dc
 
 
 
 
a347233
88034dc
 
 
 
 
 
 
 
c026a8e
88034dc
c026a8e
88034dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27668fc
88034dc
27668fc
c026a8e
 
 
88034dc
c026a8e
 
27668fc
c026a8e
 
 
 
 
 
ff448ff
c026a8e
ff448ff
 
 
 
6439e13
 
ff448ff
 
 
 
 
6439e13
 
 
 
ff448ff
6439e13
88034dc
ff448ff
 
6439e13
ff448ff
 
 
 
 
 
6439e13
 
ff448ff
6439e13
ff448ff
6439e13
 
 
 
 
 
 
 
 
 
 
 
ff448ff
c026a8e
 
6439e13
d914408
 
 
 
6439e13
 
 
 
 
d914408
 
 
 
6439e13
 
a347233
6439e13
27668fc
 
a347233
 
6439e13
27668fc
a347233
 
27668fc
 
 
6439e13
 
27668fc
a347233
 
 
6439e13
a347233
 
6439e13
 
a347233
6439e13
 
 
 
 
 
 
 
 
 
 
8e8e1c3
27668fc
23fbbf8
 
a347233
 
 
27668fc
 
a347233
 
6439e13
a347233
 
 
 
 
 
 
 
 
 
 
 
 
27668fc
a347233
 
 
 
27668fc
 
a347233
 
27668fc
 
e3abbc5
27668fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3abbc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27668fc
 
e3abbc5
 
27668fc
 
 
 
e3abbc5
 
 
 
 
 
 
27668fc
d73d47b
27668fc
 
 
d73d47b
27668fc
d73d47b
27668fc
 
 
d73d47b
 
 
 
 
 
 
 
 
 
 
 
27668fc
 
 
 
 
 
 
0d969e0
27668fc
b0651d1
1a28fda
27668fc
772a0ba
b0651d1
27668fc
 
 
 
 
5d49488
27668fc
b0651d1
27668fc
 
 
 
5d49488
27668fc
b0651d1
5d49488
 
1a28fda
27668fc
5d49488
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a28fda
 
0d969e0
5d49488
 
 
 
0d969e0
b0651d1
5d49488
1a28fda
5d49488
 
 
b0651d1
1a28fda
5d49488
1a28fda
 
 
 
 
5d49488
 
a347233
27668fc
 
 
 
 
41ba79a
27668fc
 
41ba79a
27668fc
 
 
41ba79a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27668fc
 
 
 
 
8e8e1c3
27668fc
 
 
8e8e1c3
27668fc
a347233
27668fc
 
 
 
 
 
 
 
 
8e8e1c3
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# app.py - PARTE 1
import streamlit as st
import pandas as pd
import numpy as np
import sqlite3
import os
from datetime import datetime
import matplotlib.pyplot as plt
from io import BytesIO
import hashlib
import smtplib
from email.mime.text import MIMEText

# ---------------- CONFIG ----------------
DB_PATH = "data/filtros.db"
REPORTS_DIR = "data/reports"
BACKUP_DIR = "data/backups"
os.makedirs("data", exist_ok=True)
os.makedirs(REPORTS_DIR, exist_ok=True)
os.makedirs(BACKUP_DIR, exist_ok=True)

CAPACIDAD_CARBON_G = 1.8 * 1000 * 1000  # gramos de carbón por filtro
CAPACIDAD_ADSORB_G_PER_G = 0.35        # antes 0.15, ahora 0.35 g H2S/g carbón
CAPACIDAD_POR_FILTRO_G = CAPACIDAD_CARBON_G * CAPACIDAD_ADSORB_G_PER_G

UMBRAL_PPM = 10.0

# Optional SMTP config for email alerts:
SMTP_HOST = os.environ.get("SMTP_HOST", "")     
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587") or 587)
SMTP_USER = os.environ.get("SMTP_USER", "")     
SMTP_PASS = os.environ.get("SMTP_PASS", "")     
ALERT_TO = os.environ.get("ALERT_TO", "")       

# ---------------- DB UTIL ----------------
def get_conn():
    conn = sqlite3.connect(DB_PATH, check_same_thread=False)
    return conn

def hash_pwd(pwd: str):
    return hashlib.sha256(pwd.encode()).hexdigest()

def init_db():
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE,
        fullname TEXT,
        password TEXT
    )""")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS records (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        filter_id INTEGER,
        timestamp TEXT,
        date TEXT,
        caudal REAL,
        h2s_in REAL,
        h2s_out REAL,
        user_id INTEGER
    )""")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS backups (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        timestamp TEXT,
        description TEXT,
        payload TEXT
    )""")
    conn.commit()

    # ensure admin exists
    cur.execute("SELECT COUNT(*) FROM users WHERE username='admin'")
    if cur.fetchone()[0] == 0:
        cur.execute("INSERT INTO users (username, fullname, password) VALUES (?,?,?)",
                    ("admin", "Administrador", hash_pwd("admin")))
        conn.commit()
    conn.close()

init_db()

# ---------------- USER FUNCTIONS ----------------
def add_user(username, fullname, password):
    conn = get_conn()
    cur = conn.cursor()
    try:
        cur.execute("INSERT INTO users (username, fullname, password) VALUES (?, ?, ?)",
                    (username, fullname, hash_pwd(password)))
        conn.commit()
        return True, "Usuario creado"
    except Exception as e:
        return False, str(e)
    finally:
        conn.close()

def reset_password(username, new_password):
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("UPDATE users SET password=? WHERE username=?",
                (hash_pwd(new_password), username))
    conn.commit()
    conn.close()
    return True

def delete_user(username):
    if username == "admin":
        return False, "No se puede eliminar el admin"
    conn = get_conn()
    cur = conn.cursor()
    try:
        cur.execute("DELETE FROM users WHERE username=?", (username,))
        conn.commit()
        return True, f"Usuario {username} eliminado"
    except Exception as e:
        return False, str(e)
    finally:
        conn.close()

def authenticate(username, password):
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("SELECT id, username, fullname, password FROM users WHERE username=?", (username,))
    row = cur.fetchone()
    conn.close()
    if not row:
        return None
    if hash_pwd(password) == row[3]:
        return {"id": row[0], "username": row[1], "fullname": row[2]}
    return None

def list_users():
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("SELECT username, fullname FROM users ORDER BY username")
    rows = cur.fetchall()
    conn.close()
    return rows

# ---------------- HELPERS (cálculos) ----------------
def ppm_to_g_m3(ppm):
    return ppm * 0.00152

def calc_load_captured_g(h2s_in_ppm, h2s_out_ppm, caudal_m3h):
    removed_ppm = max(h2s_in_ppm - h2s_out_ppm, 0)
    removed_g_m3 = ppm_to_g_m3(removed_ppm)
    return removed_g_m3 * caudal_m3h

# ---------------- EMAIL ALERT (opcional) ----------------
def send_email_alert(subject, body):
    if not (SMTP_HOST and SMTP_USER and SMTP_PASS and ALERT_TO):
        return False, "SMTP no configurado"
    try:
        msg = MIMEText(body)
        msg["Subject"] = subject
        msg["From"] = SMTP_USER
        msg["To"] = ALERT_TO
        s = smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=10)
        s.starttls()
        s.login(SMTP_USER, SMTP_PASS)
        s.sendmail(SMTP_USER, [ALERT_TO], msg.as_string())
        s.quit()
        return True, "Enviado"
    except Exception as e:
        return False, str(e)

# ---------------- UI: Auth ----------------
st.set_page_config(page_title="Filtros EPM", layout="wide")
if "logged" not in st.session_state:
    st.session_state.logged = False
if "user" not in st.session_state:
    st.session_state.user = None

def login_panel():
    st.header("Acceso - Filtros EPM")
    col1, col2 = st.columns([2,1])
    with col1:
        st.subheader("Iniciar sesión")
        username = st.text_input("Usuario", key="login_user")
        password = st.text_input("Contraseña", type="password", key="login_pass")
        if st.button("Entrar"):
            user = authenticate(username, password)
            if user:
                st.session_state.logged = True
                st.session_state.user = user
                st.success(f"Bienvenido, {user['fullname'] or user['username']}")
                st.experimental_rerun()
            else:
                st.error("Usuario o contraseña incorrectos")

# ---------------- UI: Admin ----------------
def admin_panel_ui():
    st.sidebar.subheader("Admin - Gestión de usuarios")
    st.sidebar.write("Usuario conectado: *admin*")
    st.sidebar.markdown("---")

    st.sidebar.markdown("### ➕ Crear usuario")
    new_user = st.sidebar.text_input("Usuario nuevo", key="admin_new_user")
    new_full = st.sidebar.text_input("Nombre completo", key="admin_new_full")
    new_pass = st.sidebar.text_input("Contraseña", type="password", key="admin_new_pass")
    if st.sidebar.button("Crear usuario", key="admin_create_btn"):
        ok, msg = add_user(new_user, new_full, new_pass)
        if ok:
            st.sidebar.success(msg)
        else:
            st.sidebar.error(f"Error: {msg}")

    st.sidebar.markdown("---")
    st.sidebar.markdown("### 🔑 Resetear contraseña")
    rp_user = st.sidebar.selectbox("Seleccionar usuario", [u[0] for u in list_users()], key="rp_select")
    rp_new = st.sidebar.text_input("Nueva contraseña", type="password", key="rp_new_pass")
    if st.sidebar.button("Resetear contraseña", key="admin_reset_btn"):
        if reset_password(rp_user, rp_new):
            st.sidebar.success(f"Contraseña de {rp_user} actualizada")
        else:
            st.sidebar.error("Error al resetear")

    st.sidebar.markdown("---")
    st.sidebar.markdown("### 🗑️ Eliminar usuario")
    del_user = st.sidebar.selectbox("Usuario a eliminar", [u[0] for u in list_users() if u[0] != "admin"], index=0, key="del_select")
    if st.sidebar.button("Eliminar usuario", key="admin_del_btn"):
        ok, msg = delete_user(del_user)
        if ok:
            st.sidebar.success(msg)
        else:
            st.sidebar.error(msg)
# app.py - PARTE 2

# ---------------- UI: Main (tus funcionalidades originales) ----------------
def sidebar_menu():
    st.sidebar.title("Menú")
    st.sidebar.write(f"Usuario: {st.session_state.user['username']}")
    page = st.sidebar.radio("Navegar", ["Dashboard", "Ingresar datos", "Resetear filtros", "Reportes", "Simulación", "Historial / Backups", "Salir"])
    return page

# ---- Dashboard, plots y cálculo de saturación ----
def dashboard():
    st.title("Dashboard - Estado de filtros")
    conn = get_conn()
    cur = conn.cursor()
    filtros = []
    for fid in range(1,5):
        cur.execute("SELECT caudal, h2s_in, h2s_out, timestamp FROM records WHERE filter_id=? ORDER BY id ASC", (fid,))
        rows = cur.fetchall()
        acumulado = 0.0
        last_h2s_out = 0.0
        times = []
        acumul_over_time = []
        saturado_flag = False  # nuevo flag

        if rows:
            for r in rows:
                acumulado += calc_load_captured_g(r[1], r[2], r[0])
                times.append(pd.to_datetime(r[3]))
                acumul_over_time.append(acumulado)
                # Si en cualquier registro se saturó, marcarlo
                if r[2] >= UMBRAL_PPM or acumulado >= CAPACIDAD_POR_FILTRO_G:
                    saturado_flag = True

            last_h2s_out = rows[-1][2]

        percent_used = round((acumulado / CAPACIDAD_POR_FILTRO_G) * 100, 1) if CAPACIDAD_POR_FILTRO_G>0 else 0
        days_left = "∞"
        prediction_days = None

        if rows:
            last = rows[-1]
            carga_hora = calc_load_captured_g(last[1], last[2], last[0])
            if carga_hora>0:
                hours_left = (CAPACIDAD_POR_FILTRO_G - acumulado) / carga_hora
                days_left = round(max(hours_left/24, 0),1)

        # Determinar estado del filtro
        status = "OK"
        if saturado_flag:
            status = "Saturado"
        elif percent_used >= 90:
            status = "Alerta"

        filtros.append({
            "id":fid,
            "percent_used":percent_used,
            "days_left":days_left,
            "status":status,
            "prediction_days":prediction_days,
            "last_h2s_out": last_h2s_out,
            "acumulado":acumulado
        })

    conn.close()

    # Mostrar métricas
    cols = st.columns(4)
    icons = {"OK":"🟢", "Alerta":"🟡", "Saturado":"🔴"}
    for i, f in enumerate(filtros):
        with cols[i]:
            st.metric(
                label=f"Filtro {f['id']} {icons.get(f['status'],'')}",
                value=f"{f['percent_used']}% usado",
                delta=f"{f['days_left']} días restantes"
            )
            if f['status']=="OK":
                st.success("OK")
            elif f['status']=="Alerta":
                st.warning("Alerta: cerca de 90%")
            else:  # Saturado
                st.error("🔴 Saturado (>10 ppm o capacidad máxima alcanzada)")

    # Curvas de saturación
    st.subheader("Curvas de saturación")
    fig = make_overall_plot_bars(filtros)
    st.pyplot(fig)


def make_overall_plot_bars(filtros):
    conn = get_conn()
    cur = conn.cursor()
    fig, ax = plt.subplots(figsize=(8,4))
    filtro_ids = [1,2,3,4]
    acumulados = []
    statuses = []

    for fid in filtro_ids:
        cur.execute("SELECT caudal, h2s_in, h2s_out FROM records WHERE filter_id=? ORDER BY id ASC", (fid,))
        rows = cur.fetchall()
        total = 0.0
        saturado_flag = False
        for r in rows:
            total += calc_load_captured_g(r[1], r[2], r[0])
            if r[2] >= UMBRAL_PPM or total >= CAPACIDAD_POR_FILTRO_G:
                saturado_flag = True
        acumulados.append(total/1000.0)  # kg
        statuses.append("Saturado" if saturado_flag else "OK")

    # Colores según estado
    colors = []
    for s in statuses:
        if s == "Saturado":
            colors.append("red")
        else:
            colors.append("green")

    bars = ax.bar([f"Filtro {i}" for i in filtro_ids], acumulados, color=colors)
    for bar, val in zip(bars, acumulados):
        ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(), f"{val:.2f} kg", ha='center', va='bottom')
    ax.axhline(CAPACIDAD_POR_FILTRO_G/1000.0, color='r', linestyle='--', 
           label=f'Capacidad filtro: {CAPACIDAD_POR_FILTRO_G/1000:.0f} kg')
    ax.set_ylabel('H2S acumulado (kg)')
    ax.set_title('Acumulado de H2S por filtro')
    ax.legend()
    ax.grid(True)
    conn.close()
    return fig


# ---- Ingreso de datos ----
def ingresar_datos_page():
    st.header("Ingresar datos de operación")
    with st.form("ingresar"):
        filtros_text = st.text_input("Filtros operando (ej: '1 3')")
        h2s_in = st.number_input("H2S entrada (ppm)", min_value=0.0, value=200.0)
        h2s_out = st.number_input("H2S salida (ppm)", min_value=0.0, value=1.0)
        caudal = st.number_input("Caudal total (Nm3/h)", min_value=0.0, value=600.0)
        submitted = st.form_submit_button("Guardar")
    if submitted:
        try:
            filtros = [int(x) for x in filtros_text.split()]
        except Exception:
            st.error("Formato de filtros inválido. Ej: '1 3' ")
            return
        conn = get_conn()
        cur = conn.cursor()
        for f in filtros:
            cur.execute("INSERT INTO records (filter_id, timestamp, date, caudal, h2s_in, h2s_out, user_id) VALUES (?,?,?,?,?,?,?)",
                        (f, datetime.utcnow().isoformat(), str(datetime.utcnow().date()), caudal/len(filtros), h2s_in, h2s_out, st.session_state.user['id']))
        conn.commit()
        conn.close()
        st.success("Datos guardados y memorizados por filtro.")

# ---- Reset de filtros (backup antes) ----
# ---- Reset de filtros (backup antes) ----
def reset_page():
    st.header("Resetear filtro(s) - respaldo antes de borrar")
    with st.form("reset"):
        filtros_text = st.text_input("Filtros a resetear (ej: '2 3')")
        confirm = st.checkbox("Confirmo generar backup y resetear estos filtros")
        submitted = st.form_submit_button("Resetear")
    if submitted:
        if not confirm:
            st.error("Marca la casilla de confirmación para proceder.")
            return
        try:
            filtros = [int(x) for x in filtros_text.split()]
        except Exception:
            st.error("Formato de filtros inválido. Ej: '2 3'")
            return
        conn = get_conn()
        cur = conn.cursor()
        combined = {}
        for f in filtros:
            cur.execute("SELECT timestamp, date, caudal, h2s_in, h2s_out, user_id FROM records WHERE filter_id=? ORDER BY id ASC", (f,))
            rows = cur.fetchall()
            combined[f] = [{"timestamp":r[0], "date":r[1], "caudal":r[2], "h2s_in":r[3], "h2s_out":r[4], "user_id":r[5]} for r in rows]

        # Crear DataFrame para Excel
        data_rows = []
        for fid, rows in combined.items():
            for r in rows:
                data_rows.append([fid, r['timestamp'], r['date'], r['caudal'], r['h2s_in'], r['h2s_out'], r['user_id']])
        df_backup = pd.DataFrame(data_rows, columns=["filter_id","timestamp","date","caudal","h2s_in","h2s_out","user_id"])

        # Guardar a Excel en memoria
        from io import BytesIO
        excel_buffer = BytesIO()
        with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer:
            df_backup.to_excel(writer, index=False, sheet_name="backup")
        excel_buffer.seek(0)

        # Guardar registro en la DB
        cur.execute("INSERT INTO backups (timestamp, description, payload) VALUES (?,?,?)",
                    (datetime.utcnow().isoformat(), f"Reset filtros {filtros} por {st.session_state.user['username']}", str(combined)))

        # Borrar datos de los filtros seleccionados
        for f in filtros:
            cur.execute("DELETE FROM records WHERE filter_id=?", (f,))
        conn.commit()
        conn.close()

        st.success(f"Backup generado para filtros {filtros} (Excel)")
        st.download_button(
            "Descargar backup (Excel)",
            data=excel_buffer,
            file_name=f"reset_backup_{''.join(map(str,filtros))}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
        )

# ---- Reportes y descargas ----
# ---- Reportes y descargas ----
def reportes_page():
    st.header("Reportes y descargas")
    
    st.subheader("Descargar estado actual (todos los filtros)")
    if st.button("Generar Excel estado actual"):
        conn = get_conn()
        df = pd.read_sql_query("SELECT * FROM records ORDER BY filter_id, id", conn)
        conn.close()

        excel_buffer = BytesIO()
        with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer:
            df.to_excel(writer, index=False, sheet_name="estado_actual")
        excel_buffer.seek(0)

        st.download_button(
            "Descargar Excel",
            data=excel_buffer,
            file_name=f"estado_actual_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
        )
    
    st.subheader("Descargar gráficos (PNG)")
    fig = make_overall_plot_bars([{"id":i} for i in range(1,5)])
    buf = BytesIO()
    fig.savefig(buf, format="png", bbox_inches="tight")
    buf.seek(0)
    st.download_button("Descargar gráfica PNG", data=buf, file_name=f"curva_saturacion_{datetime.utcnow().strftime('%Y%m%d')}.png")

# ---- Simulación ----
# ---- Simulación ----
# ---- Simulación corregida ----
# ---- Simulación ----
def simulacion_page():
    st.header("Simulación de escenario (desde cero)")

    with st.form("sim"):
        filtros_text = st.text_input("Filtros a simular (ej: '1 2')", value="1")
        h2s_in = st.number_input("H2S entrada (ppm)", min_value=0.0, value=200.0)
        h2s_out = st.number_input("H2S salida (ppm)", min_value=0.0, value=1.0)
        caudal = st.number_input("Caudal total (Nm3/h)", min_value=0.0, value=600.0)
        carbon_kg = st.number_input("Cantidad de carbón cargado por filtro (kg)", min_value=0.0, value=1800.0)
        submit = st.form_submit_button("Simular")

    if submit:
        try:
            filtros = [int(x) for x in filtros_text.split()]
        except Exception:
            st.error("Formato de filtros inválido.")
            return

        # Nuevo factor de absorción
        CAPACIDAD_ADSORB_G_PER_G = 0.35
        results = []
        for f in filtros:
            # Convertir carbón cargado a gramos y calcular capacidad total de H2S
            carbon_g = carbon_kg * 1000
            capacidad_h2s_g = carbon_g * CAPACIDAD_ADSORB_G_PER_G

            # Cálculo carga capturada por hora
            carga_hora_g = calc_load_captured_g(h2s_in, h2s_out, caudal / len(filtros))
            carga_hora_kg = carga_hora_g / 1000.0

            # Días y horas hasta saturación
            if carga_hora_kg > 0:
                hours_left = capacidad_h2s_g / carga_hora_g
                days_left = hours_left / 24
            else:
                hours_left = np.inf
                days_left = np.inf

            results.append({
                "Filtro": f,
                "Carga total tratada (kg)": round(capacidad_h2s_g / 1000.0, 2),
                "Carga capturada por hora (kg/h)": round(carga_hora_kg, 2),
                "Días hasta saturación": round(days_left, 2),
                "Horas hasta saturación": round(hours_left, 2)
            })

        # Mostrar resultados en texto
        for r in results:
            st.subheader(f"Filtro {r['Filtro']}")
            st.write(f"Carga total tratada: {r['Carga total tratada (kg)']} kg")
            st.write(f"Carga capturada por hora: {r['Carga capturada por hora (kg/h)']} kg/h")
            st.write(f"Días hasta saturación: {r['Días hasta saturación']} días ({r['Horas hasta saturación']} horas)")

        # Generar Excel descargable
        df = pd.DataFrame(results)
        output = BytesIO()
        with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
            df.to_excel(writer, index=False, sheet_name="Simulación")
        output.seek(0)
        st.download_button("Descargar resultados en Excel", data=output,
                           file_name=f"simulacion_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx")

# ---- Historial / Backups ----
def historial_page():
    st.header("Historial general (backups)")
    conn = get_conn()
    cur = conn.cursor()
    cur.execute("SELECT id, timestamp, description, payload FROM backups ORDER BY id DESC LIMIT 50")
    rows = cur.fetchall()
    conn.close()

    for r in rows:
        st.write(r[0], r[1], r[2])
        if st.button(f"Descargar backup {r[0]}", key=f"bk{r[0]}"):
            # Convertir payload (string de lista/dict) a DataFrame
            import ast
            try:
                payload_data = ast.literal_eval(r[3])
                records_list = []
                for fid, recs in payload_data.items():
                    for rec in recs:
                        records_list.append({
                            "filter_id": fid,
                            "timestamp": rec["timestamp"],
                            "date": rec["date"],
                            "caudal": rec["caudal"],
                            "h2s_in": rec["h2s_in"],
                            "h2s_out": rec["h2s_out"],
                            "user_id": rec["user_id"]
                        })
                df = pd.DataFrame(records_list)
            except Exception:
                st.error("Error al convertir el backup a DataFrame")
                continue

            # Crear buffer Excel
            excel_buffer = BytesIO()
            with pd.ExcelWriter(excel_buffer, engine='xlsxwriter') as writer:
                df.to_excel(writer, index=False, sheet_name=f"backup_{r[0]}")
            excel_buffer.seek(0)

            st.download_button(
                f"Descargar backup {r[0]} en Excel",
                data=excel_buffer,
                file_name=f"backup_{r[0]}.xlsx"
            )


# ---------------- App layout control ----------------
if not st.session_state.logged:
    login_panel()
else:
    page = sidebar_menu()
    if st.session_state.user and st.session_state.user.get('username') == 'admin':
        admin_panel_ui()
    if page == "Dashboard":
        dashboard()
    elif page == "Ingresar datos":
        ingresar_datos_page()
    elif page == "Resetear filtros":
        reset_page()
    elif page == "Reportes":
        reportes_page()
    elif page == "Simulación":
        simulacion_page()
    elif page == "Historial / Backups":
        historial_page()
    elif page == "Salir":
        st.session_state.logged = False
        st.session_state.user = None
        st.experimental_rerun()