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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e978f7
64fb1e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
"""
Fin fintech tool implementations.
All async. Called only via execute_with_recovery() β€” never directly.
"""
import asyncio
import json
import logging
import uuid as _uuid
from datetime import datetime, timezone, timedelta

import httpx
from sqlalchemy import text

import database as _db_module
from config import settings
from constants.transaction_status import (
    FAILED, COMPLETED, FLAGGED, PENDING, PROCESSING, CANCELLED, EXPIRED,
    REFUND_INITIATED, REFUND_PROCESSING, REFUND_COMPLETED,
    KYC_HOLD, COMPLIANCE_HOLD,
    DISPUTED, CHARGEBACK_INITIATED, CHARGEBACK_WON, CHARGEBACK_LOST,
    FRAUD_REPORTED, FRAUD_CONFIRMED, FRAUD_REVERSED,
)
from session.call_session import get_session, ACTIVE_CALLS

logger = logging.getLogger(__name__)


# ── escalate_to_human ─────────────────────────────────────────────────────────

async def escalate_to_human(
    reason: str,
    lead_summary: str,
    call_id: str,
) -> dict:
    """
    Marks the call as escalated and notifies the agent desktop via WebSocket.
    Builds an EscalationPacket from session state and sends it.
    """
    from models.escalation_packet import build_escalation_packet
    from voice.events import emit, EscalationRequestedEvent

    session = get_session(call_id)
    if not session:
        logger.error(f"[{call_id}] escalate_to_human: no active session")
        return {"success": False, "fast_response_key": "tool_error"}

    if session.escalated:
        return {"success": True, "fast_response_key": "already_escalated"}

    # No identity gate here β€” the orchestrator already enforces two-step escalation
    # confirmation before escalate_to_human is available to the LLM.
    # Unverified customers (FAQ-only callers) escalate with a conversation-history
    # bundle; the specialist can verify them directly.

    packet = build_escalation_packet(session, reason=reason)
    packet_dict = packet.to_dict() if packet else {}

    if packet:
        await emit(EscalationRequestedEvent(
            call_id=call_id,
            reason=reason,
            packet=packet,
        ))

    session.escalated = True
    session.conv_state.mark_escalated()

    # Text-to-TTS model: no separate room needed. Agent types β†’ agent-say endpoint
    # sends LiveKit data message β†’ worker calls agent_session.say(text).
    esc_room_name: str | None = None
    customer_esc_token: str | None = None
    agent_esc_token: str | None = None

    # Update call record β€” asyncpg requires UUID objects for UUID columns
    async with _db_module.AsyncSessionLocal() as db:
        await db.execute(
            text("""
                UPDATE calls
                SET escalated = TRUE,
                    escalation_reason = :reason,
                    escalation_at = NOW()
                WHERE id = :call_id
            """),
            {"reason": reason, "call_id": _uuid.UUID(call_id)},
        )
        await db.commit()

    logger.info(json.dumps({
        "call_id": call_id, "tool": "escalate_to_human", "reason": reason,
    }))

    return {
        "success": True,
        "fast_response_key": "escalating",
        "handoff_bundle": packet_dict,
        "esc_room_name": esc_room_name,
        "customer_esc_token": customer_esc_token,
        "agent_esc_token": agent_esc_token,
        "livekit_url": settings.livekit_url,
    }


# ── verify_account ────────────────────────────────────────────────────────────

import re as _re

def _normalize_phone_digits(raw: str) -> str:
    return _re.sub(r"[^\d]", "", raw)


