File size: 37,514 Bytes
803ae2d
63938e5
803ae2d
63938e5
 
 
 
 
 
 
803ae2d
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
 
 
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
 
 
803ae2d
 
 
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
63938e5
 
 
 
803ae2d
 
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
63938e5
803ae2d
 
 
 
63938e5
803ae2d
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
63938e5
 
803ae2d
 
 
 
63938e5
 
 
 
803ae2d
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
 
 
63938e5
 
 
 
 
 
 
 
 
 
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
63938e5
803ae2d
 
 
63938e5
803ae2d
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
 
 
 
 
 
803ae2d
 
 
63938e5
803ae2d
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
63938e5
 
 
803ae2d
 
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63938e5
803ae2d
 
 
 
 
 
 
63938e5
 
803ae2d
 
 
 
 
63938e5
803ae2d
63938e5
 
 
 
 
803ae2d
 
 
 
 
 
 
 
 
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
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
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
import json
import os
import statistics
import time

import pandas as pd
import requests
import streamlit as st


RATE_LIMIT_REQUESTS = 8
RATE_LIMIT_WINDOW_SECONDS = 60
ROUTING_OPTIONS = [
    "Auto-approve",
    "Escalate to manager",
    "Send to committee",
    "Reject",
]
FACTOR_WEIGHTS = {
    "Amount Risk": 0.24,
    "Urgency Risk": 0.19,
    "Category Risk": 0.21,
    "Department Risk": 0.17,
    "Historical Outcome Risk": 0.19,
}


@st.cache_data
def load_history():
    history_df = pd.read_csv("data/historical_approvals.csv")
    history_df["created_at"] = pd.to_datetime(history_df["created_at"], errors="coerce")
    history_df["amount"] = pd.to_numeric(history_df["amount"], errors="coerce")
    history_df["urgency"] = pd.to_numeric(history_df["urgency"], errors="coerce")
    history_df["amount"] = history_df["amount"].fillna(0.0)
    history_df["urgency"] = history_df["urgency"].fillna(0.0)
    history_df["override"] = history_df["override"].astype(str).str.lower().eq("true")
    return history_df


def default_state(history_df):
    departments = sorted(history_df["business_unit"].dropna().unique().tolist())
    categories = sorted(history_df["category"].dropna().unique().tolist())
    return {
        "department_options": departments,
        "category_options": categories,
        "step_unlocked": 1,
        "request_timestamps": [],
        "step1_description": "",
        "step1_department": departments[0] if departments else "Engineering",
        "step1_amount": 0.0,
        "step1_category": categories[0] if categories else "Software",
        "step1_urgency": "Medium",
        "step2_risk_sliders": {},
        "step2_ai": None,
        "step2_adjusted_total": None,
        "step2_similar": None,
        "step2_ai_vs_user": None,
        "step3_suggested_route": None,
        "step3_selected_route": None,
        "step3_route_override_reason": "",
        "step3_confidence": 0.0,
        "step3_explanation": "",
        "step3_gemini_error": None,
        "step4_audit": None,
        "show_sample_toast": False,
    }


def init_state(history_df):
    for key, value in default_state(history_df).items():
        if key not in st.session_state:
            st.session_state[key] = value


def clear_dependent_state():
    st.session_state["step2_risk_sliders"] = {}
    st.session_state["step2_ai"] = None
    st.session_state["step2_adjusted_total"] = None
    st.session_state["step2_similar"] = None
    st.session_state["step2_ai_vs_user"] = None
    st.session_state["step3_suggested_route"] = None
    st.session_state["step3_selected_route"] = None
    st.session_state["step3_route_override_reason"] = ""
    st.session_state["step3_confidence"] = 0.0
    st.session_state["step3_explanation"] = ""
    st.session_state["step3_gemini_error"] = None
    st.session_state["step4_audit"] = None


def start_new_request(history_df):
    preserved = st.session_state.get("request_timestamps", [])
    base = default_state(history_df)
    for key, value in base.items():
        st.session_state[key] = value
    st.session_state["request_timestamps"] = preserved


def load_sample_request():
    st.session_state["step1_description"] = (
        "We need a budget exception to expand Databricks capacity for two enterprise clients "
        "signed in Q4. Without additional spend, analytics SLAs will be missed in 30 days."
    )
    st.session_state["step1_department"] = "Finance"
    st.session_state["step1_amount"] = 84500.0
    st.session_state["step1_category"] = "Cloud Infrastructure"
    st.session_state["step1_urgency"] = "High"
    st.session_state["show_sample_toast"] = True
    clear_dependent_state()
    st.session_state["step_unlocked"] = 1


