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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
# Altius PumpAI™ — GD20 Monitor (Streamlit)
# Stable + persistent version (Windows / Linux / GCP friendly)
# Save this as: C:\AI-Kit\dashboard\app.py  (or wherever your dashboard folder is)

from __future__ import annotations

import os
import time
import sqlite3
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, Dict, Any, Tuple

import numpy as np
import pandas as pd
import streamlit as st

# Optional imports (keep app running even if these are missing)
try:
    from streamlit_autorefresh import st_autorefresh
except Exception:
    st_autorefresh = None

try:
    # pymodbus 3.x
    from pymodbus.client import ModbusSerialClient
except Exception:
    ModbusSerialClient = None


# =========================
# Paths / Branding / Project
# =========================
APP_DIR = Path(__file__).resolve().parent
BASE_DIR = APP_DIR.parent if APP_DIR.name.lower() == "dashboard" else APP_DIR

ASSETS_DIR = BASE_DIR / "assets"
DATA_DIR = BASE_DIR / "data"
DB_PATH = DATA_DIR / "gd20_history.sqlite3"
RAW_MOCK = DATA_DIR / "raw" / "pump_mock.csv"

LOGO_PATH = ASSETS_DIR / "altius_logo.png"

COMPANY_NAME = "Altius Surya Tech Pvt Ltd"
PRODUCT_TITLE = "Altius PumpAI™ — Energy Saver & Health Monitor for VFD Pumps"

PROJECT_LOCATION = "CSV Fountain"
PROJECT_ADDRESS = "CSV Swimming pool"
DRIVE_MODEL = "INVT GD20-1R5G-4-PV (2HP Solar Pump Drive-3Phase)"


# =========================
# Modbus settings (edit if needed)
# =========================
@dataclass
class ModbusCfg:
    port: str = os.environ.get("GD20_PORT", "COM3")          # Windows: COM3, Linux: /dev/ttyUSB0
    baud: int = int(os.environ.get("GD20_BAUD", "9600"))
    slave_id: int = int(os.environ.get("GD20_SLAVE", "1"))
    parity: str = os.environ.get("GD20_PARITY", "N")
    stopbits: int = int(os.environ.get("GD20_STOPBITS", "1"))
    bytesize: int = int(os.environ.get("GD20_BYTESIZE", "8"))
    timeout: float = float(os.environ.get("GD20_TIMEOUT", "1.0"))

CFG = ModbusCfg()

# NOTE: Replace these register addresses with your confirmed GD20 map.
# These are placeholders that you must verify against your GD20 manual / parameters.
REG_MAP = {
    "freq_hz": 0,     # example
    "current_a": 1,   # example
    "voltage_v": 2,   # example (output / bus depending on your mapping)
    "dc_bus_v": 3,    # example
    "fault_code": 4,  # example
}

# =========================
# UI styling (light blue background)
# =========================
LIGHT_BLUE_BG = """
<style>
    .stApp { background: #EAF4FF; }
    /* Make metric cards pop slightly */
    div[data-testid="stMetric"] {
        background: rgba(255,255,255,0.75);
        border-radius: 12px;
        padding: 10px 12px;
        border: 1px solid rgba(0,0,0,0.06);
    }
    /* Sidebar */
    section[data-testid="stSidebar"] {
        background: rgba(255,255,255,0.55);
    }
</style>
"""


# =========================
# Persistence (SQLite)
# =========================
def db_init() -> None:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
    (DATA_DIR / "raw").mkdir(parents=True, exist_ok=True)
    with sqlite3.connect(DB_PATH) as con:
        con.execute(
            """
            CREATE TABLE IF NOT EXISTS samples (
                ts_utc TEXT PRIMARY KEY,
                freq_hz REAL,
                current_a REAL,
                voltage_v REAL,
                dc_bus_v REAL,
                fault_code INTEGER,
                source TEXT
            )
            """
        )
        con.execute("CREATE INDEX IF NOT EXISTS idx_samples_ts ON samples(ts_utc)")
        con.commit()


def db_insert_sample(sample: Dict[str, Any]) -> None:
    with sqlite3.connect(DB_PATH) as con:
        con.execute(
            """
            INSERT OR IGNORE INTO samples
            (ts_utc, freq_hz, current_a, voltage_v, dc_bus_v, fault_code, source)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            """,
            (
                sample["ts_utc"],
                sample.get("freq_hz"),
                sample.get("current_a"),
                sample.get("voltage_v"),
                sample.get("dc_bus_v"),
                int(sample.get("fault_code") or 0),
                sample.get("source", "unknown"),
            ),
        )
        con.commit()