async def verify_account(phone: str, call_id: str) -> dict:
    """
    Look up a customer by phone number and cache the customer_id on the session.
    Returns masked identity fields only β€” raw PII never reaches the LLM.
    """
    digits = _normalize_phone_digits(phone)

    row = None
    async with _db_module.AsyncSessionLocal() as db:
        result = await db.execute(
            text("""
                SELECT id, name, phone, email, account_type,
                       account_status, fraud_hold_active, kyc_status
                FROM customers
                WHERE regexp_replace(phone, '[^0-9]', '', 'g') = :v
            """),
            {"v": digits},
        )
        row = result.mappings().first()

        if not row and len(digits) >= 7:
            for suffix_len in (len(digits), len(digits) - 1, 10):
                if suffix_len < 7:
                    break
                suffix = digits[-suffix_len:] if suffix_len < len(digits) else digits
                result = await db.execute(
                    text("""
                        SELECT id, name, phone, email, account_type,
                               account_status, fraud_hold_active, kyc_status
                        FROM customers
                        WHERE regexp_replace(phone, '[^0-9]', '', 'g') LIKE :suffix
                    """),
                    {"suffix": f"%{suffix}"},
                )
                row = result.mappings().first()
                if row:
                    break

        if not row:
            session = get_session(call_id)
            if session:
                session.verify_account_attempts += 1
            attempts = session.verify_account_attempts if session else 1
            logger.info(json.dumps({"call_id": call_id, "tool": "verify_account", "found": False, "attempts": attempts}))
            return {
                "success": False,
                "found": False,
                "attempts": attempts,
                "fast_response_key": "account_not_found",
            }

        cid = row["id"]

        # Load transactions
        txn_result = await db.execute(
            text("""
                SELECT txn_number, merchant, amount, currency, txn_type,
                       status, txn_date, gateway_ref
                FROM transactions
                WHERE customer_id = :cid
                ORDER BY txn_date DESC
            """),
            {"cid": cid},
        )
        transactions = [
            {
                "txn_number":  r["txn_number"],
                "merchant":    r["merchant"],
                "amount":      float(r["amount"]),
                "currency":    r["currency"],
                "txn_type":    r["txn_type"],
                "status":      r["status"],
                "txn_date":    str(r["txn_date"]),
                "gateway_ref": r["gateway_ref"],
            }
            for r in txn_result.mappings().all()
        ]

        # Load active account holds
        holds_result = await db.execute(
            text("""
                SELECT hold_type, status, reason, placed_at
                FROM account_holds
                WHERE customer_id = :cid AND status = 'active'
                ORDER BY placed_at DESC
            """),
            {"cid": cid},
        )
        account_holds_data = [
            {
                "hold_type": r["hold_type"],
                "reason":    r["reason"],
                "placed_at": str(r["placed_at"]) if r["placed_at"] else None,
            }
            for r in holds_result.mappings().all()
        ]

        # Load non-terminal refunds (initiated / processing)
        refunds_result = await db.execute(
            text("""
                SELECT r.rfn_number, r.amount AS refund_amount, r.status,
                       r.initiated_at, t.txn_number AS transaction_id, t.merchant
                FROM refunds r
                JOIN transactions t ON r.transaction_id = t.id
                WHERE r.customer_id = :cid
                  AND r.status NOT IN ('completed', 'rejected')
                ORDER BY r.initiated_at DESC
            """),
            {"cid": cid},
        )
        open_refunds = [
            {
                "rfn_number":     r["rfn_number"],
                "transaction_id": r["transaction_id"],
                "merchant":       r["merchant"],
                "amount":         float(r["refund_amount"]),
                "status":         r["status"],
                "initiated_at":   str(r["initiated_at"]) if r["initiated_at"] else None,
            }
            for r in refunds_result.mappings().all()
        ]

        # Load non-terminal disputes (open / under_review)
        disputes_result = await db.execute(
            text("""
                SELECT d.dsp_number, d.reason, d.status, d.opened_at,
                       t.txn_number AS transaction_id, t.merchant,
                       t.amount AS txn_amount
                FROM disputes d
                JOIN transactions t ON d.transaction_id = t.id
                WHERE d.customer_id = :cid
                  AND d.status NOT IN ('resolved_won', 'resolved_lost', 'closed')
                ORDER BY d.opened_at DESC
            """),
            {"cid": cid},
        )
        open_disputes = [
            {
                "dsp_number":     r["dsp_number"],
                "transaction_id": r["transaction_id"],
                "merchant":       r["merchant"],
                "amount":         float(r["txn_amount"]),
                "reason":         r["reason"],
                "status":         r["status"],
                "opened_at":      str(r["opened_at"]) if r["opened_at"] else None,
            }
            for r in disputes_result.mappings().all()
        ]

        # Load active fraud cases under review
        fraud_result = await db.execute(
            text("""
                SELECT fc.fraud_number, fc.fraud_type, fc.status, fc.risk_level,
                       fc.hold_placed_at, t.txn_number AS transaction_id
                FROM fraud_cases fc
                LEFT JOIN transactions t ON fc.transaction_id = t.id
                WHERE fc.customer_id = :cid AND fc.status = 'under_review'
                ORDER BY fc.hold_placed_at DESC
            """),
            {"cid": cid},
        )
        active_fraud_cases = [
            {
                "fraud_number":   r["fraud_number"],
                "transaction_id": r["transaction_id"],
                "fraud_type":     r["fraud_type"],
                "risk_level":     r["risk_level"],
                "status":         r["status"],
                "hold_placed_at": str(r["hold_placed_at"]) if r["hold_placed_at"] else None,
            }
            for r in fraud_result.mappings().all()
        ]

    customer_id = str(row["id"])
    name = row["name"] or ""
    phone_raw = row["phone"] or ""
    email_raw = row["email"] or ""

    masked_phone = f"***{phone_raw[-3:]}" if len(phone_raw) >= 3 else "***"
    at = email_raw.find("@")
    masked_email = (
        f"{email_raw[:2]}***{email_raw[at:]}" if at > 2 else "***"
    )
    first_name = name.split()[0] if name else "customer"

    session = get_session(call_id)
    if session:
        session.customer_id = customer_id
        session.verify_account_attempts = 0
        session.customer_profile = {
            "name":               name,
            "first_name":         first_name,
            "email":              email_raw,
            "phone":              phone_raw,
            "account_type":       row["account_type"] or "standard",
            "account_status":     row["account_status"] or "active",
            "fraud_hold_active":  bool(row["fraud_hold_active"]),
            "kyc_status":         row["kyc_status"] or "pending",
            "masked_phone":       masked_phone,
            "masked_email":       masked_email,
            "transactions":       transactions,
            "account_holds":      account_holds_data,
            "open_refunds":       open_refunds,
            "open_disputes":      open_disputes,
            "active_fraud_cases": active_fraud_cases,
        }

    logger.info(json.dumps({
        "call_id": call_id, "tool": "verify_account",
        "customer_id": customer_id, "found": True,
    }))

    fraud_note = (
        f"Active fraud cases ({len(active_fraud_cases)}): " +
        ", ".join(
            f"{fc['fraud_number']} ({fc['fraud_type']}, {fc['status']})"
            for fc in active_fraud_cases
        )
        if active_fraud_cases
        else "NO fraud cases on record for this customer. Do NOT mention, imply, or invent any fraud case or fraud reference number."
    )

    return {
        "success": True,
        "found": True,
        "customer_id": customer_id,
        "first_name": first_name,
        "account_type": row["account_type"] or "standard",
        "masked_phone": masked_phone,
        "masked_email": masked_email,
        "fraud_cases": fraud_note,
        "fast_response_key": "account_verified",
        "template_vars": {"name": first_name},
    }