def check_rate_limit():
    now = time.time()
    timeline = st.session_state.get("request_timestamps", [])
    timeline = [t for t in timeline if now - t <= RATE_LIMIT_WINDOW_SECONDS]
    st.session_state["request_timestamps"] = timeline
    if len(timeline) >= RATE_LIMIT_REQUESTS:
        return False, max(1, int(RATE_LIMIT_WINDOW_SECONDS - (now - timeline[0])))
    timeline.append(now)
    st.session_state["request_timestamps"] = timeline
    return True, 0


def normalized_amount_risk(amount, history_df):
    cap = max(50000.0, float(history_df["amount"].quantile(0.90)))
    return min(1.0, max(0.0, float(amount) / cap))


def urgency_to_score(urgency):
    return {
        "Low": 0.25,
        "Medium": 0.52,
        "High": 0.84,
        "Critical": 0.96,
    }.get(urgency, 0.5)


def to_float(value, default=0.0):
    if isinstance(value, (int, float)):
        return float(value)
    if isinstance(value, str):
        try:
            return float(value)
        except ValueError:
            return float(default)
    return float(default)


def category_historical_risk(history_df, category):
    rows = history_df[history_df["category"] == category].copy()
    if rows.empty:
        return 0.5
    rejected_share = rows["outcome"].eq("Rejected").mean()
    override_share = rows["override"].mean()
    committee_share = rows["routing"].str.contains("Risk|Compliance", case=False, na=False).mean()
    return min(1.0, 0.55 * rejected_share + 0.20 * override_share + 0.25 * committee_share + 0.2)


def department_historical_risk(history_df, department):
    rows = history_df[history_df["business_unit"] == department].copy()
    if rows.empty:
        return 0.5
    rejected_share = rows["outcome"].eq("Rejected").mean()
    high_urgency_share = (rows["urgency"] >= 60).mean()
    return min(1.0, 0.62 * rejected_share + 0.38 * high_urgency_share + 0.15)


def similar_case_risk(history_df, department, category, amount):
    subset = history_df[
        (history_df["business_unit"] == department)
        & (history_df["category"] == category)
    ].copy()
    if subset.empty:
        subset = history_df[history_df["category"] == category].copy()
    if subset.empty:
        subset = history_df.copy()
    subset["amount_diff"] = (subset["amount"] - amount).abs()
    nearest = subset.sort_values(["amount_diff", "created_at"], ascending=[True, False]).head(6)
    rejected_share = nearest["outcome"].eq("Rejected").mean() if not nearest.empty else 0.4
    override_share = nearest["override"].mean() if not nearest.empty else 0.2
    blended = min(1.0, rejected_share * 0.65 + override_share * 0.35 + 0.15)
    return blended, nearest


def compute_heuristic_assessment(request_payload, history_df):
    amount_score = normalized_amount_risk(request_payload["amount"], history_df)
    urgency_score = urgency_to_score(request_payload["urgency"])
    category_score = category_historical_risk(history_df, request_payload["category"])
    department_score = department_historical_risk(history_df, request_payload["department"])
    historical_score, similar = similar_case_risk(
        history_df,
        request_payload["department"],
        request_payload["category"],
        request_payload["amount"],
    )

    factor_scores = {
        "Amount Risk": amount_score,
        "Urgency Risk": urgency_score,
        "Category Risk": category_score,
        "Department Risk": department_score,
        "Historical Outcome Risk": historical_score,
    }

    weighted_total = 0.0
    for name, score in factor_scores.items():
        weighted_total += FACTOR_WEIGHTS[name] * score

    confidence = min(
        0.97,
        max(
            0.56,
            0.60
            + 0.14 * min(1.0, len(similar) / 6)
            + 0.09 * (1.0 - abs(weighted_total - 0.5) * 1.8),
        ),
    )

    baseline = {
        "overall_score": round(float(weighted_total), 4),
        "confidence": round(float(confidence), 4),
        "explanation": "",
        "factors": [
            {
                "name": name,
                "weight": FACTOR_WEIGHTS[name],
                "score": round(float(score), 4),
                "weighted": round(float(FACTOR_WEIGHTS[name] * score), 4),
            }
            for name, score in factor_scores.items()
        ],
    }
    return baseline, similar