def db_read_last_n(n: int) -> pd.DataFrame:
    with sqlite3.connect(DB_PATH) as con:
        df = pd.read_sql_query(
            f"SELECT * FROM samples ORDER BY ts_utc DESC LIMIT {int(n)}", con
        )
    if df.empty:
        return df
    df = df.sort_values("ts_utc")
    df["ts"] = pd.to_datetime(df["ts_utc"], utc=True).dt.tz_convert(None)
    return df


# =========================
# Data sources
# =========================
def now_utc_iso() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def read_mock_once() -> Dict[str, Any]:
    """
    Reads latest row from pump_mock.csv if present, otherwise generates a reasonable mock sample.
    """
    if RAW_MOCK.exists():
        try:
            df = pd.read_csv(RAW_MOCK)
            if len(df) > 0:
                row = df.iloc[-1].to_dict()
                return {
                    "ts_utc": now_utc_iso(),
                    "freq_hz": float(row.get("freq_hz", row.get("freq", 50.0))),
                    "current_a": float(row.get("current_a", row.get("curr", 0.0))),
                    "voltage_v": float(row.get("voltage_v", row.get("volt", 0.0))),
                    "dc_bus_v": float(row.get("dc_bus_v", row.get("dc_bus", np.nan))),
                    "fault_code": int(row.get("fault_code", row.get("fault", 0)) or 0),
                    "source": "mock_csv",
                }
        except Exception:
            pass

    # Fallback mock generator
    return {
        "ts_utc": now_utc_iso(),
        "freq_hz": float(np.random.uniform(30, 50)),
        "current_a": float(np.random.uniform(2, 7)),
        "voltage_v": float(np.random.uniform(380, 420)),
        "dc_bus_v": float(np.random.uniform(480, 560)),
        "fault_code": int(np.random.choice([0, 0, 0, 1])),
        "source": "mock_gen",
    }


def read_modbus_once(cfg: ModbusCfg) -> Tuple[Optional[Dict[str, Any]], str]:
    """
    Reads one sample via Modbus RTU. Returns (sample or None, status_message).
    Keeps the app stable: never raises.
    """
    if ModbusSerialClient is None:
        return None, "pymodbus is not installed. Run: pip install pymodbus pyserial"

    try:
        client = ModbusSerialClient(
            port=cfg.port,
            baudrate=cfg.baud,
            parity=cfg.parity,
            stopbits=cfg.stopbits,
            bytesize=cfg.bytesize,
            timeout=cfg.timeout,
        )

        if not client.connect():
            return None, f"GD20 NOT CONNECTED on {cfg.port} (connect() failed)"

        # Read registers individually (robust). If you know contiguous blocks, you can optimize later.
        def r(addr: int) -> Optional[int]:
            rr = client.read_holding_registers(address=int(addr), count=1, slave=int(cfg.slave_id))
            if not rr or getattr(rr, "isError", lambda: True)():
                return None
            regs = getattr(rr, "registers", None)
            if not regs:
                return None
            return int(regs[0])

        raw_freq = r(REG_MAP["freq_hz"])
        raw_curr = r(REG_MAP["current_a"])
        raw_volt = r(REG_MAP["voltage_v"])
        raw_dcbus = r(REG_MAP["dc_bus_v"])
        raw_fault = r(REG_MAP["fault_code"])

        # ---- Scaling (placeholders!) ----
        # Many drives store values with scaling (e.g., 0.01 Hz). Adjust after you confirm.
        freq_hz = None if raw_freq is None else raw_freq / 100.0
        current_a = None if raw_curr is None else raw_curr / 100.0
        voltage_v = None if raw_volt is None else raw_volt * 1.0
        dc_bus_v = None if raw_dcbus is None else raw_dcbus * 1.0
        fault_code = int(raw_fault or 0)

        sample = {
            "ts_utc": now_utc_iso(),
            "freq_hz": freq_hz,
            "current_a": current_a,
            "voltage_v": voltage_v,
            "dc_bus_v": dc_bus_v,
            "fault_code": fault_code,
            "source": f"modbus:{cfg.port}",
        }
        return sample, f"GD20 CONNECTED (Modbus RTU on {cfg.port}, slave {cfg.slave_id})"
    except Exception as e:
        return None, f"GD20 read error: {e.__class__.__name__}: {e}"
    finally:
        try:
            client.close()  # type: ignore
        except Exception:
            pass


