File size: 32,599 Bytes
f6182b1
a52e62f
 
 
5f829f5
06c492c
57f3033
de7ee5b
a52e62f
 
 
5f829f5
a52e62f
168e602
57f3033
 
168e602
57f3033
 
 
 
a52e62f
06c492c
0bbd6e4
bc12e32
 
 
 
 
 
 
 
 
 
 
 
 
 
a52e62f
06c492c
a52e62f
168e602
 
06c492c
 
 
 
 
 
 
 
 
0e0de06
06c492c
 
168e602
 
31f73ed
168e602
 
 
930651f
43705d6
 
6a00baa
 
43705d6
 
a52e62f
 
 
43705d6
 
a52e62f
 
06c492c
43705d6
a52e62f
 
06c492c
 
 
 
 
 
 
 
 
57f3033
06c492c
57f3033
06c492c
de7ee5b
22ba880
de7ee5b
 
 
 
 
06c492c
 
de7ee5b
 
06c492c
 
 
 
 
 
 
de7ee5b
43705d6
 
de7ee5b
 
 
 
 
 
 
 
43705d6
 
de7ee5b
 
 
 
 
 
 
 
43705d6
 
de7ee5b
 
 
 
43705d6
de7ee5b
 
 
 
 
 
 
 
 
06c492c
de7ee5b
 
 
 
 
 
 
43705d6
06c492c
de7ee5b
 
 
 
 
 
 
43705d6
de7ee5b
168e602
22ba880
06c492c
22ba880
43705d6
 
 
 
 
8d582ff
 
43705d6
8d582ff
 
43705d6
 
 
 
 
 
8d582ff
 
43705d6
8d582ff
43705d6
de7ee5b
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43705d6
06c492c
43705d6
de7ee5b
 
 
 
740413d
de7ee5b
740413d
de7ee5b
740413d
 
 
43705d6
06c492c
 
 
 
 
e783d30
43705d6
f94a786
0e0de06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43705d6
de7ee5b
 
43705d6
 
06c492c
43705d6
 
06c492c
31f73ed
43705d6
 
 
 
 
 
de7ee5b
22ba880
e783d30
 
 
 
43705d6
740413d
de7ee5b
 
 
06c492c
 
 
 
 
de7ee5b
06c492c
de7ee5b
06c492c
de7ee5b
06c492c
 
 
 
 
 
 
de7ee5b
43705d6
de7ee5b
 
 
 
 
 
43705d6
de7ee5b
 
 
 
 
 
 
 
 
 
 
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
0e0de06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06c492c
 
 
 
 
de7ee5b
34b42c0
06c492c
34b42c0
06c492c
 
 
8d582ff
06c492c
 
 
e783d30
06c492c
 
 
 
 
43705d6
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168e602
 
43705d6
06c492c
31f73ed
a52e62f
 
06c492c
930651f
5fa538f
740413d
de7ee5b
740413d
de7ee5b
06c492c
740413d
43705d6
740413d
06c492c
 
 
a52e62f
 
930651f
06c492c
 
43705d6
06c492c
 
 
 
 
8d76ccc
43705d6
 
06c492c
43705d6
06c492c
 
 
43705d6
de7ee5b
43705d6
 
de7ee5b
 
06c492c
de7ee5b
8d76ccc
de7ee5b
 
bd3988d
5fa538f
06c492c
 
 
 
 
 
 
 
 
 
 
 
43705d6
930651f
06c492c
 
 
 
0e0de06
06c492c
d54e25f
a52e62f
5fa538f
06c492c
e783d30
06c492c
43705d6
 
 
 
de7ee5b
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e783d30
43705d6
e783d30
43705d6
06c492c
e783d30
06c492c
e783d30
0e0de06
06c492c
43705d6
 
 
e783d30
43705d6
e783d30
 
 
 
43705d6
e783d30
06c492c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e783d30
 
06c492c
 
43705d6
 
06c492c
 
 
 
 
43705d6
06c492c
 
 
 
 
 
 
 
 
43705d6
168e602
930651f
de7ee5b
168e602
a52e62f
168e602
 
de7ee5b
168e602
 
de7ee5b
 
 
 
06c492c
 
43705d6
06c492c
43705d6
0e0de06
06c492c
 
0e0de06
 
 
06c492c
 
 
0e0de06
 
 
06c492c
a52e62f
06c492c
 
 
0e0de06
 
 
 
 
 
22ba880
06c492c
de7ee5b
06c492c
 
 
43705d6
06c492c
 
 
 
43705d6
0e0de06
 
 
 
 
06c492c
de7ee5b
06c492c
168e602
06c492c
 
 
d54e25f
 
fed836a
de7ee5b
168e602
fed836a
43705d6
 
 
 
 
740413d
06c492c
0e0de06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de7ee5b
06c492c
 
 
 
 
 