def parse_gemini_json(text):
    try:
        payload = json.loads(text)
        if not isinstance(payload, dict):
            return None
        if "overall_score" not in payload or "factors" not in payload:
            return None
        factors = payload.get("factors", [])
        if not isinstance(factors, list):
            return None
        fixed_factors = []
        for item in factors:
            if not isinstance(item, dict):
                continue
            name = str(item.get("name", "")).strip()
            if name not in FACTOR_WEIGHTS:
                continue
            score = float(item.get("score", 0.5))
            fixed_factors.append(
                {
                    "name": name,
                    "weight": FACTOR_WEIGHTS[name],
                    "score": round(min(1.0, max(0.0, score)), 4),
                }
            )
        if len(fixed_factors) < 3:
            return None
        weighted = sum(row["weight"] * row["score"] for row in fixed_factors)
        for row in fixed_factors:
            row["weighted"] = round(row["weight"] * row["score"], 4)
        return {
            "overall_score": round(min(1.0, max(0.0, weighted)), 4),
            "confidence": round(min(0.97, max(0.55, float(payload.get("confidence", 0.68)))), 4),
            "factors": fixed_factors,
            "explanation": str(payload.get("explanation", "")).strip(),
        }
    except (TypeError, ValueError, json.JSONDecodeError):
        return None


def gemini_risk_assessment(request_payload, historical_slice):
    api_key = os.getenv("GEMINI_API_KEY")
    if not api_key:
        return None, "Missing GEMINI_API_KEY"

    preview_cols = [
        "request_id",
        "amount",
        "category",
        "business_unit",
        "urgency",
        "outcome",
        "routing",
        "override",
    ]
    preview_data = historical_slice[preview_cols].head(8).to_dict("records")
    prompt = (
        "You are an approval intelligence scorer. Return strict JSON only with keys: "
        "overall_score (0-1), confidence (0-1), factors (array of 5 objects), explanation. "
        "Each factor object must include name and score. Use these exact factor names: "
        f"{list(FACTOR_WEIGHTS.keys())}. "
        "Score is risk where 1 is highest."
        "\n\n"
        f"Request: {json.dumps(request_payload)}\n"
        f"Historical examples: {json.dumps(preview_data)}"
    )
    body = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {
            "temperature": 0.2,
            "maxOutputTokens": 350,
        },
    }
    endpoint = (
        "https://generativelanguage.googleapis.com/v1beta/models/"
        "gemini-2.5-flash:generateContent"
    )

    try:
        response = requests.post(
            f"{endpoint}?key={api_key}",
            json=body,
            timeout=25,
        )
    except requests.RequestException as exc:
        return None, f"Unable to reach Gemini: {exc}"

    if response.status_code != 200:
        return None, f"Gemini API status {response.status_code}"

    payload = response.json()
    candidates = payload.get("candidates", [])
    if not candidates:
        return None, "Gemini returned no candidates"

    parts = candidates[0].get("content", {}).get("parts", [])
    text = "\n".join(part.get("text", "") for part in parts if part.get("text"))
    parsed = parse_gemini_json(text.strip())
    if parsed is None:
        return None, "Gemini response was not parseable JSON"
    return parsed, None


def route_from_score(score):
    if score < 0.34:
        return "Auto-approve"
    if score < 0.56:
        return "Escalate to manager"
    if score < 0.78:
        return "Send to committee"
    return "Reject"


def explanation_from_assessment(request_payload, ai_assessment, adjusted_total, selected_route):
    factors_sorted = sorted(ai_assessment["factors"], key=lambda item: item["weighted"], reverse=True)
    top_names = ", ".join(item["name"] for item in factors_sorted[:3])
    decision_text = (
        f"The request for ${request_payload['amount']:,.0f} in {request_payload['category']} from "
        f"{request_payload['department']} lands at a risk score of {adjusted_total:.1%}. "
        f"Primary pressure points are {top_names}. "
        f"Given this profile and historical behavior, the decision engine routes it to '{selected_route}' "
        f"with {ai_assessment['confidence']:.1%} confidence."
    )
    return decision_text