# ── lookup_transaction ────────────────────────────────────────────────────────

async def lookup_transaction(transaction_id: str, call_id: str) -> dict:
    """
    Look up a transaction by txn_number for the verified customer.
    Uses session cache populated by verify_account; falls back to DB.
    """
    session = get_session(call_id)
    customer_id = getattr(session, "customer_id", None) if session else None

    if not customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    txn_id_upper = transaction_id.upper()
    cached_profile = getattr(session, "customer_profile", None) if session else None

    if cached_profile is not None:
        transactions = cached_profile.get("transactions") or []
        match = next(
            (t for t in transactions if str(t.get("txn_number", "")).upper() == txn_id_upper),
            None,
        )
    else:
        async with _db_module.AsyncSessionLocal() as db:
            result = await db.execute(
                text("""
                    SELECT txn_number, merchant, amount, currency, txn_type,
                           status, txn_date, gateway_ref
                    FROM transactions
                    WHERE customer_id = :cid AND UPPER(txn_number) = :txn
                """),
                {"cid": _uuid.UUID(customer_id), "txn": txn_id_upper},
            )
            row = result.mappings().first()
        if not row:
            return {"success": True, "found": False, "fast_response_key": "transaction_not_found"}
        match = dict(row)

    if not match:
        logger.info(json.dumps({
            "call_id": call_id, "tool": "lookup_transaction",
            "transaction_id": transaction_id, "found": False,
        }))
        return {"success": True, "found": False, "fast_response_key": "transaction_not_found"}

    logger.info(json.dumps({
        "call_id": call_id, "tool": "lookup_transaction",
        "transaction_id": transaction_id, "found": True,
        "status": match.get("status"),
    }))

    txn_num = match.get("txn_number", transaction_id)
    return {
        "success": True,
        "found": True,
        "transaction_id": txn_num,
        "merchant": match.get("merchant"),
        "amount": match.get("amount"),
        "type": match.get("txn_type"),
        "status": match.get("status"),
        "date": match.get("txn_date"),
        "fast_response_key": "transaction_found",
        "template_vars": {
            "transaction_id": txn_num,
            "merchant": match.get("merchant"),
            "amount": match.get("amount"),
            "status": match.get("status"),
        },
    }


# ── send_otp ─────────────────────────────────────────────────────────────────

import random as _random

async def send_otp(call_id: str) -> dict:
    """Generate a 6-digit demo OTP and store it on the session.
    Enforces: 30s resend cooldown, 5 sends/session max.
    """
    session = get_session(call_id)
    if not session:
        return {"success": False}

    # Cooldown: 10s minimum between sends (voice calls are real-time)
    if session.otp_sent_at:
        elapsed = (datetime.now(timezone.utc) - session.otp_sent_at).total_seconds()
        if elapsed < 10:
            return {
                "success": False,
                "fast_response_key": "otp_cooldown",
                "retry_in_seconds": int(10 - elapsed),
            }

    # Cap total sends this session
    if session.otp_resend_count >= 5:
        return {"success": False, "fast_response_key": "otp_resend_limit"}

    otp = str(_random.randint(100000, 999999))
    session.otp_code = otp
    session.otp_verified = False
    session.otp_sent_at = datetime.now(timezone.utc)
    session.otp_attempts = 0       # reset wrong-code counter on each new send
    session.otp_locked = False
    session.otp_resend_count += 1

    logger.info(json.dumps({"call_id": call_id, "tool": "send_otp",
                             "resend_count": session.otp_resend_count}))
    return {"success": True, "otp": otp, "fast_response_key": "otp_sent"}