a52e62f
43705d6
06c492c
168e602
de7ee5b
168e602
a52e62f
06c492c
43705d6
 
 
 
06c492c
168e602
0e0de06
 
 
 
de7ee5b
0e0de06
 
 
 
 
06c492c
0e0de06
 
de7ee5b
06c492c
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
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
import streamlit as st
import pandas as pd
import numpy as np
import json
import joblib
import re
from pathlib import Path
from datetime import datetime
from dateutil.relativedelta import relativedelta
import plotly.express as px
import plotly.graph_objects as go

# -------------------------------------------------------
# PATHS
# -------------------------------------------------------
BASE_DIR = Path(__file__).resolve().parent
def p(name: str) -> Path:
    return BASE_DIR / name

# -------------------------------------------------------
# PAGE CONFIG
# -------------------------------------------------------
st.set_page_config(page_title="Kenya IPC Phase Dashboard", layout="wide")

# -------------------------------------------------------
# APP HEADER
# -------------------------------------------------------
st.markdown(
    """
<h1 style="margin-bottom:0.2rem;">County-Level Food Insecurity Risk Prediction Dashboard (Kenya)</h1>
<div class="small-note" style="margin-top:0;">
Predicting IPC Phase 3+ (Crisis and above) risk to support monitoring, planning, and targeted response.
</div>
<hr/>
""",
    unsafe_allow_html=True,
)

# -------------------------------------------------------
# CSS
# -------------------------------------------------------
st.markdown(
    """
<style>
.block-container {padding-top:2rem;padding-bottom:2rem;}
[data-testid="stSidebar"] {background: rgba(255,255,255,0.02);}
.card {background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.06);
       border-radius:16px;padding:14px;margin-bottom:10px;}
.small-note {opacity:0.78;font-size:0.92rem;}
.legend-dot {display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:8px;}
div[data-testid="stMetricValue"] {font-size: 2rem;}
hr {border:none;border-top:1px solid rgba(255,255,255,0.08); margin:0.6rem 0;}
.band-pill {display:inline-block;padding:2px 10px;border-radius:999px;font-weight:700;}
</style>
""",
    unsafe_allow_html=True,
)

# -------------------------------------------------------
# LOADERS
# -------------------------------------------------------
@st.cache_data
def load_csv(filename: str) -> pd.DataFrame:
    return pd.read_csv(p(filename))

@st.cache_data
def load_geojson(filename: str) -> dict:
    with open(p(filename), "r", encoding="utf-8") as f:
        return json.load(f)

@st.cache_resource
def load_model(filename: str):
    return joblib.load(p(filename))

@st.cache_data
def load_json(filename: str):
    with open(p(filename), "r", encoding="utf-8") as f:
        return json.load(f)

def load_optional_csv(filename: str) -> pd.DataFrame | None:
    fp = p(filename)
    if not fp.exists():
        return None
    try:
        return pd.read_csv(fp)
    except Exception:
        return None

# -------------------------------------------------------
# STANDARDIZATION
# -------------------------------------------------------
def normalize_county_name(x) -> str:
    if pd.isna(x):
        return ""
    s = str(x).strip()
    s = " ".join(s.split())
    s = s.replace("&", "and")
    s = s.title()
    s = s.replace("Elgeyo Marakwet", "Elgeyo-Marakwet")
    s = s.replace("Taita Taveta", "Taita-Taveta")
    s = s.replace("Tharaka Nithi", "Tharaka-Nithi")
    return s

def county_key(x) -> str:
    if pd.isna(x):
        return ""
    s = str(x).strip().lower()
    s = s.replace("&", "and")
    return re.sub(r"[^a-z0-9]+", "", s)

def detect_month_col(df: pd.DataFrame) -> str | None:
    candidates = ["month", "Month", "date", "Date", "TIME_PERIOD", "time_period", "assessment_month", "Assessment_Month"]
    for c in candidates:
        if c in df.columns:
            return c
    for c in df.columns:
        if "month" in c.lower():
            return c
    return None

def detect_county_col(df: pd.DataFrame) -> str | None:
    candidates = ["county", "County", "admin1", "Admin1", "Admin 1", "Admin_1"]
    for c in candidates:
        if c in df.columns:
            return c
    for c in df.columns:
        if "county" in c.lower():
            return c
    return None

def detect_risk_col(df: pd.DataFrame) -> str | None:
    candidates = ["risk_proba", "risk_probability", "Risk_Probability", "risk_prob", "probability", "proba"]
    for c in candidates:
        if c in df.columns:
            return c
    for c in df.columns:
        lc = c.lower()
        if ("risk" in lc and "prob" in lc) or (lc in ["risk", "proba", "probability"]):
            return c
    return None