def build_audit_trail(history_df):
    ai_data = st.session_state["step2_ai"]
    request_data = {
        "description": st.session_state["step1_description"],
        "department": st.session_state["step1_department"],
        "amount": float(st.session_state["step1_amount"]),
        "category": st.session_state["step1_category"],
        "urgency": st.session_state["step1_urgency"],
        "submitted_at": pd.Timestamp.utcnow().isoformat(),
    }
    slider_map = st.session_state["step2_risk_sliders"]
    adjusted_factors = []
    for factor in ai_data["factors"]:
        name = factor["name"]
        score = float(slider_map.get(name, factor["score"]))
        adjusted_factors.append(
            {
                "name": name,
                "weight": factor["weight"],
                "ai_score": factor["score"],
                "user_adjusted_score": round(score, 4),
                "user_weighted": round(factor["weight"] * score, 4),
            }
        )

    ai_score = float(ai_data["overall_score"])
    user_score = float(st.session_state["step2_adjusted_total"])
    suggested_route = st.session_state["step3_suggested_route"]
    selected_route = st.session_state["step3_selected_route"]
    override_used = suggested_route != selected_route

    similar_df = st.session_state["step2_similar"]
    similar_records = []
    if similar_df is not None and not similar_df.empty:
        for _, row in similar_df.head(8).iterrows():
            similar_records.append(
                {
                    "request_id": str(row.get("request_id", "")),
                    "created_at": str(pd.to_datetime(row.get("created_at"), errors="coerce").date()),
                    "amount": float(row.get("amount", 0.0)),
                    "category": str(row.get("category", "")),
                    "department": str(row.get("business_unit", "")),
                    "outcome": str(row.get("outcome", "")),
                    "routing": str(row.get("routing", "")),
                    "override": bool(row.get("override", False)),
                }
            )

    return {
        "request": request_data,
        "risk_assessment": {
            "ai_overall_score": round(ai_score, 4),
            "user_adjusted_score": round(user_score, 4),
            "confidence": float(st.session_state["step3_confidence"]),
            "factors": adjusted_factors,
            "comparison": st.session_state["step2_ai_vs_user"],
        },
        "routing_decision": {
            "ai_recommendation": suggested_route,
            "final_selection": selected_route,
            "override_used": override_used,
            "override_reason": st.session_state["step3_route_override_reason"].strip(),
            "explanation": st.session_state["step3_explanation"],
        },
        "similar_cases_considered": similar_records,
        "engine_metadata": {
            "rate_limit": f"{RATE_LIMIT_REQUESTS} requests / {RATE_LIMIT_WINDOW_SECONDS}s",
            "model": "gemini-2.5-flash with deterministic fallback",
            "historical_rows": int(len(history_df)),
        },
    }


def factor_table(factors, include_user=False):
    rows = []
    slider_values = st.session_state.get("step2_risk_sliders", {})
    for item in factors:
        name = item["name"]
        row = {
            "Factor": name,
            "Weight": f"{item['weight']:.0%}",
            "AI Score": f"{item['score']:.2f}",
            "AI Weighted": f"{item['weighted']:.2f}",
        }
        if include_user:
            user_score = float(slider_values.get(name, item["score"]))
            row["Your Score"] = f"{user_score:.2f}"
            row["Your Weighted"] = f"{(item['weight'] * user_score):.2f}"
        rows.append(row)
    return pd.DataFrame(rows)


def dataset_view(history_df):
    df = history_df.copy()
    df["created_at"] = df["created_at"].dt.strftime("%Y-%m-%d")
    df["amount"] = df["amount"].map(lambda amt: f"${amt:,.0f}")
    return df


st.set_page_config(
    page_title="Approval Intelligence Engine | Arcalab XYZ",
    page_icon="🧠",
    layout="wide",
)