# ── verify_otp ────────────────────────────────────────────────────────────────

async def verify_otp(otp_input: str, call_id: str) -> dict:
    """Validate the OTP entered by the customer.
    Enforces: 5-min expiry, 3-attempt lock, locked-state guard.
    """
    session = get_session(call_id)
    if not session or not session.otp_code:
        return {"success": False, "fast_response_key": "no_otp_pending"}

    # Expiry check (5 minutes)
    if session.otp_sent_at:
        elapsed = (datetime.now(timezone.utc) - session.otp_sent_at).total_seconds()
        if elapsed > 300:
            session.otp_code = None
            logger.info(json.dumps({"call_id": call_id, "tool": "verify_otp", "result": "expired"}))
            return {"success": False, "fast_response_key": "otp_expired"}

    # Already locked after 3 failures
    if session.otp_locked:
        return {"success": False, "fast_response_key": "otp_max_attempts"}

    clean = otp_input.strip().replace(" ", "").replace("-", "")
    session.otp_attempts += 1

    if clean == session.otp_code:
        session.otp_verified = True
        logger.info(json.dumps({"call_id": call_id, "tool": "verify_otp", "result": "success"}))
        return {"success": True, "fast_response_key": "otp_verified"}

    # Wrong code
    if session.otp_attempts >= 3:
        session.otp_locked = True
        logger.info(json.dumps({"call_id": call_id, "tool": "verify_otp",
                                 "result": "locked", "attempts": session.otp_attempts}))
        return {"success": False, "fast_response_key": "otp_max_attempts"}

    remaining = 3 - session.otp_attempts
    logger.info(json.dumps({"call_id": call_id, "tool": "verify_otp",
                             "result": "wrong", "attempts": session.otp_attempts,
                             "remaining": remaining}))
    return {"success": False, "fast_response_key": "otp_wrong",
            "attempts_remaining": remaining}


# ── unlock_account ────────────────────────────────────────────────────────────

async def unlock_account(call_id: str) -> dict:
    """Unlock the verified customer's account. Requires otp_verified on session."""
    session = get_session(call_id)
    if not session or not session.otp_verified:
        return {"success": False, "fast_response_key": "verification_required"}
    if not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    async with _db_module.AsyncSessionLocal() as db:
        result = await db.execute(
            text("""
                SELECT account_status, fraud_hold_active, kyc_status
                FROM customers WHERE id = :id
            """),
            {"id": _uuid.UUID(session.customer_id)},
        )
        row = result.mappings().first()

    if not row:
        return {"success": False, "fast_response_key": "account_not_found"}

    if row["fraud_hold_active"]:
        return {"success": False, "fast_response_key": "fraud_lock"}
    if row["account_status"] == "frozen":
        return {"success": False, "fast_response_key": "compliance_hold"}

    async with _db_module.AsyncSessionLocal() as db:
        await db.execute(
            text("""
                UPDATE customers
                SET account_status = 'active',
                    account_locked_at = NULL,
                    account_locked_reason = NULL
                WHERE id = :id
            """),
            {"id": _uuid.UUID(session.customer_id)},
        )
        await db.commit()

    logger.info(json.dumps({"call_id": call_id, "tool": "unlock_account", "customer_id": session.customer_id}))
    return {"success": True, "fast_response_key": "account_unlocked"}


# ── initiate_refund ───────────────────────────────────────────────────────────