def coerce_month(df: pd.DataFrame) -> pd.DataFrame:
    mcol = detect_month_col(df)
    if mcol is not None and mcol != "month":
        df = df.rename(columns={mcol: "month"})
    if "month" in df.columns:
        df["month"] = pd.to_datetime(df["month"], errors="coerce")
        df["month"] = df["month"].dt.to_period("M").dt.to_timestamp()
    return df

def coerce_county(df: pd.DataFrame) -> pd.DataFrame:
    ccol = detect_county_col(df)
    if ccol is not None and ccol != "county":
        df = df.rename(columns={ccol: "county"})
    if "county" in df.columns:
        df["county"] = df["county"].map(normalize_county_name)
        df["county_key"] = df["county"].map(county_key)
    return df

def coerce_risk(df: pd.DataFrame) -> pd.DataFrame:
    rcol = detect_risk_col(df)
    if rcol is not None and rcol != "risk_proba":
        df = df.rename(columns={rcol: "risk_proba"})
    if "risk_proba" in df.columns:
        df["risk_proba"] = pd.to_numeric(df["risk_proba"], errors="coerce").clip(0, 1)
    return df

# -------------------------------------------------------
# GEOJSON HELPERS (BORROWED IDEA: USE RAW PROPERTY VALUES)
# -------------------------------------------------------
def geojson_detect_county_key(gj: dict) -> str:
    features = gj.get("features", [])
    if not features:
        return "properties.shapeName"
    props = features[0].get("properties", {})
    keys = list(props.keys())

    preferred = []
    for k in keys:
        lk = k.lower()
        if "shapename" in lk or (("county" in lk or "name" in lk) and "code" not in lk and "id" not in lk):
            preferred.append(k)

    if preferred:
        return f"properties.{preferred[0]}"

    for k in keys:
        if isinstance(props.get(k), str):
            return f"properties.{k}"

    return "properties.shapeName"

@st.cache_data
def build_geo_base(gj: dict) -> tuple[str, pd.DataFrame, dict]:
    """
    Returns:
      - featureidkey string
      - base dataframe with all polygons (47 rows): county, county_key, geo_value
      - lookup dict: normalized county -> raw geo_value
    """
    featureidkey = geojson_detect_county_key(gj)
    prop = featureidkey.split(".", 1)[1] if featureidkey.startswith("properties.") else featureidkey

    rows = []
    lookup = {}
    for ft in gj.get("features", []):
        props = ft.get("properties", {})
        raw = props.get(prop, "")
        pretty = normalize_county_name(raw)
        key = county_key(raw)
        if raw and key:
            rows.append({"county": pretty, "county_key": key, "geo_value": raw})
            lookup[pretty] = raw

    base = pd.DataFrame(rows).drop_duplicates(subset=["county_key"]).sort_values("county")
    return featureidkey, base, lookup

# -------------------------------------------------------
# RISK + IPC
# -------------------------------------------------------
def risk_band(p: float, thr: float) -> str:
    if pd.isna(p):
        return "Unknown"
    if p < thr:
        return "Secure"
    if p < min(thr + 0.15, 1.0):
        return "Watch"
    if p < min(thr + 0.35, 1.0):
        return "High"
    return "Extreme"

RISK_COLORS = {
    "Secure":  "#16a34a",
    "Watch":   "#facc15",
    "High":    "#f97316",
    "Extreme": "#dc2626",
    "Unknown": "#6b7280",
}
RISK_ORDER = ["Secure", "Watch", "High", "Extreme", "Unknown"]

def band_badge_html(band: str) -> str:
    c = RISK_COLORS.get(band, "#6b7280")
    return f"<span class='band-pill' style='background:{c}22;border:1px solid {c}66;color:{c};'>{band}</span>"

# -------------------------------------------------------
# HUMAN-FRIENDLY NAMES FOR FEATURES (Scenario inputs + Drivers)
# -------------------------------------------------------
FEATURE_LABELS = {
    "is_ASAL": "Arid/Semi-Arid county (ASAL)",
    "vim": "Vegetation health (greenness)",
    "r3q": "Rainfall (3-month total)",
    "r1q": "Rainfall (1-month total)",
    "r1h": "Rainfall intensity (1-month)",
    "r3h": "Rainfall intensity (3-month)",
    "maize_price_per_kg": "Maize price (KES per kg)",
    "price_pct_change": "Food price change (%)",
}

FEATURE_HELP = {
    "is_ASAL": "1 means the county is classified as ASAL; 0 means non-ASAL.",
    "vim": "Higher usually means greener vegetation; lower can indicate drought stress.",
    "r3q": "Total rainfall over the recent 3-month window.",
    "r1q": "Total rainfall for the most recent month.",
    "maize_price_per_kg": "Market price of maize per kilogram (KES).",
    "price_pct_change": "Percent change in a food price index compared to the previous period.",
}