st.markdown(
    """
    <style>
    @import url('https://fonts.googleapis.com/css2?family=DM+Serif+Display:ital@0;1&family=Manrope:wght@400;500;600;700;800&display=swap');
    .stApp {
        background:
            radial-gradient(1200px 700px at 12% -5%, rgba(45, 186, 167, 0.15), transparent 65%),
            radial-gradient(1000px 550px at 105% 0%, rgba(245, 140, 89, 0.14), transparent 58%),
            linear-gradient(125deg, rgba(14, 17, 23, 0.98), rgba(19, 23, 31, 0.96));
    }
    h1, h2, h3 {
        font-family: 'DM Serif Display', serif;
        letter-spacing: 0.2px;
    }
    html, body, [class*="css"], [data-testid="stMarkdownContainer"], .stCaption, .stText, p, label {
        font-family: 'Manrope', sans-serif;
    }
    .stage-card {
        border: 1px solid rgba(143, 155, 179, 0.24);
        border-radius: 18px;
        padding: 1.1rem 1rem;
        background: linear-gradient(180deg, rgba(24, 29, 39, 0.9), rgba(17, 21, 28, 0.92));
        box-shadow: 0 22px 42px -24px rgba(0, 0, 0, 0.65);
    }
    .locked-card {
        border: 1px dashed rgba(168, 176, 194, 0.45);
        border-radius: 16px;
        padding: 1.1rem 1rem;
        background: linear-gradient(180deg, rgba(29, 33, 44, 0.64), rgba(22, 26, 34, 0.58));
        opacity: 0.62;
    }
    .helper {
        color: rgba(204, 213, 229, 0.82);
        font-size: 0.86rem;
        margin-top: -8px;
        margin-bottom: 6px;
    }
    .value-pill {
        display: inline-block;
        border-radius: 999px;
        border: 1px solid rgba(134, 250, 220, 0.26);
        padding: 6px 10px;
        margin-right: 8px;
        margin-bottom: 8px;
        background: rgba(56, 178, 172, 0.13);
        font-size: 0.8rem;
    }
    .report-card {
        border-radius: 18px;
        border: 1px solid rgba(142, 151, 171, 0.28);
        background: linear-gradient(170deg, rgba(20, 25, 35, 0.92), rgba(14, 18, 24, 0.92));
        padding: 1.15rem 1rem;
    }
    .st-key-step1_sample_link button {
        border: none;
        background: transparent;
        color: #6ddccf;
        text-decoration: underline;
        padding: 0;
        min-height: 0;
        height: auto;
    }
    .st-key-step1_sample_link button:hover {
        color: #9df3ea;
        border: none;
        background: transparent;
    }
    </style>
    """,
    unsafe_allow_html=True,
)

history = load_history()
init_state(history)

st.title("AI-Powered Approval Intelligence Engine")
st.caption(
    "An AI decision engine that auto-scores approval requests and routes them through smart automation with transparent confidence scores."
)

if st.session_state["show_sample_toast"]:
    st.toast("Sample request loaded. Tweak details, then run analysis.")
    st.session_state["show_sample_toast"] = False

tabs = st.tabs(
    [
        "1. Describe Request",
        "2. Risk Assessment",
        "3. Routing Decision",
        "4. Decision Summary",
    ]
)