async def initiate_refund(transaction_id: str, call_id: str) -> dict:
    """Initiate a refund for a failed transaction.
    Pre-checks transaction status before writing. Idempotent within session.
    Requires OTP verification (otp_verified=True) before executing.
    """
    session = get_session(call_id)
    if not session or not session.otp_verified:
        logger.warning(json.dumps({
            "call_id": call_id,
            "tool": "initiate_refund",
            "event": "blocked_otp_not_verified",
            "otp_verified": getattr(session, "otp_verified", None),
        }))
        return {"success": False, "fast_response_key": "verification_required"}
    if not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    txn_upper = transaction_id.upper()

    # Idempotency: if a refund case was already opened this session, don't re-initiate
    if session.refund_case_id:
        return {
            "success": False,
            "fast_response_key": "refund_already_initiated",
            "refund_case_id": session.refund_case_id,
            "estimated_days": "3–5 business days",
        }

    from utils.ref_numbers import next_rfn_number

    async with _db_module.AsyncSessionLocal() as db:
        result = await db.execute(
            text("""
                SELECT id, txn_number, status, amount
                FROM transactions
                WHERE customer_id = :cid AND UPPER(txn_number) = :txn
            """),
            {"cid": _uuid.UUID(session.customer_id), "txn": txn_upper},
        )
        txn_row = result.mappings().first()

    if not txn_row:
        return {"success": False, "fast_response_key": "transaction_not_found"}

    # Refunds-table idempotency β€” checked BEFORE transactions.status.
    # transactions.status is derived state that can become stale or be manually
    # reset; the refunds table is the authoritative record.  A row for this
    # transaction means the goal is already achieved β€” never create a second one.
    async with _db_module.AsyncSessionLocal() as db:
        _er = await db.execute(
            text("""
                SELECT rfn_number, status
                FROM refunds
                WHERE transaction_id = :tid
                ORDER BY initiated_at DESC
                LIMIT 1
            """),
            {"tid": txn_row["id"]},
        )
        existing_refund = _er.mappings().first()

    if existing_refund:
        if existing_refund["status"] in ("completed", REFUND_COMPLETED):
            return {"success": False, "fast_response_key": "refund_already_completed",
                    "rfn_number": existing_refund["rfn_number"]}
        return {
            "success": False,
            "fast_response_key": "refund_already_initiated",
            "rfn_number": existing_refund["rfn_number"],
            "estimated_days": "3–5 business days",
        }

    status = txn_row["status"] or ""

    if status in (REFUND_INITIATED, REFUND_PROCESSING):
        return {
            "success": False,
            "fast_response_key": "refund_already_initiated",
            "estimated_days": "3–5 business days",
        }
    if status == REFUND_COMPLETED:
        return {"success": False, "fast_response_key": "refund_already_completed"}
    if status == COMPLETED:
        return {
            "success": False,
            "fast_response_key": "refund_ineligible",
            "reason": "Transaction completed successfully. Route to disputes team.",
        }
    if status == FLAGGED:
        return {
            "success": False,
            "fast_response_key": "fraud_review_required",
            "reason": "Transaction under fraud review. Escalate immediately.",
        }
    if status == KYC_HOLD:
        return {
            "success": False,
            "fast_response_key": "kyc_escalation_required",
            "reason": "Account KYC hold active. Cannot process refund.",
        }

    async with _db_module.AsyncSessionLocal() as db:
        rfn_number = await next_rfn_number(db)

        await db.execute(
            text("UPDATE transactions SET status = :status WHERE id = :id"),
            {"status": REFUND_INITIATED, "id": txn_row["id"]},
        )
        await db.execute(
            text("""
                INSERT INTO refunds (rfn_number, transaction_id, customer_id,
                                     amount, status, initiated_by, call_id)
                VALUES (:rfn, :tid, :cid, :amount, 'initiated', :by, :call_id)
            """),
            {
                "rfn": rfn_number,
                "tid": txn_row["id"],
                "cid": _uuid.UUID(session.customer_id),
                "amount": float(txn_row["amount"]),
                "by": f"voice_ai_{call_id}",
                "call_id": call_id,
            },
        )
        await db.commit()

    session.refund_case_id = rfn_number
    session.otp_verified = False  # reset after refund β€” next sensitive action needs fresh OTP

    # Update cached transactions status
    cached = getattr(session, "customer_profile", {})
    for t in (cached.get("transactions") or []):
        if t.get("txn_number", "").upper() == txn_upper:
            t["status"] = REFUND_INITIATED

    logger.info(json.dumps({
        "call_id": call_id, "tool": "initiate_refund",
        "transaction_id": transaction_id, "rfn_number": rfn_number,
    }))
    return {
        "success": True,
        "fast_response_key": "refund_initiated",
        "rfn_number": rfn_number,
        "message": f"Refund initiated. Reference number: {rfn_number}. Read this to the customer immediately.",
        "template_vars": {"transaction_id": transaction_id, "rfn_number": rfn_number},
    }


# ── raise_dispute ────────────────────────────────────────────────────────────