def humanize_feature_name(f: str) -> str:
    if f in FEATURE_LABELS:
        return FEATURE_LABELS[f]

    m = re.match(r"^(.*)_lag_(\d+)$", str(f))
    if m:
        base = m.group(1)
        n = int(m.group(2))
        base_label = FEATURE_LABELS.get(base, base.replace("_", " ").title())
        # Simple phrasing a normal user understands
        if n == 1:
            return f"{base_label} (1 month ago)"
        return f"{base_label} ({n} months ago)"

    return str(f).replace("_", " ").title()

def feature_help_text(f: str) -> str:
    if f in FEATURE_HELP:
        return FEATURE_HELP[f]
    m = re.match(r"^(.*)_lag_(\d+)$", str(f))
    if m:
        base = m.group(1)
        return FEATURE_HELP.get(base, "A past (lagged) value of this factor.")
    return "Model input used to estimate IPC Phase 3+ risk."

# IPC Phase reference (definition + colors)
ipc_table = pd.DataFrame(
    [
        [1, "Minimal", "Households meet basic food needs without atypical coping."],
        [2, "Stressed", "Basic food needs met, but cannot afford essential non-food needs."],
        [3, "Crisis", "Food gaps and/or high coping; requires urgent action."],
        [4, "Emergency", "Large food gaps; very high malnutrition; excess mortality risk."],
        [5, "Famine", "Extreme lack of food; starvation, death, destitution."],
    ],
    columns=["IPC Phase", "Label", "Interpretation"],
)

IPC_PHASE_COLORS = {1: "#16a34a", 2: "#84cc16", 3: "#facc15", 4: "#f97316", 5: "#dc2626"}

def style_ipc_table(df: pd.DataFrame):
    d = df.copy()

    def row_style(row):
        c = IPC_PHASE_COLORS.get(int(row["IPC Phase"]), "#6b7280")
        return [f"background-color: {c}22; border-left: 6px solid {c};"] * len(row)

    sty = d.style.apply(row_style, axis=1)
    try:
        sty = sty.hide(axis="index")
    except Exception:
        pass
    return sty

def styled_df_for_display(df: pd.DataFrame, thr: float):
    d = df.copy()
    if "risk_proba" in d.columns:
        d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce").clip(0, 1)
        d["band"] = d["risk_proba"].apply(lambda x: risk_band(x, thr))
        d["class"] = np.where(d["risk_proba"] >= thr, "At Risk", "Secure")
    else:
        d["band"] = "Unknown"
        d["class"] = "Unknown"

    def row_style(row):
        band = row.get("band", "Unknown")
        color = RISK_COLORS.get(band, "#6b7280")
        return [f"background-color: {color}22; border-left: 6px solid {color};"] * len(row)

    sty = d.style.apply(row_style, axis=1)
    if "risk_proba" in d.columns:
        sty = sty.format({"risk_proba": "{:.3f}"})
    try:
        sty = sty.hide(axis="index")
    except Exception:
        pass
    return d, sty

# -------------------------------------------------------
# LOAD DATA
# -------------------------------------------------------
hist = coerce_month(coerce_risk(coerce_county(load_csv("predictions_historical.csv"))))
forecast = coerce_month(coerce_risk(coerce_county(load_csv("predictions_forecast_next_month.csv"))))
national = coerce_month(load_csv("national_trend.csv"))
top10 = coerce_month(coerce_risk(coerce_county(load_csv("top10_by_month.csv"))))
baseline = coerce_county(load_csv("baseline_latest_features.csv"))
feature_importance = load_csv("feature_importance.csv")
geojson = load_geojson("kenya_counties.geojson")
model = load_model("model.joblib")
FEATURES = load_json("features.json")

# Optional observed IPC phases file (exact phase 1–5). This is the only way to show "exact phase".
# File name expected: ipc_phases_county_month.csv with columns: county, month, ipc_phase (1–5)
ipc_obs = load_optional_csv("ipc_phases_county_month.csv")
if ipc_obs is not None:
    ipc_obs = coerce_month(coerce_county(ipc_obs))
    if "ipc_phase" in ipc_obs.columns:
        ipc_obs["ipc_phase"] = pd.to_numeric(ipc_obs["ipc_phase"], errors="coerce").astype("Int64")

# National trend robustness
if "national_avg_risk" not in national.columns:
    rc = detect_risk_col(national)
    if rc and rc != "national_avg_risk":
        national = national.rename(columns={rc: "national_avg_risk"})
national["national_avg_risk"] = pd.to_numeric(national.get("national_avg_risk", np.nan), errors="coerce")

# Feature importance robustness
if "feature" not in feature_importance.columns:
    for c in feature_importance.columns:
        if "feature" in c.lower():
            feature_importance = feature_importance.rename(columns={c: "feature"})
if "importance" not in feature_importance.columns:
    for c in feature_importance.columns:
        if "import" in c.lower():
            feature_importance = feature_importance.rename(columns={c: "importance"})