# =========================
# App logic helpers
# =========================
def compute_power_kw(df: pd.DataFrame) -> pd.Series:
    """
    Approx power estimate: for 3-phase, P ≈ √3 * V * I * PF / 1000.
    PF is assumed (tweak if needed).
    """
    pf = float(st.session_state.get("pf", 0.85))
    v = df["voltage_v"].astype(float).fillna(0)
    i = df["current_a"].astype(float).fillna(0)
    return (np.sqrt(3) * v * i * pf) / 1000.0


def summarize(df: pd.DataFrame, tariff_rs_kwh: float) -> Dict[str, float]:
    if df.empty:
        return {"kwh_window": 0.0, "cost_window": 0.0, "fault_kwh": 0.0}

    df2 = df.copy()
    df2["power_kw"] = compute_power_kw(df2)

    # kWh with time deltas
    ts = pd.to_datetime(df2["ts"])
    dt = ts.diff().dt.total_seconds().fillna(0).clip(lower=0, upper=30)  # cap to 30s per step
    df2["kwh"] = df2["power_kw"].clip(lower=0) * (dt / 3600.0)

    kwh_window = float(df2["kwh"].sum())
    cost_window = float(kwh_window * tariff_rs_kwh)
    fault_kwh = float(df2.loc[df2["fault_code"].fillna(0).astype(int) != 0, "kwh"].sum())
    return {"kwh_window": kwh_window, "cost_window": cost_window, "fault_kwh": fault_kwh}


def page_header(data_type_label: str) -> None:
    c1, c2 = st.columns([1, 5])
    with c1:
        if LOGO_PATH.exists():
            st.image(str(LOGO_PATH), use_container_width=True)
    with c2:
        st.markdown(f"## {COMPANY_NAME}")
        st.markdown(f"### {PRODUCT_TITLE}")
        st.caption("Measure kWh & cost, detect abnormal operation early, and quantify savings opportunities.")

        st.markdown(
            f"""
            **Project location:** {PROJECT_LOCATION}  
            **Address:** {PROJECT_ADDRESS}  
            **Drive:** {DRIVE_MODEL}
            """
        )

        st.markdown(
            f"<div style='display:inline-block;padding:10px 14px;border-radius:12px;"
            f"background:#F59E0B;color:white;font-weight:700;'>Data Type: {data_type_label}</div>",
            unsafe_allow_html=True,
        )


# =========================
# Main App
# =========================

# =========================
# ML / Model Metrics helpers
# =========================

def ml_ensure_tables() -> None:
    with sqlite3.connect(DB_PATH) as con:
        con.execute(
            """
            CREATE TABLE IF NOT EXISTS model_metrics (
                run_ts_utc TEXT,
                model_name TEXT,
                n_rows INTEGER,
                n_train INTEGER,
                n_test INTEGER,
                target TEXT,
                metric1_name TEXT,
                metric1 REAL,
                metric2_name TEXT,
                metric2 REAL
            )
            """
        )
        con.execute("CREATE INDEX IF NOT EXISTS idx_model_metrics_ts ON model_metrics(run_ts_utc)")
        con.commit()


def ml_load_history(limit_rows: int = 5000) -> pd.DataFrame:
    with sqlite3.connect(DB_PATH) as con:
        df = pd.read_sql(
            "SELECT * FROM samples ORDER BY ts_utc ASC LIMIT ?",
            con,
            params=(int(limit_rows),),
        )
    if df.empty:
        return df
    df["ts_utc"] = pd.to_datetime(df["ts_utc"], errors="coerce")
    df = df.dropna(subset=["ts_utc"]).sort_values("ts_utc").reset_index(drop=True)
    return df


def ml_try_import_sklearn():
    try:
        from sklearn.pipeline import Pipeline
        from sklearn.preprocessing import StandardScaler
        from sklearn.linear_model import Ridge, LogisticRegression
        from sklearn.metrics import mean_absolute_error, r2_score, f1_score, roc_auc_score
        return {
            "ok": True,
            "Pipeline": Pipeline,
            "StandardScaler": StandardScaler,
            "Ridge": Ridge,
            "LogisticRegression": LogisticRegression,
            "mean_absolute_error": mean_absolute_error,
            "r2_score": r2_score,
            "f1_score": f1_score,
            "roc_auc_score": roc_auc_score,
        }
    except Exception as e:
        return {"ok": False, "err": str(e)}