async def raise_dispute(transaction_id: str, reason: str, call_id: str) -> dict:
    """
    File a dispute for a completed transaction the customer doesn't recognise
    or didn't receive service for.
    Requires OTP verification. Idempotent β€” duplicate disputes return fast_response_key.
    """
    session = get_session(call_id)
    if not session or not session.otp_verified:
        return {"success": False, "fast_response_key": "verification_required"}
    if not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    txn_upper = transaction_id.upper()

    from utils.ref_numbers import next_dsp_number

    async with _db_module.AsyncSessionLocal() as db:
        result = await db.execute(
            text("""
                SELECT id, txn_number, status, amount
                FROM transactions
                WHERE customer_id = :cid AND UPPER(txn_number) = :txn
            """),
            {"cid": _uuid.UUID(session.customer_id), "txn": txn_upper},
        )
        txn_row = result.mappings().first()

    if not txn_row:
        return {"success": False, "fast_response_key": "transaction_not_found"}

    status = txn_row["status"] or ""

    if status == DISPUTED:
        return {"success": False, "fast_response_key": "dispute_duplicate"}
    if status in (CHARGEBACK_INITIATED, CHARGEBACK_WON, CHARGEBACK_LOST):
        return {"success": False, "fast_response_key": "dispute_duplicate"}
    if status == FLAGGED:
        return {"success": False, "fast_response_key": "fraud_review_required"}
    if status in (REFUND_INITIATED, REFUND_PROCESSING):
        return {"success": False, "fast_response_key": "refund_already_initiated"}
    if status == REFUND_COMPLETED:
        return {"success": False, "fast_response_key": "refund_already_completed"}

    amount = float(txn_row["amount"] or 0)
    if amount >= 50000:
        return {"success": False, "fast_response_key": "high_value_manual_required"}

    async with _db_module.AsyncSessionLocal() as db:
        dsp_number = await next_dsp_number(db)

        await db.execute(
            text("UPDATE transactions SET status = :status WHERE id = :id"),
            {"status": DISPUTED, "id": txn_row["id"]},
        )
        await db.execute(
            text("""
                INSERT INTO disputes (dsp_number, transaction_id, customer_id,
                                      reason, status, filed_via, call_id)
                VALUES (:dsp, :tid, :cid, :reason, 'open', 'voice_ai', :call_id)
            """),
            {
                "dsp": dsp_number,
                "tid": txn_row["id"],
                "cid": _uuid.UUID(session.customer_id),
                "reason": reason,
                "call_id": call_id,
            },
        )
        await db.commit()

    # Update session cache
    cached = getattr(session, "customer_profile", {})
    for t in (cached.get("transactions") or []):
        if t.get("txn_number", "").upper() == txn_upper:
            t["status"] = DISPUTED

    logger.info(json.dumps({
        "call_id": call_id, "tool": "raise_dispute",
        "transaction_id": transaction_id, "reason": reason,
        "dsp_number": dsp_number,
    }))
    return {
        "success": True,
        "fast_response_key": "dispute_filed",
        "dsp_number": dsp_number,
        "message": f"Dispute filed. Reference number: {dsp_number}. Read this to the customer immediately.",
        "template_vars": {"transaction_id": transaction_id, "dsp_number": dsp_number},
    }


# ── report_fraud ──────────────────────────────────────────────────────────────