with tabs[0]:
    st.markdown("<div class='stage-card'>", unsafe_allow_html=True)
    st.subheader("Describe Your Request")
    st.write(
        "Start with plain language, then add quick configuration details. The request stays empty by default so you can model real scenarios."
    )

    st.text_area(
        "Describe the approval request in your own words",
        key="step1_description",
        placeholder=(
            "Example: We need a temporary budget override to expand cloud analytics capacity "
            "for two signed enterprise contracts while existing spend is capped."
        ),
        height=160,
    )
    st.caption("Describe business impact, constraints, and why timing matters.")

    c1, c2 = st.columns(2)
    with c1:
        st.selectbox(
            "Department",
            options=st.session_state["department_options"],
            key="step1_department",
        )
        st.markdown("<div class='helper'>Who owns budget accountability for this request.</div>", unsafe_allow_html=True)
    with c2:
        st.number_input(
            "Amount (USD)",
            min_value=0.0,
            max_value=5000000.0,
            step=500.0,
            key="step1_amount",
        )
        st.markdown("<div class='helper'>Total spend requested for approval.</div>", unsafe_allow_html=True)

    c3, c4 = st.columns(2)
    with c3:
        st.selectbox(
            "Category",
            options=st.session_state["category_options"],
            key="step1_category",
        )
        st.markdown("<div class='helper'>Used to match precedent and policy risk patterns.</div>", unsafe_allow_html=True)
    with c4:
        st.selectbox(
            "Urgency",
            options=["Low", "Medium", "High", "Critical"],
            key="step1_urgency",
        )
        st.markdown("<div class='helper'>Higher urgency increases scrutiny when precedent is weak.</div>", unsafe_allow_html=True)

    st.button("Try with sample", key="step1_sample_link", on_click=load_sample_request)

    analyze_clicked = st.button("Analyze Request ->", type="primary", use_container_width=True)

    if analyze_clicked:
        message_holder = st.empty()
        clean_description = st.session_state["step1_description"].strip()
        if not clean_description:
            message_holder.warning("Please describe the request before running analysis.")
        elif st.session_state["step1_amount"] <= 0:
            message_holder.warning("Amount must be greater than 0 to assess risk.")
        else:
            allowed, wait_seconds = check_rate_limit()
            if not allowed:
                message_holder.error(
                    f"Rate limit reached: max {RATE_LIMIT_REQUESTS} requests per {RATE_LIMIT_WINDOW_SECONDS}s. Try again in ~{wait_seconds}s."
                )
            else:
                request_payload = {
                    "description": clean_description,
                    "department": st.session_state["step1_department"],
                    "amount": float(st.session_state["step1_amount"]),
                    "category": st.session_state["step1_category"],
                    "urgency": st.session_state["step1_urgency"],
                }

                clear_dependent_state()

                with st.spinner("Scoring 5 risk factors..."):
                    heuristic_assessment, similar_df = compute_heuristic_assessment(request_payload, history)
                    gemini_assessment, gemini_error = gemini_risk_assessment(request_payload, similar_df)

                with st.spinner("Finding similar cases..."):
                    similar_df = similar_df.copy()
                    similar_df["created_at"] = pd.to_datetime(similar_df["created_at"], errors="coerce")

                ai_assessment = gemini_assessment if gemini_assessment else heuristic_assessment
                factors_raw = ai_assessment.get("factors", []) if isinstance(ai_assessment, dict) else []
                factors = factors_raw if isinstance(factors_raw, list) else []
                overall_score = to_float(ai_assessment.get("overall_score", 0.5), 0.5) if isinstance(ai_assessment, dict) else 0.5
                confidence_score = to_float(
                    ai_assessment.get("confidence", heuristic_assessment["confidence"]),
                    to_float(heuristic_assessment["confidence"], 0.65),
                ) if isinstance(ai_assessment, dict) else to_float(heuristic_assessment["confidence"], 0.65)
                explanation_text = str(ai_assessment.get("explanation", "")).strip() if isinstance(ai_assessment, dict) else ""

                slider_defaults = {
                    str(row.get("name", "Factor")): to_float(row.get("score", 0.5), 0.5)
                    for row in factors
                    if isinstance(row, dict) and row.get("name")
                }
                st.session_state["step2_risk_sliders"] = slider_defaults
                st.session_state["step2_ai"] = ai_assessment
                st.session_state["step2_adjusted_total"] = overall_score
                st.session_state["step2_similar"] = similar_df
                st.session_state["step2_ai_vs_user"] = {
                    "ai": overall_score,
                    "user": overall_score,
                }

                suggested_route = route_from_score(overall_score)
                st.session_state["step3_suggested_route"] = suggested_route
                st.session_state["step3_selected_route"] = suggested_route
                st.session_state["step3_confidence"] = confidence_score

                if not explanation_text:
                    explanation_text = explanation_from_assessment(
                        request_payload,
                        ai_assessment,
                        overall_score,
                        suggested_route,
                    )
                st.session_state["step3_explanation"] = explanation_text
                st.session_state["step3_gemini_error"] = gemini_error
                st.session_state["step_unlocked"] = 2
                message_holder.success("Assessment complete. Move to Step 2.")

    st.markdown("</div>", unsafe_allow_html=True)