def ml_regress_expected_current(df: pd.DataFrame):
    sk = ml_try_import_sklearn()
    if not sk["ok"]:
        return None, f"scikit-learn not available: {sk['err']}. Install: pip install scikit-learn"

    target = "current_a"
    if target not in df.columns or df[target].dropna().empty:
        return None, "No 'current_a' column available to train regression."

    # Basic feature set from telemetry
    candidates = ["freq_hz", "voltage_v", "dc_bus_v"]
    features = [c for c in candidates if c in df.columns and df[c].notna().any()]

    # If voltage isn't present in LIVE mode yet, we can still learn from freq + dc_bus
    if len(features) < 2:
        return None, f"Not enough features for regression. Found features={features}"

    work = df[["ts_utc", target] + features].replace([np.inf, -np.inf], np.nan).dropna()
    if len(work) < 250:
        return None, f"Need at least ~250 valid rows to show stable ML metrics. Found {len(work)}."

    # Time-based split (first 80% train, last 20% test)
    split = int(len(work) * 0.8)
    train = work.iloc[:split]
    test = work.iloc[split:]

    X_train, y_train = train[features], train[target]
    X_test, y_test = test[features], test[target]

    pipe = sk["Pipeline"]([
        ("scaler", sk["StandardScaler"]()),
        ("model", sk["Ridge"](alpha=1.0)),
    ])
    pipe.fit(X_train, y_train)
    pred = pipe.predict(X_test)

    mae = float(sk["mean_absolute_error"](y_test, pred))
    r2 = float(sk["r2_score"](y_test, pred))

    pred_df = pd.DataFrame({
        "ts_utc": test["ts_utc"].values,
        "actual_current_a": y_test.values,
        "pred_current_a": pred,
    })

    return {
        "model_name": "Expected Current (Ridge)",
        "target": target,
        "features": features,
        "n_rows": int(len(work)),
        "n_train": int(len(train)),
        "n_test": int(len(test)),
        "metric1_name": "MAE (A)",
        "metric1": mae,
        "metric2_name": "R²",
        "metric2": r2,
        "pred_df": pred_df,
    }, None


def ml_classify_fault(df: pd.DataFrame):
    sk = ml_try_import_sklearn()
    if not sk["ok"]:
        return None, f"scikit-learn not available: {sk['err']}. Install: pip install scikit-learn"

    if "fault_code" not in df.columns:
        return None, "No fault_code column available."

    # Create binary label
    work = df.copy()
    work["fault_bin"] = (work["fault_code"].fillna(0).astype(float) > 0).astype(int)

    # Need both classes
    if work["fault_bin"].nunique() < 2:
        return None, "No fault events in the data yet (fault_code never > 0). Collect more live data."

    candidates = ["freq_hz", "current_a", "voltage_v", "dc_bus_v"]
    features = [c for c in candidates if c in work.columns and work[c].notna().any()]

    if len(features) < 2:
        return None, f"Not enough features for classification. Found features={features}"

    work = work[["ts_utc", "fault_bin"] + features].replace([np.inf, -np.inf], np.nan).dropna()
    if len(work) < 400:
        return None, f"Need at least ~400 valid rows to show stable fault classification metrics. Found {len(work)}."

    split = int(len(work) * 0.8)
    train = work.iloc[:split]
    test = work.iloc[split:]

    X_train, y_train = train[features], train["fault_bin"]
    X_test, y_test = test[features], test["fault_bin"]

    pipe = sk["Pipeline"]([
        ("scaler", sk["StandardScaler"]()),
        ("model", sk["LogisticRegression"](max_iter=1000)),
    ])
    pipe.fit(X_train, y_train)
    proba = pipe.predict_proba(X_test)[:, 1]
    pred = (proba >= 0.5).astype(int)

    f1 = float(sk["f1_score"](y_test, pred))
    try:
        auc = float(sk["roc_auc_score"](y_test, proba))
    except Exception:
        auc = float("nan")

    return {
        "model_name": "Fault Classifier (LogReg)",
        "target": "fault_bin",
        "features": features,
        "n_rows": int(len(work)),
        "n_train": int(len(train)),
        "n_test": int(len(test)),
        "metric1_name": "F1",
        "metric1": f1,
        "metric2_name": "AUC",
        "metric2": auc,
    }, None