async def report_fraud(transaction_id: str, fraud_type: str, call_id: str) -> dict:
    """
    File a fraud report for an unauthorised transaction.
    Marks the transaction FRAUD_REPORTED, inserts into fraud_cases, triggers account review.
    Requires OTP verification (proves caller owns the account).
    """
    session = get_session(call_id)
    if not session or not session.otp_verified:
        return {"success": False, "fast_response_key": "verification_required"}
    if not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    txn_upper = transaction_id.upper()

    from utils.ref_numbers import next_fraud_number

    async with _db_module.AsyncSessionLocal() as db:
        result = await db.execute(
            text("""
                SELECT id, txn_number, status
                FROM transactions
                WHERE customer_id = :cid AND UPPER(txn_number) = :txn
            """),
            {"cid": _uuid.UUID(session.customer_id), "txn": txn_upper},
        )
        txn_row = result.mappings().first()

    if not txn_row:
        return {"success": False, "fast_response_key": "transaction_not_found"}

    status = txn_row["status"] or ""

    if status in (FRAUD_REPORTED, FRAUD_CONFIRMED):
        return {"success": False, "fast_response_key": "fraud_already_reported"}
    if status == FRAUD_REVERSED:
        return {"success": False, "fast_response_key": "fraud_transaction_reversed"}

    # Check for an existing active fraud case on this transaction regardless of
    # transaction status β€” prevents duplicate cases when status was previously
    # changed to refund_initiated, completed, etc.
    async with _db_module.AsyncSessionLocal() as db:
        existing_case = await db.execute(
            text("""
                SELECT fraud_number FROM fraud_cases
                WHERE transaction_id = :tid
                  AND status NOT IN ('resolved', 'closed', 'rejected')
                LIMIT 1
            """),
            {"tid": txn_row["id"]},
        )
        existing = existing_case.mappings().first()
    if existing:
        existing_num = existing["fraud_number"]
        logger.info("report_fraud: case %s already exists for %s β€” returning existing",
                    existing_num, txn_upper)
        return {
            "success": True,
            "fraud_number": existing_num,
            "fast_response_key": "fraud_already_reported",
            "message": (
                f"A fraud case {existing_num} is already open for this transaction "
                f"and is currently under review. No new case has been created."
            ),
        }

    async with _db_module.AsyncSessionLocal() as db:
        fraud_number = await next_fraud_number(db)

        await db.execute(
            text("UPDATE transactions SET status = :status WHERE id = :id"),
            {"status": FRAUD_REPORTED, "id": txn_row["id"]},
        )
        await db.execute(
            text("""
                INSERT INTO fraud_cases (fraud_number, transaction_id, customer_id,
                                         fraud_type, status, risk_level,
                                         reported_via, call_id)
                VALUES (:fraud_num, :tid, :cid, :ftype, 'under_review', 'high',
                        'voice_ai', :call_id)
            """),
            {
                "fraud_num": fraud_number,
                "tid": txn_row["id"],
                "cid": _uuid.UUID(session.customer_id),
                "ftype": fraud_type,
                "call_id": call_id,
            },
        )
        # Place a fraud hold on the account so the Agent Console can later lift it
        await db.execute(
            text("""
                UPDATE customers
                SET fraud_hold_active = true,
                    fraud_hold_placed_at = now()
                WHERE id = :cid
            """),
            {"cid": _uuid.UUID(session.customer_id)},
        )
        await db.execute(
            text("""
                INSERT INTO account_holds
                    (customer_id, hold_type, reason, status, placed_at, placed_by, call_id)
                VALUES (:cid, 'fraud', :reason, 'active', now(), 'voice_ai', :call_id)
            """),
            {
                "cid": _uuid.UUID(session.customer_id),
                "reason": f"Fraud reported via voice AI β€” {fraud_number}",
                "call_id": call_id,
            },
        )
        await db.commit()

    # Update session cache
    cached = getattr(session, "customer_profile", {})
    for t in (cached.get("transactions") or []):
        if t.get("txn_number", "").upper() == txn_upper:
            t["status"] = FRAUD_REPORTED
    if cached:
        cached["fraud_hold_active"] = True

    logger.info(json.dumps({
        "call_id": call_id, "tool": "report_fraud",
        "transaction_id": transaction_id, "fraud_type": fraud_type,
        "fraud_number": fraud_number,
    }))
    return {
        "success": True,
        "fast_response_key": "fraud_case_opened",
        "fraud_number": fraud_number,
        "message": f"Fraud case opened. Reference number: {fraud_number}. Read this to the customer immediately.",
        "template_vars": {"transaction_id": transaction_id, "fraud_number": fraud_number},
    }


# ── check_payment_status ──────────────────────────────────────────────────────

async def check_payment_status(transaction_id: str, call_id: str) -> dict:
    """
    Return a detailed payment status with SLA context.
    Maps transaction status to a resolution-oriented fast_response_key.
    Used when customer says "my payment is stuck" or "money not credited yet".
    """
    session = get_session(call_id)
    if not session or not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}

    txn_upper = transaction_id.upper()
    cached_profile = getattr(session, "customer_profile", None) if session else None
    transactions = cached_profile.get("transactions") or [] if cached_profile else []

    txn = next((t for t in transactions if str(t.get("txn_number", "")).upper() == txn_upper), None)
    if not txn:
        return {"success": False, "fast_response_key": "transaction_not_found"}

    status = txn.get("status", "")
    amount = txn.get("amount", "")
    merchant = txn.get("merchant", "the merchant")
    txn_date = txn.get("txn_date", "")

    # Determine SLA breach β€” pending for more than 3 hours on same day is abnormal
    from datetime import date as _date
    today = _date.today().isoformat()
    is_today = txn_date == today

    key_map = {
        PENDING:            "payment_processing_delayed" if not is_today else "payment_processing",
        PROCESSING:         "payment_processing",
        FAILED:             "payment_failed_post_debit",
        COMPLETED:          "payment_settled",
        CANCELLED:          "payment_returned",
        EXPIRED:            "payment_returned",
        REFUND_INITIATED:   "payment_returned",
        REFUND_PROCESSING:  "payment_returned",
        REFUND_COMPLETED:   "payment_returned",
        FLAGGED:            "gateway_error",
        KYC_HOLD:           "gateway_error",
    }
    fast_key = key_map.get(status, "gateway_error")

    logger.info(json.dumps({
        "call_id": call_id, "tool": "check_payment_status",
        "transaction_id": transaction_id, "status": status, "key": fast_key,
    }))
    return {
        "success": True,
        "fast_response_key": fast_key,
        "status": status,
        "merchant": merchant,
        "amount": amount,
        "template_vars": {"transaction_id": transaction_id, "merchant": merchant, "amount": amount},
    }


# ── get_account_holds ────────────────────────────────────────────────────────