with tabs[1]:
    unlocked = st.session_state["step_unlocked"] >= 2 and st.session_state["step2_ai"] is not None
    if not unlocked:
        st.markdown("<div class='locked-card'>", unsafe_allow_html=True)
        st.subheader("Risk Assessment")
        st.write("Complete Step 1 to unlock AI risk analysis, adjustable factor sliders, and similar-case evidence.")
        st.markdown("</div>", unsafe_allow_html=True)
    else:
        st.markdown("<div class='stage-card'>", unsafe_allow_html=True)
        st.subheader("Risk Assessment")
        st.write("Review AI factor weights, adjust what you disagree with, and watch total risk recalculate live.")

        ai_assessment = st.session_state["step2_ai"]
        slider_values = {}
        for item in ai_assessment["factors"]:
            slider_values[item["name"]] = st.slider(
                f"{item['name']} ({item['weight']:.0%} weight)",
                min_value=0.0,
                max_value=1.0,
                value=float(st.session_state["step2_risk_sliders"].get(item["name"], item["score"])),
                step=0.01,
                key=f"slider_{item['name']}",
            )

        adjusted_total = sum(
            FACTOR_WEIGHTS[name] * score for name, score in slider_values.items()
        )
        st.session_state["step2_risk_sliders"] = slider_values
        st.session_state["step2_adjusted_total"] = float(adjusted_total)
        st.session_state["step2_ai_vs_user"] = {
            "ai": float(ai_assessment["overall_score"]),
            "user": float(adjusted_total),
        }
        st.session_state["step3_suggested_route"] = route_from_score(float(adjusted_total))
        if st.session_state["step3_selected_route"] not in ROUTING_OPTIONS:
            st.session_state["step3_selected_route"] = st.session_state["step3_suggested_route"]

        metric_c1, metric_c2, metric_c3 = st.columns(3)
        metric_c1.metric("AI Assessment", f"{float(ai_assessment['overall_score']):.1%}")
        metric_c2.metric("Your Adjusted Assessment", f"{float(adjusted_total):.1%}")
        metric_c3.metric(
            "Delta",
            f"{(float(adjusted_total) - float(ai_assessment['overall_score'])):+.1%}",
        )

        compare_left, compare_right = st.columns(2)
        with compare_left:
            st.markdown("**AI Assessment**")
            st.dataframe(factor_table(ai_assessment["factors"]), use_container_width=True, hide_index=True)
        with compare_right:
            st.markdown("**Your Adjusted Assessment**")
            st.dataframe(
                factor_table(ai_assessment["factors"], include_user=True),
                use_container_width=True,
                hide_index=True,
            )

        st.markdown("**Similar Past Decisions**")
        similar_df = st.session_state["step2_similar"]
        if similar_df is not None and not similar_df.empty:
            view = similar_df.copy()
            view["created_at"] = pd.to_datetime(view["created_at"], errors="coerce").dt.strftime("%Y-%m-%d")
            view["amount"] = view["amount"].map(lambda v: f"${v:,.0f}")
            display = view[
                [
                    "request_id",
                    "created_at",
                    "business_unit",
                    "category",
                    "amount",
                    "urgency",
                    "outcome",
                    "routing",
                    "override",
                ]
            ].rename(
                columns={
                    "business_unit": "department",
                }
            )
            st.dataframe(display, use_container_width=True, hide_index=True)
        else:
            st.info("No similar historical cases matched this request.")

        continue_step3 = st.button("Continue to Routing ->", type="primary", use_container_width=True)
        if continue_step3:
            st.session_state["step_unlocked"] = max(3, st.session_state["step_unlocked"])
            st.success("Routing step unlocked.")

        st.markdown("</div>", unsafe_allow_html=True)

with tabs[2]:
    unlocked = st.session_state["step_unlocked"] >= 3 and st.session_state["step2_ai"] is not None
    if not unlocked:
        st.markdown("<div class='locked-card'>", unsafe_allow_html=True)
        st.subheader("Routing Decision")
        st.write("Complete Step 2 first to produce a calibrated risk score and unlock routing controls.")
        st.markdown("</div>", unsafe_allow_html=True)
    else:
        st.markdown("<div class='stage-card'>", unsafe_allow_html=True)
        st.subheader("Routing Decision")
        st.write("Choose the final path. You can accept the recommendation or override it with accountability.")

        adjusted_score = float(st.session_state["step2_adjusted_total"])
        suggested_route = route_from_score(adjusted_score)
        st.session_state["step3_suggested_route"] = suggested_route

        score_band = "Low" if adjusted_score < 0.34 else "Moderate" if adjusted_score < 0.56 else "Elevated" if adjusted_score < 0.78 else "Severe"
        st.markdown(
            """
            <div>
                <span class='value-pill'>Risk Band: {}</span>
                <span class='value-pill'>AI Route: {}</span>
            </div>
            """.format(score_band, suggested_route),
            unsafe_allow_html=True,
        )

        selected_route = st.radio(
            "Routing path",
            ROUTING_OPTIONS,
            index=ROUTING_OPTIONS.index(st.session_state["step3_selected_route"])
            if st.session_state["step3_selected_route"] in ROUTING_OPTIONS
            else ROUTING_OPTIONS.index(suggested_route),
            key="step3_selected_route",
            horizontal=False,
        )

        override_active = selected_route != suggested_route
        if override_active:
            st.text_input(
                "Reason for override",
                key="step3_route_override_reason",
                placeholder="Explain why the final route should differ from the model recommendation.",
            )

        confidence = float(st.session_state["step3_confidence"])
        st.write("**Confidence Meter**")
        st.progress(min(1.0, max(0.0, confidence)), text=f"{confidence:.1%} confidence")

        st.write("**AI Explanation**")
        request_payload = {
            "description": st.session_state["step1_description"],
            "department": st.session_state["step1_department"],
            "amount": float(st.session_state["step1_amount"]),
            "category": st.session_state["step1_category"],
            "urgency": st.session_state["step1_urgency"],
        }
        live_explanation = explanation_from_assessment(
            request_payload,
            st.session_state["step2_ai"],
            adjusted_score,
            selected_route,
        )
        if st.session_state["step3_gemini_error"]:
            st.info(f"Gemini unavailable, using heuristic explanation: {st.session_state['step3_gemini_error']}")
        st.write(live_explanation)
        st.session_state["step3_explanation"] = live_explanation

        can_finalize = True
        if override_active and not st.session_state["step3_route_override_reason"].strip():
            can_finalize = False
            st.warning("Add a reason for override before finalizing.")

        finalize = st.button("Finalize Decision ->", type="primary", use_container_width=True, disabled=not can_finalize)
        if finalize:
            st.session_state["step4_audit"] = build_audit_trail(history)
            st.session_state["step_unlocked"] = max(4, st.session_state["step_unlocked"])
            st.success("Decision finalized. Review audit trail in Step 4.")

        st.markdown("</div>", unsafe_allow_html=True)