def ml_log_metrics(m: Dict[str, Any]) -> None:
    ml_ensure_tables()
    run_ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    with sqlite3.connect(DB_PATH) as con:
        con.execute(
            """
            INSERT INTO model_metrics
            (run_ts_utc, model_name, n_rows, n_train, n_test, target, metric1_name, metric1, metric2_name, metric2)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                run_ts,
                m["model_name"],
                int(m["n_rows"]),
                int(m["n_train"]),
                int(m["n_test"]),
                str(m["target"]),
                str(m["metric1_name"]),
                float(m["metric1"]),
                str(m["metric2_name"]),
                float(m["metric2"]),
            ),
        )
        con.commit()


def ml_read_metric_history() -> pd.DataFrame:
    ml_ensure_tables()
    with sqlite3.connect(DB_PATH) as con:
        df = pd.read_sql("SELECT * FROM model_metrics ORDER BY run_ts_utc ASC", con)
    if df.empty:
        return df
    df["run_ts_utc"] = pd.to_datetime(df["run_ts_utc"], errors="coerce")
    return df



def render_dashboard(df: pd.DataFrame, tariff: float) -> None:
    page_header("LIVE MODBUS" if (not df.empty and str(df.iloc[-1].get("source","")).upper().startswith("LIVE")) else "MOCK DATA")
    st.caption(f"Persistent store: {DB_PATH}  •  Last refresh: {datetime.now().strftime('%H:%M:%S')}")

    if df.empty:
        st.warning("No samples yet. If this is LIVE MODBUS mode, check COM port, wiring, and slave ID.")
        return

    st.subheader("Live Telemetry")
    last = df.iloc[-1]

    c1, c2, c3, c4, c5 = st.columns(5)
    c1.metric("Frequency (Hz)", f"{float(last['freq_hz'] or 0):.2f}")
    c2.metric("Current (A)", f"{float(last['current_a'] or 0):.2f}")
    c3.metric("Voltage (V)", f"{float(last['voltage_v'] or 0):.1f}")
    c4.metric("DC Bus (V)", f"{float(last['dc_bus_v'] or 0):.1f}")
    c5.metric("Fault", f"{int(last.get('fault_code') or 0)}")

    st.subheader("Energy, Waste, and Savings (Quantified Proof)")
    sums = summarize(df, tariff_rs_kwh=float(tariff))

    e1, e2, e3 = st.columns(3)
    e1.metric("kWh (window)", f"{sums['kwh_window']:.3f}")
    e2.metric("₹ cost (window)", f"{sums['cost_window']:.2f}")
    e3.metric("Fault-waste kWh (proxy)", f"{sums['fault_kwh']:.3f}")

    st.subheader("Trends")
    # Charts: time on x
    plot_df = df.copy()
    plot_df["ts"] = pd.to_datetime(plot_df["ts_utc"], errors="coerce")
    plot_df = plot_df.dropna(subset=["ts"]).set_index("ts")

    st.line_chart(plot_df[["freq_hz", "current_a"]].rename(columns={"freq_hz": "Freq (Hz)", "current_a": "Current (A)"}))

    if "fault_code" in plot_df.columns:
        st.line_chart((plot_df["fault_code"].fillna(0) > 0).astype(int).rename("Fault (binary)"))

    with st.expander("Raw samples (latest first)"):
        st.dataframe(df.sort_values("ts_utc", ascending=False).head(200), use_container_width=True)


def render_ml_metrics(limit_rows: int = 5000) -> None:
    st.header("AI/ML Metrics")
    st.markdown(
        """
This tab demonstrates **real ML** on your pump telemetry and creates a **measurable “improves over time” story**.

What you get:
- A regression model that learns **expected motor current** from other signals (Freq/Voltage/DC Bus).
- An optional fault classifier (when `fault_code > 0` events exist).
- **Metrics are logged to SQLite** each time you run evaluation, so charts show improvement over time.
        """
    )

    sk = ml_try_import_sklearn()
    if not sk["ok"]:
        st.error(f"scikit-learn is not installed/available: {sk['err']}")
        st.code("pip install scikit-learn", language="bash")
        st.stop()

    df = ml_load_history(limit_rows=limit_rows)
    if df.empty:
        st.warning("No history in SQLite yet. Run the dashboard for a while (preferably LIVE MODBUS) and come back.")
        return

    st.caption(f"Using history from: {DB_PATH}  •  Rows available: {len(df)}")

    colA, colB = st.columns([1, 1])
    with colA:
        st.info("Tip: Run evaluation after you have at least 15–30 minutes of LIVE data for a meaningful baseline.")
    with colB:
        auto_log = st.checkbox("Auto-log metrics on each refresh (advanced)", value=False)

    run_eval = st.button("Run ML evaluation now")

    if auto_log or run_eval:
        # Regression
        reg, err = ml_regress_expected_current(df)
        if err:
            st.warning(f"Regression model: {err}")
        else:
            ml_log_metrics(reg)
            st.success(f"Logged: {reg['model_name']}  •  {reg['metric1_name']}={reg['metric1']:.3f}  •  {reg['metric2_name']}={reg['metric2']:.3f}")
            st.subheader("Expected Current (Actual vs Predicted)")
            st.caption("If the model improves, MAE should generally go down and R² should generally go up as you collect more representative data.")
            pred_df = reg["pred_df"].copy()
            pred_df["ts_utc"] = pd.to_datetime(pred_df["ts_utc"], errors="coerce")
            pred_df = pred_df.dropna(subset=["ts_utc"]).set_index("ts_utc")
            st.line_chart(pred_df[["actual_current_a", "pred_current_a"]])

        # Classification (optional)
        clf, err2 = ml_classify_fault(df)
        if err2:
            st.info(f"Fault classifier: {err2}")
        else:
            ml_log_metrics(clf)
            st.success(f"Logged: {clf['model_name']}  •  {clf['metric1_name']}={clf['metric1']:.3f}  •  {clf['metric2_name']}={clf['metric2']:.3f}")

    st.subheader("Metric History (Improvement Over Time)")
    hist = ml_read_metric_history()
    if hist.empty:
        st.info("No logged metric runs yet. Click **Run ML evaluation now**.")
        return

    st.dataframe(hist, use_container_width=True)

    # Trend charts per model
    for model in hist["model_name"].unique():
        sub = hist[hist["model_name"] == model].copy()
        sub = sub.dropna(subset=["run_ts_utc"]).sort_values("run_ts_utc")
        if sub.empty:
            continue
        st.markdown(f"### {model}")
        sub = sub.set_index("run_ts_utc")
        st.line_chart(sub[["metric1", "metric2"]].rename(columns={"metric1": sub.iloc[0]["metric1_name"], "metric2": sub.iloc[0]["metric2_name"]}))


def render_education() -> None:
    st.header("Education & How Performance Improves Over Time")
    st.markdown(
        f"""
### What this project is
This is an **edge AI kit** for a VFD-driven pump system.

- **Project location:** {PROJECT_LOCATION}  
- **Address:** {PROJECT_ADDRESS}  
- **Drive:** {DRIVE_MODEL}

### What “ML improves performance over time” means here
In practical pump monitoring, “better over time” usually comes from:

1) **More representative data**  
   As you collect data across mornings/afternoons, different sunlight, load, and pipe conditions, models generalize better.