async def get_account_holds(call_id: str) -> dict:
    """Return active account holds from session cache (loaded at verify_account)."""
    session = get_session(call_id)
    if not session or not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}
    profile = getattr(session, "customer_profile", {}) or {}
    holds = profile.get("account_holds") or []
    return {
        "success": True,
        "holds": holds,
        "count": len(holds),
        "has_holds": len(holds) > 0,
    }


# ── get_refund_status ─────────────────────────────────────────────────────────

async def get_refund_status(transaction_id: str | None, call_id: str) -> dict:
    """Return open/in-progress refunds from session cache, optionally filtered by transaction ID."""
    session = get_session(call_id)
    if not session or not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}
    profile = getattr(session, "customer_profile", {}) or {}
    refunds = profile.get("open_refunds") or []
    if transaction_id:
        tid = transaction_id.upper()
        refunds = [r for r in refunds if str(r.get("transaction_id", "")).upper() == tid]

    # Fallback: refund row may not exist if it was from a previous demo session
    # (seed re-run orphans old refund rows). If the transaction itself says
    # refund_initiated/refund_processing, surface that so the AI isn't left empty.
    if not refunds and transaction_id:
        txns = profile.get("transactions") or []
        txn = next(
            (t for t in txns if str(t.get("txn_number", "")).upper() == tid),
            None,
        )
        if txn and txn.get("status") in ("refund_initiated", "refund_processing"):
            return {
                "success": True,
                "refunds": [{
                    "transaction_id": txn["txn_number"],
                    "merchant": txn.get("merchant"),
                    "amount": float(txn.get("amount", 0)),
                    "status": "processing",
                    "note": "Refund already in progress for this transaction.",
                }],
                "count": 1,
                "note": (
                    "Refund is in progress. The RFN reference number will be issued "
                    "when the refund clears. Advise the customer to allow 3-5 business days."
                ),
            }

    return {
        "success": True,
        "refunds": refunds,
        "count": len(refunds),
    }


# ── get_dispute_status ────────────────────────────────────────────────────────

async def get_dispute_status(transaction_id: str | None, call_id: str) -> dict:
    """Return open/under-review disputes from session cache, optionally filtered by transaction ID."""
    session = get_session(call_id)
    if not session or not session.customer_id:
        return {"success": False, "fast_response_key": "verification_required"}
    profile = getattr(session, "customer_profile", {}) or {}
    disputes = profile.get("open_disputes") or []
    if transaction_id:
        tid = transaction_id.upper()
        disputes = [d for d in disputes if str(d.get("transaction_id", "")).upper() == tid]
    return {
        "success": True,
        "disputes": disputes,
        "count": len(disputes),
    }


# ── dispatcher ────────────────────────────────────────────────────────────────

async def execute_tool(tool_name: str, args: dict, call_id: str) -> dict:
    """Routes tool_name to the correct implementation."""
    if tool_name == "verify_account":
        return await verify_account(
            phone=args.get("phone", ""),
            call_id=call_id,
        )
    elif tool_name == "lookup_transaction":
        return await lookup_transaction(
            transaction_id=args.get("transaction_id", ""),
            call_id=call_id,
        )
    elif tool_name == "send_otp":
        return await send_otp(call_id=call_id)
    elif tool_name == "verify_otp":
        return await verify_otp(otp_input=args.get("otp_code", ""), call_id=call_id)
    elif tool_name == "unlock_account":
        return await unlock_account(call_id=call_id)
    elif tool_name == "initiate_refund":
        return await initiate_refund(
            transaction_id=args.get("transaction_id", ""),
            call_id=call_id,
        )
    elif tool_name == "raise_dispute":
        return await raise_dispute(
            transaction_id=args.get("transaction_id", ""),
            reason=args.get("reason", "unrecognised_transaction"),
            call_id=call_id,
        )
    elif tool_name == "report_fraud":
        return await report_fraud(
            transaction_id=args.get("transaction_id", ""),
            fraud_type=args.get("fraud_type", "unauthorized_transaction"),
            call_id=call_id,
        )
    elif tool_name == "check_payment_status":
        return await check_payment_status(
            transaction_id=args.get("transaction_id", ""),
            call_id=call_id,
        )
    elif tool_name == "get_account_holds":
        return await get_account_holds(call_id=call_id)
    elif tool_name == "get_refund_status":
        return await get_refund_status(
            transaction_id=args.get("transaction_id"),
            call_id=call_id,
        )
    elif tool_name == "get_dispute_status":
        return await get_dispute_status(
            transaction_id=args.get("transaction_id"),
            call_id=call_id,
        )
    elif tool_name == "escalate_to_human":
        return await escalate_to_human(
            reason=args.get("reason", "customer_request"),
            lead_summary=args.get("lead_summary", ""),
            call_id=call_id,
        )
    else:
        raise ValueError(f"Unknown tool: {tool_name}")