with tabs[3]:
    unlocked = st.session_state["step_unlocked"] >= 4 and st.session_state["step4_audit"] is not None
    if not unlocked:
        st.markdown("<div class='locked-card'>", unsafe_allow_html=True)
        st.subheader("Decision Summary & Audit Trail")
        st.write("Finalize the routing decision in Step 3 to generate a complete audit report and export package.")
        st.markdown("</div>", unsafe_allow_html=True)
    else:
        audit = st.session_state["step4_audit"]
        st.markdown("<div class='report-card'>", unsafe_allow_html=True)
        st.subheader("Decision Summary & Audit Trail")
        st.write("A full audit-grade report of request inputs, AI assessment, user adjustments, and final routing outcome.")

        req = audit["request"]
        st.markdown("**Original Request**")
        req_col_1, req_col_2, req_col_3 = st.columns(3)
        req_col_1.metric("Department", req["department"])
        req_col_2.metric("Category", req["category"])
        req_col_3.metric("Amount", f"${req['amount']:,.0f}")
        st.write(req["description"])

        st.markdown("**Risk Assessment**")
        risk = audit["risk_assessment"]
        risk_col_1, risk_col_2, risk_col_3 = st.columns(3)
        risk_col_1.metric("AI Score", f"{risk['ai_overall_score']:.1%}")
        risk_col_2.metric("Adjusted Score", f"{risk['user_adjusted_score']:.1%}")
        risk_col_3.metric("Confidence", f"{risk['confidence']:.1%}")

        factor_rows = []
        for row in risk["factors"]:
            factor_rows.append(
                {
                    "factor": row["name"],
                    "weight": f"{row['weight']:.0%}",
                    "ai_score": f"{row['ai_score']:.2f}",
                    "user_score": f"{row['user_adjusted_score']:.2f}",
                    "user_weighted": f"{row['user_weighted']:.2f}",
                }
            )
        st.dataframe(pd.DataFrame(factor_rows), use_container_width=True, hide_index=True)

        st.markdown("**Routing Decision**")
        route = audit["routing_decision"]
        routing_col_1, routing_col_2 = st.columns(2)
        routing_col_1.metric("AI Recommendation", route["ai_recommendation"])
        routing_col_2.metric("Final Selection", route["final_selection"])
        if route["override_used"]:
            st.warning(f"Override reason: {route['override_reason']}")
        st.write(route["explanation"])

        export_payload = json.dumps(audit, indent=2)
        st.download_button(
            "Download Decision Trail (JSON)",
            data=export_payload,
            file_name="approval_decision_audit_trail.json",
            mime="application/json",
            use_container_width=True,
        )

        st.button(
            "Start New Request",
            use_container_width=True,
            on_click=start_new_request,
            args=(history,),
        )
        st.markdown("</div>", unsafe_allow_html=True)

st.markdown("---")
with st.expander("Historical Dataset", expanded=False):
    st.write(
        f"{len(history)} decisions loaded. This historical set is used for similarity matching, trend learning, and fallback scoring."
    )
    st.dataframe(dataset_view(history), use_container_width=True, hide_index=True)
    st.download_button(
        "Download historical CSV",
        data=history.to_csv(index=False),
        file_name="historical_approvals.csv",
        mime="text/csv",
    )

try:
    history_reject_rate = history["outcome"].eq("Rejected").mean()
    history_override_rate = history["override"].mean()
    avg_amount = statistics.mean(history["amount"].tolist()) if len(history) > 0 else 0.0
    st.caption(
        f"Engine baseline: {history_reject_rate:.1%} reject rate, {history_override_rate:.1%} override rate, ${avg_amount:,.0f} average request size."
    )
except Exception:
    st.caption("Engine baseline available after historical data loads.")