2) **Better labels (ground truth)**  
   When you (or maintenance team) confirm real faults / normal events, classification metrics become meaningful and improve.

3) **Feedback loop into actions**  
   Once the model detects trends (e.g., current increases at same frequency), you can act (cleaning, valve check) and show
   reduced waste/fault-rate later.

### Metrics you can show to investors / stakeholders
**Telemetry/Operations metrics (always available):**
- kWh, ₹ cost, fault-waste proxy
- fault frequency (events/day)
- stability (variance) of current at a fixed frequency band

**ML metrics (from AI/ML Metrics tab):**
- Regression: **MAE (A)** and **R²** for expected current prediction  
- Classification (when faults exist): **F1** and **AUC** for fault detection

### Why we log metrics into SQLite
Every time you run evaluation, we store a record in `model_metrics`.  
That creates a **time series of model performance**, which is how you demonstrate improvement.

### Notes about live Modbus
- If LIVE MODBUS is not responding, the app will fall back safely and continue.
- Verify: wiring (A/B), COM port, baud, slave ID, and your GD20 register map.

### References (conceptual)
- **Supervised learning evaluation:** MAE/R² for regression, Precision/Recall/F1 and ROC-AUC for classification.
- **Concept drift:** data distribution changes across seasons/usage; monitor metrics regularly.
- **Edge AI pattern:** collect at edge, optionally sync to cloud (GCP/Vertex) later.