if "importance" in feature_importance.columns:
    feature_importance["importance"] = pd.to_numeric(feature_importance["importance"], errors="coerce")

# Month anchors
if "month" not in hist.columns or hist["month"].isna().all():
    st.error("Historical predictions file is missing a usable month column.")
    st.stop()

latest_hist_month = hist["month"].max()

# Forecast month (use file if present; else next month)
if "month" in forecast.columns and not forecast["month"].isna().all():
    forecast_month = forecast["month"].max()
else:
    forecast_month = datetime.today().replace(day=1) + relativedelta(months=1)
    forecast_month = pd.to_datetime(forecast_month).to_period("M").to_timestamp()

def get_county_forecast_probability(county_name: str) -> float | None:
    """Return forecast probability for the selected county (for forecast_month when available)."""
    if forecast is None or forecast.empty or "risk_proba" not in forecast.columns:
        return None
    ck = county_key(county_name)
    d = forecast.copy()
    if "county_key" not in d.columns:
        d = coerce_county(d)

    # Prefer the explicit forecast_month if the forecast file contains month
    if "month" in d.columns and not d["month"].isna().all():
        m = pd.to_datetime(forecast_month).to_period("M").to_timestamp()
        tmp = d[(d["county_key"] == ck) & (d["month"] == m)].copy()
        if tmp.empty:
            # fallback: latest forecast available for that county
            tmp = d[d["county_key"] == ck].sort_values("month", ascending=False).head(1)
    else:
        tmp = d[d["county_key"] == ck].head(1)

    if tmp.empty:
        return None
    return float(pd.to_numeric(tmp["risk_proba"], errors="coerce").clip(0, 1).iloc[0])

# Geo base (this is what ensures all 47 polygons can render)
featureidkey, GEO_BASE, GEO_LOOKUP = build_geo_base(geojson)
if GEO_BASE.empty or GEO_BASE.shape[0] < 40:
    st.error("GeoJSON county extraction failed. Your GeoJSON may not contain county names in the detected properties.")
    st.stop()

# -------------------------------------------------------
# CACHED PREP (ALL 47 ALWAYS)
# -------------------------------------------------------
@st.cache_data
def prepare_month_all47(pred_df: pd.DataFrame, month_value: pd.Timestamp | None, thr: float) -> pd.DataFrame:
    base = GEO_BASE.copy()

    d = pred_df.copy()
    if "month" in d.columns and month_value is not None:
        d = d[d["month"] == month_value].copy()

    # If predictions have duplicates per county-month, keep max risk (conservative)
    if "risk_proba" in d.columns:
        d["risk_proba"] = pd.to_numeric(d["risk_proba"], errors="coerce").clip(0, 1)
        d = d.sort_values("risk_proba", ascending=False)
        d = d.drop_duplicates(subset=["county_key"], keep="first")

    merged = base.merge(
        d[["county_key", "risk_proba"]] if "risk_proba" in d.columns else d[["county_key"]],
        on="county_key",
        how="left",
    )

    merged["risk_proba"] = pd.to_numeric(merged.get("risk_proba", np.nan), errors="coerce").clip(0, 1)
    merged["band"] = merged["risk_proba"].apply(lambda x: risk_band(x, thr))
    merged["class"] = np.where(merged["risk_proba"] >= thr, "At Risk", "Secure")
    return merged

def attach_ipc_phase(df47: pd.DataFrame, month_value: pd.Timestamp) -> pd.DataFrame:
    out = df47.copy()
    out["ipc_phase"] = pd.NA
    if ipc_obs is None:
        return out
    if "month" not in ipc_obs.columns or "ipc_phase" not in ipc_obs.columns:
        return out
    m = pd.to_datetime(month_value).to_period("M").to_timestamp()
    tmp = ipc_obs[ipc_obs["month"] == m].copy()
    if tmp.empty:
        return out
    tmp = tmp.sort_values("ipc_phase", ascending=False).drop_duplicates(subset=["county_key"], keep="first")
    out = out.merge(tmp[["county_key", "ipc_phase"]], on="county_key", how="left", suffixes=("", "_obs"))
    if "ipc_phase_obs" in out.columns:
        out["ipc_phase"] = out["ipc_phase_obs"]
        out = out.drop(columns=["ipc_phase_obs"])
    return out

# -------------------------------------------------------
# SIDEBAR
# -------------------------------------------------------
st.sidebar.markdown("## System Controls")

threshold = st.sidebar.slider("Risk Threshold", 0.10, 0.90, 0.45, 0.01)

page = st.sidebar.radio(
    "Navigation",
    ["National Situation", "Risk Map", "Scenario Simulator", "County Profile"],
)

st.sidebar.markdown("### Risk Bands")
for k in ["Secure", "Watch", "High", "Extreme"]:
    st.sidebar.markdown(
        f"<span class='legend-dot' style='background:{RISK_COLORS[k]}'></span>{k}",
        unsafe_allow_html=True,
    )
st.sidebar.markdown("<div class='small-note'>Bands adapt when you move the threshold slider.</div>", unsafe_allow_html=True)

# =======================================================
# NATIONAL SITUATION
# =======================================================
if page == "National Situation":
    st.title("National Risk Situation")

    latest_data = hist[hist["month"] == latest_hist_month].copy()
    latest_data["risk_proba"] = pd.to_numeric(latest_data["risk_proba"], errors="coerce").clip(0, 1)

    col1, col2, col3, col4 = st.columns(4)
    col1.metric("Observed Month (Latest)", latest_hist_month.strftime("%B %Y"))
    col2.metric("National Risk Index (Observed)", f"{latest_data['risk_proba'].mean():.2f}")
    col3.metric("Counties Above Threshold (Observed)", int((latest_data["risk_proba"] >= threshold).sum()))
    col4.metric("Projection Month", forecast_month.strftime("%B %Y"))

    fig = go.Figure()
    nat = national.dropna(subset=["month", "national_avg_risk"]).sort_values("month")
    fig.add_trace(go.Scatter(x=nat["month"], y=nat["national_avg_risk"], mode="lines", name="Observed"))

    if not forecast.empty and "risk_proba" in forecast.columns:
        proj_y = float(pd.to_numeric(forecast["risk_proba"], errors="coerce").clip(0, 1).mean())
        fig.add_trace(go.Scatter(x=[forecast_month], y=[proj_y], mode="markers", name="Projection"))
        if len(nat) > 0:
            fig.add_trace(go.Scatter(
                x=[nat["month"].iloc[-1], forecast_month],
                y=[nat["national_avg_risk"].iloc[-1], proj_y],
                mode="lines",
                line=dict(dash="dot"),
                showlegend=False
            ))

    fig.add_hline(y=threshold, line_dash="dot")
    fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
    st.plotly_chart(fig, use_container_width=True)

    st.subheader("Top Counties Above Threshold (Predicted IPC Phase 3+ Risk)")
    top_risk = (
        latest_data[latest_data["risk_proba"] >= threshold]
        .sort_values("risk_proba", ascending=False)
        .head(20)[["county", "risk_proba"]]
        .copy()
    )
    if top_risk.empty:
        st.info("No counties are above the current threshold in the latest observed month.")
    else:
        top_risk["band"] = top_risk["risk_proba"].apply(lambda x: risk_band(x, threshold))
        _, top_sty = styled_df_for_display(top_risk, threshold)
        st.dataframe(top_sty, use_container_width=True)

    with st.expander("IPC Phase Reference", expanded=False):
        st.dataframe(style_ipc_table(ipc_table), use_container_width=True)