"""
    )


def render_predictive_maintenance(limit_rows: int = 20000) -> None:
    """Predictive maintenance view (heuristic + optional ML).

    Goal: Provide an easy, demo-friendly early-warning system without requiring extra sensors.
    Uses historical telemetry stored in SQLite.
    """
    st.header("Predictive Maintenance")
    st.caption("Early warning indicators from existing telemetry (no extra sensors).")

    df = ml_load_history(limit_rows=limit_rows)
    if df.empty:
        st.warning("No history found yet. Run the Dashboard for a while to collect samples, then return here.")
        return

    # Basic cleaning
    for c in ["freq_hz", "current_a", "voltage_v", "dc_bus_v", "fault_code"]:
        if c in df.columns:
            df[c] = pd.to_numeric(df[c], errors="coerce")
    df = df.dropna(subset=["ts_utc"]).copy()
    df = df.sort_values("ts_utc").reset_index(drop=True)

    # Define a "steady operation" slice: near-rated frequency and not in fault
    steady = df.copy()
    if "fault_code" in steady.columns:
        steady = steady[steady["fault_code"].fillna(0) == 0]
    if "freq_hz" in steady.columns:
        steady = steady[steady["freq_hz"].between(45, 52)]
    steady = steady.dropna(subset=["current_a", "freq_hz"])

    if len(steady) < 200:
        st.info("Collect more steady-state samples (45–52 Hz, fault_code=0). Need ~200+ rows for meaningful trends.")
        st.dataframe(df.tail(200), use_container_width=True)
        return

    # Normalization: current per Hz (helps compare across small frequency variations)
    steady["curr_per_hz"] = steady["current_a"] / steady["freq_hz"].replace(0, np.nan)

    # Rolling features
    steady["ts"] = pd.to_datetime(steady["ts_utc"], errors="coerce")
    steady = steady.dropna(subset=["ts"]).set_index("ts")

    roll_n = min(200, max(20, int(len(steady) * 0.05)))
    minp = max(10, roll_n // 3)
    steady["curr_phz_roll"] = steady["curr_per_hz"].rolling(roll_n, min_periods=minp).median()
    steady["curr_roll"] = steady["current_a"].rolling(roll_n, min_periods=minp).median()

    # Trend: compare first 30% vs last 30%
    n = len(steady)
    a = int(n * 0.3)
    first = steady.iloc[:a]
    last = steady.iloc[-a:]

    baseline = float(first["curr_phz_roll"].dropna().median())
    recent = float(last["curr_phz_roll"].dropna().median())
    drift_pct = (recent - baseline) / max(1e-6, baseline) * 100.0

    # Optional ML residual (if sklearn is present and there is enough data)
    ml_note = None
    residual_score = None
    try:
        reg, err = ml_regress_expected_current(df)
        if err:
            ml_note = err
        else:
            pred_df = reg["pred_df"].copy()
            pred_df["residual_a"] = (pred_df["actual_current_a"] - pred_df["pred_current_a"]).astype(float)

            tail = pred_df.tail(min(300, len(pred_df)))
            residual_mae = float(np.mean(np.abs(tail["residual_a"].values)))
            residual_score = residual_mae
    except Exception as e:
        ml_note = f"ML residual unavailable: {e.__class__.__name__}: {e}"

    # Health scoring (simple + explainable)
    # - drift_pct: +10% or more is a warning (more current for same speed often means friction/clogging/head increase)
    # - residual_score: >~1A is a warning for a 2HP-class pump (tune later once you see real ranges)
    drift_points = float(np.clip(abs(drift_pct) / 15.0, 0, 1))  # 15% drift -> max penalty
    resid_points = 0.0 if residual_score is None else float(np.clip(residual_score / 1.0, 0, 1))  # 1A -> max penalty

    health = float(100.0 * (1.0 - 0.65 * drift_points - 0.35 * resid_points))
    health = float(np.clip(health, 0, 100))

    if health >= 85:
        status = "✅ Healthy"
        action = "Continue monitoring. No maintenance action needed."
    elif health >= 70:
        status = "🟡 Watchlist"
        action = "Plan a routine check: clean strainer/filter, confirm suction line, check valves are fully open."
    elif health >= 50:
        status = "🟠 Attention"
        action = "Schedule maintenance: inspect impeller/foot valve, check pipe blockage, verify bearings/alignment."
    else:
        status = "🔴 High Risk"
        action = "Immediate inspection recommended. Risk of overheating/overcurrent and downtime."

    c1, c2, c3, c4 = st.columns(4)
    c1.metric("Pump Health Score", f"{health:.0f}/100")
    c2.metric("Status", status)
    c3.metric("Current drift (steady)", f"{drift_pct:+.1f}%")
    c4.metric("ML residual (recent)", "—" if residual_score is None else f"{residual_score:.2f} A")

    st.markdown("### What this means")
    st.markdown(
        "- We look at **steady operation** samples (45–52 Hz, no faults) and track how much current is needed.\n"
        "- If current required for the same speed increases, it often indicates **higher friction / clogging / higher head**, or early mechanical wear.\n"
        "- This is an **early-warning indicator** (explainable), not a replacement for on-site inspection."
    )

    st.markdown("### Recommended action")
    st.info(action)

    if ml_note:
        st.caption(f"ML note: {ml_note}")

    st.markdown("### Trend charts")
    chart_df = steady[["current_a", "curr_roll"]].dropna().rename(
        columns={"current_a": "Current (A)", "curr_roll": f"Rolling median ({roll_n})"}
    )
    st.line_chart(chart_df)

    chart2 = steady[["curr_phz_roll"]].dropna().rename(
        columns={"curr_phz_roll": f"Current per Hz (rolling median, {roll_n})"}
    )
    st.line_chart(chart2)

    with st.expander("Details (steady-state subset)"):
        st.caption(f"Baseline median curr/Hz: {baseline:.4f}  •  Recent median curr/Hz: {recent:.4f}")
        st.dataframe(steady.reset_index().tail(300), use_container_width=True)



def main() -> None:
    st.set_page_config(page_title="GD20 Pump Monitor", layout="wide")
    st.markdown(LIGHT_BLUE_BG, unsafe_allow_html=True)

    db_init()
    ml_ensure_tables()

    # ---- Sidebar controls ----
    st.sidebar.header("Controls")

    data_mode = st.sidebar.radio(
        "Data source",
        options=["MOCK DATA", "LIVE MODBUS"],
        index=0,
        help="Use MOCK until your RS485/Modbus wiring and register map are confirmed.",
    )

    auto_refresh_sec = st.sidebar.slider("Auto-refresh (sec)", 1, 30, 2)
    rows = st.sidebar.slider("Rows to analyze", 50, 5000, 1200, step=50)
    tariff = st.sidebar.number_input("Tariff (₹/kWh)", min_value=0.0, value=9.00, step=0.50)
    st.sidebar.number_input("Power factor (assumed)", min_value=0.1, max_value=1.0, value=0.85, step=0.05, key="pf")

    show_banners = st.sidebar.checkbox("Show tips / mode banners", value=False)

    st.sidebar.divider()
    st.sidebar.subheader("Modbus settings")
    st.sidebar.text_input("Port", value=CFG.port, key="mb_port")
    st.sidebar.number_input("Baud", min_value=1200, max_value=115200, value=int(CFG.baud), step=1200, key="mb_baud")
    st.sidebar.number_input("Slave ID", min_value=1, max_value=247, value=int(CFG.slave_id), step=1, key="mb_slave")

    st.sidebar.divider()
    st.sidebar.subheader("ML / Metrics")
    ml_rows = st.sidebar.slider("Rows for ML evaluation", 500, 50000, 5000, step=500)

    # ---- Autorefresh ----
    if st_autorefresh is not None:
        st_autorefresh(interval=int(auto_refresh_sec * 1000), key="tick")
    else:
        if show_banners:
            st.info("Tip: install streamlit-autorefresh for smoother refresh: pip install streamlit-autorefresh")

    # ---- Acquire one new sample per run ----
    if data_mode == "LIVE MODBUS":
        cfg = ModbusCfg(
            port=st.session_state.mb_port,
            baud=int(st.session_state.mb_baud),
            slave_id=int(st.session_state.mb_slave),
            parity=CFG.parity,
            stopbits=CFG.stopbits,
            bytesize=CFG.bytesize,
            timeout=float(CFG.timeout),
        )
        sample, err = read_modbus_once(cfg)
        if err:
            if show_banners:
                st.warning(f"LIVE MODBUS read failed: {err}. Recording a placeholder sample from MOCK.")
            sample = read_mock_once()
        sample["source"] = "LIVE" if sample.get("source") == "LIVE" else "MOCK"
    else:
        sample = read_mock_once()
        sample["source"] = "MOCK"

    db_insert_sample(sample)

    # Read window for dashboard
    df = db_read_last_n(int(rows))

    tab_dash, tab_ml, tab_pm, tab_ed = st.tabs(["Dashboard", "AI/ML Metrics", "Predictive Maintenance", "Education"])
    with tab_dash:
        render_dashboard(df=df, tariff=float(tariff))
    with tab_ml:
        render_ml_metrics(limit_rows=int(ml_rows))
    with tab_pm:
        render_predictive_maintenance(limit_rows=int(ml_rows))
    with tab_ed:
        render_education()


if __name__ == "__main__":
    main()