# =======================================================
# RISK MAP
# =======================================================
elif page == "Risk Map":
    st.title("County Risk Map")

    view = st.radio("View", ["Historical", "Forecast"], horizontal=True)

    filt = st.radio(
        "Filter",
        ["All", "At Risk (>= threshold)", "Secure (< threshold)"],
        horizontal=True,
    )

    layer_options = ["Predicted IPC Phase 3+ Risk"]
    if ipc_obs is not None and view == "Historical":
        layer_options.append("Observed IPC Phase (Exact 1–5)")
    layer = st.radio("Map Layer", layer_options, horizontal=True)

    if view == "Historical":
        months = sorted(hist["month"].dropna().unique())
        selected_month = st.selectbox("Month", months, index=len(months) - 1)
        display_month = pd.to_datetime(selected_month).to_period("M").to_timestamp()
        df47 = prepare_month_all47(hist, display_month, threshold)
    else:
        if "month" in forecast.columns and not forecast["month"].isna().all():
            display_month = forecast["month"].max()
            df47 = prepare_month_all47(forecast, display_month, threshold)
        else:
            display_month = forecast_month
            df47 = prepare_month_all47(forecast, None, threshold)

    if layer == "Observed IPC Phase (Exact 1–5)":
        df47 = attach_ipc_phase(df47, display_month)

    st.markdown(f"**Displaying:** {display_month.strftime('%B %Y')}")
    st.markdown(f"<div class='small-note'>Map always renders all counties. Filter affects emphasis and the ranked list.</div>", unsafe_allow_html=True)

    df_map = df47.copy()
    df_list = df47.copy()

    if layer == "Predicted IPC Phase 3+ Risk":
        if filt == "At Risk (>= threshold)":
            keep = df47["risk_proba"] >= threshold
            df_list = df47[keep].copy()
            df_map.loc[~keep, "band"] = "Unknown"
        elif filt == "Secure (< threshold)":
            keep = df47["risk_proba"] < threshold
            df_list = df47[keep].copy()
            df_map.loc[~keep, "band"] = "Unknown"
    else:
        phase = pd.to_numeric(df47["ipc_phase"], errors="coerce")
        if filt == "At Risk (>= threshold)":
            keep = phase >= 3
            df_list = df47[keep].copy()
            df_map.loc[~keep, "ipc_phase"] = pd.NA
        elif filt == "Secure (< threshold)":
            keep = phase <= 2
            df_list = df47[keep].copy()
            df_map.loc[~keep, "ipc_phase"] = pd.NA

    left, right = st.columns([2.2, 1.0], gap="large")

    with left:
        if layer == "Predicted IPC Phase 3+ Risk":
            fig = px.choropleth_mapbox(
                df_map,
                geojson=geojson,
                locations="geo_value",
                featureidkey=featureidkey,
                color="band",
                category_orders={"band": RISK_ORDER},
                color_discrete_map=RISK_COLORS,
                hover_name="county",
                hover_data={"risk_proba": ":.3f", "band": True},
                mapbox_style="carto-positron",
                zoom=5.2,
                center={"lat": 0.2, "lon": 37.8},
                opacity=0.85,
                height=650,
            )
            fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, showlegend=False)
            st.plotly_chart(fig, use_container_width=True)
        else:
            df_map["_ipc_phase_str"] = df_map["ipc_phase"].astype("Int64").astype(str)
            df_map.loc[df_map["ipc_phase"].isna(), "_ipc_phase_str"] = "Unknown"

            ipc_color_map = {
                "1": IPC_PHASE_COLORS[1],
                "2": IPC_PHASE_COLORS[2],
                "3": IPC_PHASE_COLORS[3],
                "4": IPC_PHASE_COLORS[4],
                "5": IPC_PHASE_COLORS[5],
                "Unknown": "#6b7280",
            }

            fig = px.choropleth_mapbox(
                df_map,
                geojson=geojson,
                locations="geo_value",
                featureidkey=featureidkey,
                color="_ipc_phase_str",
                category_orders={"_ipc_phase_str": ["1", "2", "3", "4", "5", "Unknown"]},
                color_discrete_map=ipc_color_map,
                hover_name="county",
                hover_data={"ipc_phase": True},
                mapbox_style="carto-positron",
                zoom=5.2,
                center={"lat": 0.2, "lon": 37.8},
                opacity=0.85,
                height=650,
            )
            fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}, showlegend=False)
            st.plotly_chart(fig, use_container_width=True)

        with st.expander("IPC Phase Reference", expanded=False):
            st.dataframe(style_ipc_table(ipc_table), use_container_width=True)

    with right:
        if layer == "Predicted IPC Phase 3+ Risk":
            st.subheader("Counties Sorted by Risk")
            ranked = df_list.sort_values("risk_proba", ascending=False)[["county", "risk_proba"]].copy()
            ranked["band"] = ranked["risk_proba"].apply(lambda x: risk_band(x, threshold))
            _, ranked_sty = styled_df_for_display(ranked, threshold)
            st.dataframe(ranked_sty, use_container_width=True, height=650)
        else:
            st.subheader("Counties by Observed IPC Phase")
            ranked = df_list[["county", "ipc_phase"]].copy()
            ranked = ranked.sort_values(["ipc_phase", "county"], ascending=[False, True])
            st.dataframe(ranked, use_container_width=True, height=650)

# =======================================================
# SCENARIO SIMULATOR
# =======================================================
elif page == "Scenario Simulator":
    st.title("Scenario Simulation")

    counties = sorted([c for c in baseline["county"].dropna().unique() if c])
    county = st.selectbox("Select County", counties)

    base_row = baseline[baseline["county"] == county].copy()
    if base_row.empty:
        st.error("No baseline row found for this county.")
        st.stop()

    for f in FEATURES:
        if f not in base_row.columns:
            base_row[f] = np.nan

    x_base = base_row.iloc[[0]][FEATURES].copy()
    x_edit = x_base.copy()

    st.markdown("<div class='small-note'>Adjust inputs, then run prediction.</div>", unsafe_allow_html=True)

    # Common features if present (renamed to user-friendly labels)
    if "r3q_lag_1" in x_edit.columns:
        x_edit["r3q_lag_1"] = st.number_input(
            humanize_feature_name("r3q_lag_1"),
            value=float(x_edit["r3q_lag_1"].iloc[0]) if pd.notna(x_edit["r3q_lag_1"].iloc[0]) else 0.0,
            help=feature_help_text("r3q_lag_1"),
        )
    if "price_pct_change" in x_edit.columns:
        x_edit["price_pct_change"] = st.number_input(
            humanize_feature_name("price_pct_change"),
            value=float(x_edit["price_pct_change"].iloc[0]) if pd.notna(x_edit["price_pct_change"].iloc[0]) else 0.0,
            help=feature_help_text("price_pct_change"),
        )

    with st.expander("Advanced inputs", expanded=False):
        for f in FEATURES:
            cur = x_edit[f].iloc[0]
            x_edit[f] = st.number_input(
                humanize_feature_name(f),
                value=float(cur) if pd.notna(cur) else 0.0,
                key=f"{county}_{f}",
                help=feature_help_text(f),
            )

    if st.button("Run Prediction", use_container_width=True):
        try:
            base_prob = float(model.predict_proba(x_base)[0][1])
            new_prob = float(model.predict_proba(x_edit)[0][1])
            delta = new_prob - base_prob

            c1, c2, c3 = st.columns(3)
            c1.metric("Baseline Probability (IPC Phase 3+)", f"{base_prob:.4f}")
            c2.metric("Scenario Probability (IPC Phase 3+)", f"{new_prob:.4f}")
            c3.metric("Change (Ξ”)", f"{delta:.4f}")

            band = risk_band(new_prob, threshold)
            st.markdown(
                f"**Risk Band:** {band_badge_html(band)}",
                unsafe_allow_html=True,
            )
            st.markdown("<div class='small-note'>This model outputs IPC Phase 3+ probability. It does not output exact IPC Phase (1–5).</div>", unsafe_allow_html=True)
        except Exception as e:
            st.error(f"Prediction failed: {e}")

# =======================================================
# COUNTY PROFILE
# =======================================================
elif page == "County Profile":
    st.title("County Profile")

    counties = sorted(hist["county"].dropna().unique())
    county = st.selectbox("Select County", counties)

    county_data = hist[hist["county"] == county].sort_values("month").copy()
    county_data = county_data.dropna(subset=["month", "risk_proba"])
    if county_data.empty:
        st.warning("No historical data available for this county.")
        st.stop()

    latest = float(pd.to_numeric(county_data["risk_proba"], errors="coerce").clip(0, 1).iloc[-1])
    latest_band = risk_band(latest, threshold)

    next_prob = get_county_forecast_probability(county)
    next_band = risk_band(next_prob, threshold) if next_prob is not None else "Unknown"

    m1, m2 = st.columns(2)
    with m1:
        st.metric("Latest Risk Probability (IPC Phase 3+)", f"{latest:.2f}")
        st.markdown(f"{band_badge_html(latest_band)}", unsafe_allow_html=True)
    with m2:
        # Next month forecast (e.g., Nov)
        if next_prob is None:
            st.metric(f"Next Month Forecast ({forecast_month.strftime('%B %Y')})", "N/A")
            st.markdown(f"{band_badge_html('Unknown')}", unsafe_allow_html=True)
        else:
            st.metric(f"Next Month Forecast ({forecast_month.strftime('%B %Y')})", f"{float(next_prob):.2f}")
            st.markdown(f"{band_badge_html(next_band)}", unsafe_allow_html=True)

    # Optional: exact observed IPC phase (if file exists)
    if ipc_obs is not None:
        m = county_data["month"].iloc[-1]
        tmp = ipc_obs[(ipc_obs["county"] == county) & (ipc_obs["month"] == m)]
        if not tmp.empty and "ipc_phase" in tmp.columns and pd.notna(tmp["ipc_phase"].iloc[0]):
            st.metric("Observed IPC Phase (Exact)", int(tmp["ipc_phase"].iloc[0]))

    fig = go.Figure()
    fig.add_trace(go.Scatter(x=county_data["month"], y=county_data["risk_proba"], mode="lines+markers", name="Risk"))
    fig.add_hline(y=threshold, line_dash="dot")
    fig.update_layout(height=420, margin=dict(l=10, r=10, t=10, b=10))
    st.plotly_chart(fig, use_container_width=True)

    st.subheader("Historical Levels")
    tbl = county_data[["month", "risk_proba"]].copy()
    tbl["band"] = tbl["risk_proba"].apply(lambda x: risk_band(x, threshold))
    tbl = tbl.sort_values("month", ascending=False)
    _, tbl_sty = styled_df_for_display(tbl, threshold)
    st.dataframe(tbl_sty, use_container_width=True)

    # Rename drivers for normal users + human-friendly feature names
    st.subheader("Key Factors Behind the Risk (Model Drivers)")
    st.markdown("<div class='small-note'>These are the strongest overall factors the model learned from data (global drivers).</div>", unsafe_allow_html=True)

    if "feature" in feature_importance.columns and "importance" in feature_importance.columns:
        top_drivers = (
            feature_importance.dropna(subset=["feature", "importance"])
            .sort_values("importance", ascending=False)
            .head(6)
        )
        for _, r in top_drivers.iterrows():
            f = str(r["feature"])
            st.markdown(f"- **{humanize_feature_name(f)}**")
    else:
        st.info("feature_importance.csv is missing expected columns (feature, importance).")