File size: 43,353 Bytes
6896d6d
 
8f7c743
e3f7023
5b0dd39
e3f7023
 
92d7dac
 
e3f7023
92d7dac
ee2d1bd
47776fe
92d7dac
 
de5e25f
 
95313e0
6bc0383
c0518bd
 
 
 
54b48aa
 
c0518bd
67f8b65
c0518bd
 
370f33f
92d7dac
 
c0518bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67f8b65
c0518bd
 
 
 
 
92d7dac
 
c0518bd
92d7dac
 
 
 
 
 
 
 
370f33f
 
 
92d7dac
 
 
 
 
 
 
 
 
 
 
9de4ca1
6bc0383
 
cfb225f
6bc0383
 
cfb225f
6bc0383
 
 
 
 
 
 
 
 
cfb225f
2b09707
cfb225f
7181c25
cfb225f
7181c25
 
 
cfb225f
 
7181c25
cfb225f
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
7181c25
cfb225f
 
7181c25
cfb225f
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
7181c25
cfb225f
 
 
7181c25
cfb225f
 
 
 
7181c25
cfb225f
 
 
7181c25
cfb225f
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
7181c25
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
cfb225f
 
 
 
7181c25
 
 
 
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7181c25
ee2d1bd
2b09707
cfb225f
6896d6d
7181c25
 
945582b
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
945582b
706ece4
ee2d1bd
706ece4
 
 
 
 
 
6896d6d
ee2d1bd
6896d6d
 
cfb225f
3aa0c78
cfb225f
 
 
 
 
 
 
 
3aa0c78
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
04cb7e8
cfb225f
 
04cb7e8
cfb225f
397b23d
 
 
cfb225f
 
 
 
 
 
 
 
 
92d7dac
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d7dac
cfb225f
 
 
 
 
 
92d7dac
cfb225f
92d7dac
 
cfb225f
92d7dac
 
cfb225f
 
 
92d7dac
 
cfb225f
 
 
92d7dac
 
 
cfb225f
 
 
 
f0eec26
cfb225f
 
92d7dac
cfb225f
 
 
92d7dac
cfb225f
 
 
92d7dac
 
cfb225f
 
92d7dac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92d7dac
 
 
 
 
 
 
cfb225f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95313e0
cfb225f
 
95313e0
 
 
 
 
 
 
 
495d60d
95313e0
 
 
 
 
 
 
 
 
 
 
 
 
 
de5e25f
95313e0
92d7dac
 
95313e0
 
 
92d7dac
95313e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de5e25f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95313e0
de5e25f
95313e0
 
 
cfb225f
c0518bd
cfb225f
c0518bd
cfb225f
 
 
 
 
 
 
c0518bd
92d7dac
 
 
 
c0518bd
 
 
 
 
 
 
 
92d7dac
c0518bd
 
cfb225f
c0518bd
cfb225f
c0518bd
cfb225f
 
84d518b
c0518bd
cfb225f
c0518bd
cfb225f
 
 
c0518bd
 
cfb225f
c0518bd
cfb225f
 
92e65a1
 
c0518bd
 
 
 
de5e25f
 
 
 
 
 
 
 
c0518bd
de5e25f
 
 
 
 
 
 
 
95313e0
de5e25f
95313e0
de5e25f
 
 
 
 
 
 
 
54b48aa
95313e0
 
 
 
92d7dac
de5e25f
95313e0
 
 
54b48aa
 
 
 
92d7dac
54b48aa
 
 
 
 
 
 
 
 
25c2bcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54b48aa
 
 
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
import streamlit as st
import pandas as pd
from datetime import datetime, date, timedelta
from Analytics.AnalyseFinance import (
    analyser_capacite,
    generer_tableau_amortissement,
    calculer_taux_endettement,
    calculer_mensualite_pret,
    SEUILS,
)
from Analytics import vortex_params
from DocumentGen.AutoPDFGeneration import generer_contrat_pret, generer_reconnaissance_dette, generer_contrat_caution
from core.id_generator import generate_next_id
from core.email_client import envoyer_email, get_admin_email, get_credential
from core.sheets_cache import clear_sheets_cache
from core import signature as sg
from core import signature_service as svc
from core.ui_guards import rendre_form_submit_protege, rendre_bouton_protege, marquer_fait, liberer
import time
import requests
import base64
import os

from modules.jasmine_widget import render_scoped_widget

# ============================================================================
# FONCTION ISOLEE β€” ENVOI DES CONTRATS PAR EMAIL
# ============================================================================

def envoyer_contrat_tactique(email_client, loan_data, client_data, pdf_contrat, pdf_dette, pdf_caution=None, garant_data=None):
    """Envoi des documents d'octroi (contrat, reconnaissance de dette, caution) :
    garant en CC, admin en BCC. Transport mutualise dans core.email_client.envoyer_email."""
    if not email_client or "@" not in str(email_client):
        return False, "Adresse email invalide ou manquante."

    nom_client = client_data.get('Nom_Complet', 'Client')
    id_pret = loan_data.get('ID_Pret', 'N/A')
    montant_capital = loan_data.get('Montant_Capital', 0)
    montant_total = loan_data.get('Montant_Total', 0)
    offre = loan_data.get('Offre', 'Standard')

    html_content = f"""
    <html><body style="font-family: 'Courier New', monospace; background-color: #0a0e12; color: #c9d1d9; padding: 20px;">
        <div style="border: 1px solid #58a6ff; padding: 20px; background-color: rgba(10, 14, 18, 0.8);">
            <div style="border-bottom: 1px solid rgba(88, 166, 255, 0.2); padding-bottom: 10px; margin-bottom: 20px;">
                <span style="color: #58a6ff; font-weight: bold; font-size: 16px; letter-spacing: 2px;">CONFIRMATION D'OCTROI DE PRET</span>
            </div>
            <p>CLIENT IDENTIFIE : <strong>{nom_client}</strong></p>
            <p>REFERENCE DOSSIER : <strong>{id_pret}</strong></p>
            <p>OFFRE SOUSCRITE : <strong>{offre}</strong></p>
            <div style="background-color: rgba(255, 255, 255, 0.05); padding: 15px; margin: 20px 0; border-left: 3px solid #58a6ff;">
                <p style="margin: 0 0 10px 0; color: #8b949e; font-size: 12px; text-transform: uppercase;">CAPITAL DEBLOQUE</p>
                <p style="margin: 0; font-size: 24px; color: #58a6ff; font-weight: bold;">{montant_capital:,.0f} XOF</p>
                <p style="margin: 15px 0 0 0; color: #8b949e; font-size: 12px; text-transform: uppercase;">MONTANT TOTAL A REMBOURSER</p>
                <p style="margin: 0; font-size: 18px; color: #54bd4b; font-weight: bold;">{montant_total:,.0f} XOF</p>
            </div>
            <p style="font-size: 12px; color: #8b949e; margin-top: 30px;">
                Veuillez trouver vos documents officiels (Contrat de pret, Echeancier, Reconnaissance de dette, et l'acte de caution le cas echeant) en pieces jointes (PDF). Ces documents ont ete generes automatiquement par le systeme Vortex.
            </p>
        </div>
    </body></html>
    """

    def _octets(pdf_obj):
        return pdf_obj.getvalue() if hasattr(pdf_obj, 'getvalue') else pdf_obj

    attachments = [
        (f"Contrat_{id_pret}.pdf", _octets(pdf_contrat)),
        (f"Dette_{id_pret}.pdf", _octets(pdf_dette)),
    ]
    if pdf_caution:
        attachments.append((f"Caution_{id_pret}.pdf", _octets(pdf_caution)))

    cc = None
    if garant_data:
        email_garant = str(garant_data.get('Email', ''))
        if "@" in email_garant:
            cc = email_garant

    return envoyer_email(
        to=email_client,
        subject=f"DOCUMENTS D'OCTROI DE PRET - {id_pret}",
        html_content=html_content,
        bcc=get_admin_email(),
        cc=cc,
        attachments=attachments,
        sender_name="Vortex Finance",
    )


# ============================================================================
# GESTION DU CACHE
# ============================================================================

@st.cache_data(ttl=600)
def get_cached_data(_client, sheet_name, worksheet_name):
    try:
        sh = _client.open(sheet_name)
        ws = sh.worksheet(worksheet_name)
        return pd.DataFrame(ws.get_all_records())
    except Exception as e:
        st.error(f"Erreur lors de la lecture de {worksheet_name}: {e}")
        return pd.DataFrame()


# ============================================================================
# CSS — STYLE GOTHAM / PALANTIR ALIGNÉ SUR streamlit_app.py
# ============================================================================

def apply_loans_engine_styles():
    st.markdown("""
    <style>
    @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700;800&display=swap');

    #loans-engine-module {
        font-family: 'JetBrains Mono', 'Courier New', monospace;
    }

    /* ── OFFER SELECTION CARDS ── */
    .offer-card {
        background: rgba(10, 14, 18, 0.9);
        border: 1px solid rgba(80, 100, 120, 0.3);
        border-top: 2px solid rgba(80, 100, 120, 0.4);
        padding: 20px 18px;
        cursor: pointer;
        transition: all 0.15s ease;
        font-family: 'JetBrains Mono', monospace;
        height: 100%;
    }
    .offer-card.consumer   { border-top-color: rgba(88, 166, 255, 0.7); }
    .offer-card.decouvert  { border-top-color: rgba(138, 154, 170, 0.7); }
    .offer-card.private    { border-top-color: rgba(243, 156, 18, 0.7); }

    .offer-card.selected {
        background: rgba(15, 22, 32, 0.95);
        border-color: rgba(100, 130, 160, 0.6);
    }
    .offer-card.selected.consumer  { border-top-color: #58a6ff; box-shadow: 0 0 12px rgba(88, 166, 255, 0.15); }
    .offer-card.selected.decouvert { border-top-color: #8a9aaa; box-shadow: 0 0 12px rgba(138, 154, 170, 0.15); }
    .offer-card.selected.private   { border-top-color: #f39c12; box-shadow: 0 0 12px rgba(243, 156, 18, 0.15); }

    .offer-tag {
        font-size: 0.55rem;
        font-weight: 700;
        letter-spacing: 3px;
        text-transform: uppercase;
        margin-bottom: 10px;
        font-family: 'JetBrains Mono', monospace;
    }
    .offer-tag.consumer  { color: rgba(88, 166, 255, 0.7); }
    .offer-tag.decouvert { color: rgba(138, 154, 170, 0.7); }
    .offer-tag.private   { color: rgba(243, 156, 18, 0.7); }

    .offer-name {
        font-size: 0.85rem;
        font-weight: 800;
        letter-spacing: 2px;
        text-transform: uppercase;
        color: #a8b8c8;
        font-family: 'JetBrains Mono', monospace;
        margin-bottom: 10px;
        line-height: 1.3;
    }

    .offer-desc {
        font-size: 0.68rem;
        color: #4a5a6a;
        font-family: 'JetBrains Mono', monospace;
        line-height: 1.7;
        letter-spacing: 0.3px;
    }

    .offer-indicator {
        margin-top: 14px;
        font-size: 0.6rem;
        font-weight: 700;
        letter-spacing: 2px;
        text-transform: uppercase;
        font-family: 'JetBrains Mono', monospace;
        color: #3a4a5a;
    }
    .offer-indicator.active.consumer  { color: #58a6ff; }
    .offer-indicator.active.decouvert { color: #8a9aaa; }
    .offer-indicator.active.private   { color: #f39c12; }

    /* ── OFFER SELECTOR BUTTONS ── */
    #loans-engine-module .offer-btn button {
        background: transparent !important;
        border: 1px solid rgba(60, 80, 100, 0.3) !important;
        color: #3a4a5a !important;
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 0.6rem !important;
        font-weight: 700 !important;
        letter-spacing: 1.5px !important;
        text-transform: uppercase !important;
        border-radius: 0 !important;
        padding: 5px 12px !important;
        width: 100% !important;
        margin-top: 8px !important;
    }
    #loans-engine-module .offer-btn.consumer button {
        border-color: rgba(88, 166, 255, 0.3) !important;
        color: rgba(88, 166, 255, 0.6) !important;
    }
    #loans-engine-module .offer-btn.consumer button:hover {
        border-color: #58a6ff !important;
        color: #58a6ff !important;
        background: rgba(88, 166, 255, 0.06) !important;
    }
    #loans-engine-module .offer-btn.decouvert button {
        border-color: rgba(138, 154, 170, 0.3) !important;
        color: rgba(138, 154, 170, 0.6) !important;
    }
    #loans-engine-module .offer-btn.decouvert button:hover {
        border-color: #8a9aaa !important;
        color: #8a9aaa !important;
        background: rgba(138, 154, 170, 0.06) !important;
    }
    #loans-engine-module .offer-btn.private button {
        border-color: rgba(243, 156, 18, 0.3) !important;
        color: rgba(243, 156, 18, 0.6) !important;
    }
    #loans-engine-module .offer-btn.private button:hover {
        border-color: #f39c12 !important;
        color: #f39c12 !important;
        background: rgba(243, 156, 18, 0.06) !important;
    }

    /* ── SELECTED BADGE ── */
    .offer-selected-badge {
        display: inline-block;
        font-family: 'JetBrains Mono', monospace;
        font-size: 0.6rem;
        font-weight: 700;
        letter-spacing: 2px;
        text-transform: uppercase;
        padding: 4px 10px;
        margin-bottom: 20px;
        margin-top: 4px;
        border: 1px solid;
    }
    .offer-selected-badge.consumer  { color: #58a6ff; border-color: rgba(88, 166, 255, 0.4); background: rgba(88, 166, 255, 0.06); }
    .offer-selected-badge.decouvert { color: #8a9aaa; border-color: rgba(138, 154, 170, 0.4); background: rgba(138, 154, 170, 0.06); }
    .offer-selected-badge.private   { color: #f39c12; border-color: rgba(243, 156, 18, 0.4); background: rgba(243, 156, 18, 0.06); }

    /* ── SECTION TAG ── */
    .le-section-tag {
        display: block;
        font-family: 'JetBrains Mono', monospace;
        font-size: 0.58rem;
        font-weight: 700;
        letter-spacing: 3px;
        text-transform: uppercase;
        color: #3a4a5a;
        border: 1px solid rgba(60, 80, 100, 0.25);
        padding: 3px 10px;
        margin-bottom: 16px;
        margin-top: 24px;
    }

    /* ── METRICS ── */
    #loans-engine-module [data-testid="stMetric"] {
        background: rgba(15, 20, 26, 0.85) !important;
        border: 1px solid rgba(100, 120, 140, 0.25) !important;
        border-top: 2px solid rgba(100, 120, 140, 0.5) !important;
        padding: 14px 16px !important;
        border-radius: 0 !important;
    }
    #loans-engine-module [data-testid="stMetric"] label {
        color: #5a6a7a !important;
        font-size: 0.65rem !important;
        font-weight: 700 !important;
        text-transform: uppercase !important;
        letter-spacing: 1.5px !important;
        font-family: 'JetBrains Mono', monospace !important;
    }
    #loans-engine-module [data-testid="stMetric"] [data-testid="stMetricValue"] {
        color: #a8b8c8 !important;
        font-size: 1.3rem !important;
        font-weight: 700 !important;
        font-family: 'JetBrains Mono', monospace !important;
    }

    /* ── BUTTONS ── */
    #loans-engine-module .stButton > button {
        background: transparent !important;
        border: 1px solid rgba(100, 120, 140, 0.4) !important;
        color: #7a8a9a !important;
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 0.72rem !important;
        font-weight: 700 !important;
        letter-spacing: 1.5px !important;
        text-transform: uppercase !important;
        border-radius: 0 !important;
        padding: 8px 16px !important;
    }
    #loans-engine-module .stButton > button:hover {
        border-color: rgba(168, 184, 200, 0.6) !important;
        color: #a8b8c8 !important;
        background: rgba(100, 120, 140, 0.08) !important;
    }

    /* ── EXPANDERS ── */
    #loans-engine-module [data-testid="stExpander"] {
        border: 1px solid rgba(80, 100, 120, 0.3) !important;
        border-radius: 0 !important;
        background: rgba(15, 20, 26, 0.6) !important;
    }
    #loans-engine-module [data-testid="stExpander"] summary {
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 0.72rem !important;
        letter-spacing: 1.5px !important;
        text-transform: uppercase !important;
        color: #5a6a7a !important;
    }

    /* ── ALERTS ── */
    #loans-engine-module .stAlert {
        border-radius: 0 !important;
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 0.75rem !important;
    }

    /* ── FORM SUBMIT ── */
    #loans-engine-module [data-testid="stFormSubmitButton"] > button {
        background: transparent !important;
        border: 1px solid rgba(100, 120, 140, 0.5) !important;
        color: #7a8a9a !important;
        font-family: 'JetBrains Mono', monospace !important;
        font-size: 0.72rem !important;
        font-weight: 700 !important;
        letter-spacing: 2px !important;
        text-transform: uppercase !important;
        border-radius: 0 !important;
        padding: 10px 24px !important;
        width: 100%;
    }
    #loans-engine-module [data-testid="stFormSubmitButton"] > button:hover {
        border-color: rgba(168, 184, 200, 0.6) !important;
        color: #a8b8c8 !important;
        background: rgba(100, 120, 140, 0.08) !important;
    }
    </style>
    """, unsafe_allow_html=True)


# ============================================================================
# COMPOSANT : SÉLECTION D'OFFRE TACTIQUE
# ============================================================================

OFFRES = {
    "Offre Consumer Loan": {
        "key": "consumer",
        "tag": "// SEGMENT RETAIL",
        "desc": "Credit a la consommation destine aux particuliers.\nRemboursement hebdomadaire ou mensuel.\nMontants standards, durees courtes a moyennes.",
        "color": "#58a6ff"
    },
    "Offre Découvert Privilège": {
        "key": "decouvert",
        "tag": "// SEGMENT PREMIUM",
        "desc": "Facilite de caisse pour clients a profil etabli.\nSouplesse de remboursement personnalisee.\nAcces prioritaire et conditions negociees.",
        "color": "#8a9aaa"
    },
    "Offre Private Credit": {
        "key": "private",
        "tag": "// SEGMENT PRIVE",
        "desc": "Credit sur mesure pour projets d'envergure.\nMontants eleves, structuration sur-mesure.\nReserve aux profils analyses et valides.",
        "color": "#f39c12"
    }
}


def render_offer_selector():
    """
    Affiche le selecteur d'offre tactique (3 cartes HTML + boutons Streamlit).
    Retourne le nom de l'offre selectionnee ou None.
    """
    if 'selected_offre' not in st.session_state:
        st.session_state.selected_offre = None

    st.markdown('<span class="le-section-tag">// SELECTION DE L\'OFFRE</span>', unsafe_allow_html=True)

    cols = st.columns(3)

    for col, (offre_name, meta) in zip(cols, OFFRES.items()):
        key        = meta["key"]
        is_selected = st.session_state.selected_offre == offre_name
        card_class = f"offer-card {key} {'selected' if is_selected else ''}"
        indicator_class = f"offer-indicator {'active ' + key if is_selected else ''}"
        indicator_text  = "[ SELECTIONNE ]" if is_selected else "[ SELECTIONNER ]"

        with col:
            st.markdown(f"""
            <div class="{card_class}">
                <div class="offer-tag {key}">{meta['tag']}</div>
                <div class="offer-name">{offre_name}</div>
                <div class="offer-desc">{meta['desc'].replace(chr(10), '<br>')}</div>
                <div class="{indicator_class}">{indicator_text}</div>
            </div>
            """, unsafe_allow_html=True)

            st.markdown(f'<div class="offer-btn {key}">', unsafe_allow_html=True)
            if st.button(offre_name, key=f"btn_offre_{key}"):
                st.session_state.selected_offre = offre_name
                st.rerun()
            st.markdown('</div>', unsafe_allow_html=True)

    if st.session_state.selected_offre:
        meta = OFFRES[st.session_state.selected_offre]
        st.markdown(
            f'<span class="offer-selected-badge {meta["key"]}">'
            f'OFFRE ACTIVE : {st.session_state.selected_offre}'
            f'</span>',
            unsafe_allow_html=True
        )

    return st.session_state.selected_offre


# ============================================================================
# MAIN FUNCTION
# ============================================================================

def show_loans_engine(client, sheet_name):
    apply_loans_engine_styles()
    st.markdown('<div id="loans-engine-module">', unsafe_allow_html=True)

    st.markdown("## MOTEUR FINANCIER : OCTROI DE PRET")

    # ── SELECTION OFFRE ────────────────────────────────────────────────────
    offre_selectionnee = render_offer_selector()

    if not offre_selectionnee:
        st.markdown("""
        <div style="background:rgba(10,14,18,0.9); border:1px solid rgba(80,100,120,0.2);
                    border-left:4px solid rgba(80,100,120,0.4); padding:14px 18px; margin-top:8px;
                    font-family:'JetBrains Mono',monospace; font-size:0.75rem; color:#4a5a6a;
                    letter-spacing:0.5px;">
            SELECTIONNER UNE OFFRE CI-DESSUS POUR ACCEDER A LA CONFIGURATION DU PRET.
        </div>
        """, unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)
        return

    # ── CHARGEMENT DONNΓ‰ES ─────────────────────────────────────────────────
    try:
        sh = client.open(sheet_name)
        df_clients = get_cached_data(client, sheet_name, "Clients_KYC")
        try:
            df_garants = get_cached_data(client, sheet_name, "Garants_KYC")
            if not df_garants.empty:
                df_garants['search_label'] = df_garants['ID_Garant'].astype(str) + " - " + df_garants['Nom_Complet'].astype(str)
        except Exception as e:
            st.error(f"Erreur sur la feuille Garants : {e}")
            df_garants = pd.DataFrame()
    except Exception as e:
        st.error(f"Erreur connexion : {e}")
        return

    # ── SΓ‰LECTION CLIENT ───────────────────────────────────────────────────
    if df_clients.empty:
        st.error("Aucun client trouve dans la base KYC.")
        st.markdown('</div>', unsafe_allow_html=True)
        return

    st.markdown('<span class="le-section-tag">// IDENTIFICATION CIBLE</span>', unsafe_allow_html=True)

    df_clients['search_label'] = df_clients['ID_Client'].astype(str) + " - " + df_clients['Nom_Complet'].astype(str)
    selected_client_label = st.selectbox("Rechercher une cible", [""] + df_clients['search_label'].tolist())

    if not selected_client_label:
        st.markdown('</div>', unsafe_allow_html=True)
        return

    client_info = df_clients[df_clients['search_label'] == selected_client_label].iloc[0]
    client_id   = client_info['ID_Client']

    try:
        pers_charge = int(client_info.get('Pers_Charge', 0))
    except (ValueError, TypeError):
        pers_charge = 0

    st.info(f"CIBLE : {client_info['Nom_Complet']}")

    with st.expander(f"SOLVABILITE // {client_info['Nom_Complet']}", expanded=True):
        def clean_val(val):
            try:
                return float(str(val).replace("XOF","").replace(" ","").replace(",",""))
            except (ValueError, TypeError) as e:
                from core.errors import log_swallowed
                log_swallowed(f"Montant illisible pour {client_info.get('ID_Client', '?')} (valeur : {val!r})", e)
                return 0.0

        rev   = clean_val(client_info['Revenus_Mensuels'])
        chg   = clean_val(client_info['Charges_Estimees'])
        reste = rev - chg

        c1, c2, c3 = st.columns(3)
        c1.metric("Revenus Mensuels",   f"{int(rev):,} XOF".replace(",", " "))
        c2.metric("Charges Estimees",   f"{int(chg):,} XOF".replace(",", " "))
        delta_color = "normal" if reste > SEUILS["reste_a_vivre_min"]["acceptable"] else "inverse"
        c3.metric("Reste a Vivre (Net)", f"{int(reste):,} XOF".replace(",", " "),
                  delta=f"{int(reste):,}", delta_color=delta_color)
        st.markdown(f"**Profession :** {client_info['Statut_Pro']} | **Ville :** {client_info['Ville']}")

        if pers_charge >= 1:
            ipf = rev / (1 + pers_charge)
            st.info(f"IPF (Indice de Pression Familiale) : {int(ipf):,} XOF β€” base de calcul ajustee ({pers_charge} pers. a charge)".replace(",", " "))

    # ── SΓ‰LECTION GARANT ───────────────────────────────────────────────────
    selected_garant = None
    garant_id       = ""

    st.markdown('<span class="le-section-tag">// GARANT (OPTIONNEL)</span>', unsafe_allow_html=True)

    if df_garants.empty:
        st.info("Aucun garant enregistre dans la base.")
    else:
        selected_garant_label = st.selectbox("Rechercher un garant (Optionnel)", [""] + df_garants['search_label'].tolist())
        if selected_garant_label:
            garant_info     = df_garants[df_garants['search_label'] == selected_garant_label].iloc[0]
            selected_garant = garant_info
            garant_id       = garant_info['ID_Garant']
            st.info(f"GARANT : {garant_info['Nom_Complet']}")
            with st.expander(f"ANALYSE CAUTION // {garant_info['Nom_Complet']}", expanded=True):
                rev_g = clean_val(garant_info['Revenus_Mensuels'])
                chg_g = clean_val(garant_info['Charges_Estimees'])
                g1, g2, g3 = st.columns(3)
                g1.metric("Revenus Garant", f"{int(rev_g):,} XOF".replace(",", " "))
                g2.metric("Charges Garant", f"{int(chg_g):,} XOF".replace(",", " "))
                g3.metric("Reste a Vivre",  f"{int(rev_g - chg_g):,} XOF".replace(",", " "))
                st.warning("ENGAGEMENT SOLIDAIRE : Le garant renonce aux benefices de discussion et de division.")

    # ── CONFIGURATION PRÊT ────────────────────────────────────────────────
    st.markdown('<span class="le-section-tag">// CONFIGURATION DU PRET</span>', unsafe_allow_html=True)

    col_motif, col_type, col_moyen = st.columns(3)
    with col_motif:
        motif = st.selectbox("Motif du pret", [
            "Commerce / Achat de stock", "Investissement", "Tresorerie professionnelle",
            "Lancement d'activite", "Developpement d'activite", "Agriculture / Elevage",
            "Transport / Logistique", "Urgence medicale", "Scolarite / Formation",
            "Logement / Habitat", "Reparations", "Evenements familiaux",
            "Voyage / Deplacement", "Consommation", "Achat d'equipement personnel",
            "Projet personnel", "Autre"
        ])
    with col_type:
        type_pret = st.selectbox("Type de remboursement", [
            "In Fine", "Mensuel - Interets", "Mensuel - Constant", "Hebdomadaire", "Personnalise"
        ])
    with col_moyen:
        moyen_transfert = st.selectbox("Moyen de transfert", ["Wave", "Orange Money", "Virement"])

    type_code_map = {
        "In Fine": "IN_FINE", "Mensuel - Interets": "MENSUEL_INTERETS",
        "Mensuel - Constant": "MENSUEL_CONSTANT", "Hebdomadaire": "HEBDOMADAIRE",
        "Personnalise": "PERSONNALISE"
    }
    type_code = type_code_map[type_pret]

    col1, col2, col3 = st.columns(3)
    montant    = col1.number_input("Montant (XOF)", 10000, value=100000, step=10000)
    taux_hebdo = col2.number_input("Taux Hebdo (%)", 0.1, value=2.0, step=0.1)

    # ── VARIABLES INIT ────────────────────────────────────────────────────
    duree_semaines    = 0
    duree_mois        = 0
    dates_versements  = []
    date_debut        = date.today()
    date_fin          = date_debut

    st.markdown('<span class="le-section-tag">// SIMULATION</span>', unsafe_allow_html=True)

    # ── SAISIE DE LA DUREE / DES ECHEANCES (widgets seulement) ───────────
    if type_code == "IN_FINE":
        duree_semaines   = col3.number_input("Duree (en semaines)", min_value=1, max_value=104, value=8)
        date_fin         = date_debut + timedelta(weeks=duree_semaines)
        dates_versements = [date_fin]

    elif type_code in ("MENSUEL_INTERETS", "MENSUEL_CONSTANT"):
        duree_mois       = col3.number_input("Duree (en mois)", min_value=1, max_value=60, value=12)
        date_fin         = date_debut + timedelta(days=duree_mois * 30)
        duree_semaines   = duree_mois * 4.33
        dates_versements = [date_debut + timedelta(days=30 * i) for i in range(1, int(duree_mois) + 1)]

    elif type_code == "HEBDOMADAIRE":
        duree_semaines   = col3.number_input("Duree (en semaines)", min_value=1, max_value=104, value=12)
        date_fin         = date_debut + timedelta(weeks=duree_semaines)
        dates_versements = [date_debut + timedelta(weeks=i) for i in range(1, int(duree_semaines) + 1)]

    else:  # PERSONNALISE
        st.info("Configurez les dates de versement ci-dessous")
        if 'dates_perso' not in st.session_state:
            st.session_state.dates_perso = [date.today() + timedelta(weeks=2)]
        col_add, _ = st.columns([1, 4])
        if col_add.button("AJOUTER ECHEANCE"):
            st.session_state.dates_perso.append(st.session_state.dates_perso[-1] + timedelta(weeks=1))
            st.rerun()
        dates_saisies = []
        for idx, dt in enumerate(st.session_state.dates_perso):
            col_d, col_x = st.columns([4, 1])
            new_date = col_d.date_input(f"Echeance {idx+1}", value=dt, key=f"d_{idx}", min_value=date.today())
            dates_saisies.append(new_date)
            if col_x.button("[ X ]", key=f"del_{idx}") and len(st.session_state.dates_perso) > 1:
                st.session_state.dates_perso.pop(idx)
                st.rerun()
        st.session_state.dates_perso = dates_saisies
        dates_versements = sorted(dates_saisies)
        if dates_versements:
            date_fin       = dates_versements[-1]
            duree_semaines = max(1, (date_fin - date_debut).days // 7)

    if not dates_versements:
        st.warning("Ajoutez au moins une echeance.")
        st.markdown('</div>', unsafe_allow_html=True)
        return

    # ── CALCUL UNIQUE (meme moteur que le simulateur : frais de transfert + forfait duree min) ──
    df_param_regles = get_cached_data(client, sheet_name, "Parametres_Vortex")
    regles = vortex_params.get_regles_actuelles_depuis_df(df_param_regles)
    calc = calculer_mensualite_pret(
        type_code, montant, taux_hebdo, duree_semaines, duree_mois,
        nb_dates_perso=len(dates_versements),
        duree_minimale_semaines=regles["Regle_Duree_Minimale_Semaines"],
        forfait_pct=regles["Regle_Forfait_Duree_Minimale_Pct"],
    )
    montant_total     = calc["montant_total"]
    cout_credit       = calc["cout_credit"]
    montant_versement = calc["mensualite"]
    nb_versements     = calc["nb_versements"]
    frais_transfert   = calc["frais_transfert"]
    forfait_applique  = calc["duree_min_non_respectee"]

    # ── METRIQUES (valeurs issues du calcul ci-dessus) ────────────────────
    libelle_versement = {
        "IN_FINE":          "Versement unique",
        "MENSUEL_INTERETS": "Interets mensuels",
        "MENSUEL_CONSTANT": "Mensualite constante",
        "HEBDOMADAIRE":     "Versement Hebdo",
        "PERSONNALISE":     "Moyenne/Versement",
    }[type_code]
    if forfait_applique:
        st.info("Duree inferieure au minimum : forfait fixe applique.")
    r1, r2, r3 = st.columns(3)
    r1.metric(libelle_versement, f"{int(montant_versement):,} XOF".replace(",", " "))
    r2.metric("Cout du credit",  f"{int(cout_credit):,} XOF".replace(",", " "))
    r3.metric("Montant Total",   f"{int(montant_total):,} XOF".replace(",", " "), delta=f"+{int(cout_credit):,}")

    # ── ANALYSE CAPACITΓ‰ ──────────────────────────────────────────────────
    st.markdown('<span class="le-section-tag">// ANALYSE DE CAPACITE</span>', unsafe_allow_html=True)

    analyse = analyser_capacite(
        type_code, montant, taux_hebdo, duree_semaines, montant_versement, nb_versements,
        client_info['Revenus_Mensuels'], client_info.get('Charges_Estimees', 0),
        montant_total, pers_charge=pers_charge
    )
    _couleur = analyse['couleur']
    _statut  = analyse['statut']
    st.markdown(
        f"<span style='font-family:JetBrains Mono,monospace;font-size:0.8rem;"
        f"font-weight:800;color:{_couleur};letter-spacing:2px;text-transform:uppercase;'>"
        f"STATUT : {_statut}</span>",
        unsafe_allow_html=True
    )
    st.info(analyse['message'])
    with st.expander("DETAILS FINANCIERS"):
        st.markdown(analyse['details'])

    # ── TABLEAU D'AMORTISSEMENT ───────────────────────────────────────────
    st.markdown('<span class="le-section-tag">// TABLEAU D\'ECHEANCES</span>', unsafe_allow_html=True)

    date_debut = date.today()
    df_amort = generer_tableau_amortissement(
        type_code, montant, taux_hebdo, duree_semaines,
        montant_versement, nb_versements, date_debut,
        dates_versements=dates_versements,
        frais_transfert=frais_transfert,
        forfait_fixe_pct=regles["Regle_Forfait_Duree_Minimale_Pct"] if forfait_applique else None,
    )
    if not df_amort.empty:
        df_amort.insert(0, "Type", type_pret)
    st.dataframe(df_amort, hide_index=True, use_container_width=True)

    # ── TAUX D'ENDETTEMENT ────────────────────────────────────────────────
    from Analytics.AnalyseFinance import calculer_taux_endettement
    taux_endettement = calculer_taux_endettement(
        type_code, montant_versement, nb_versements, duree_semaines,
        client_info['Revenus_Mensuels'], pers_charge=pers_charge
    )
    st.info(f"TAUX D'ENDETTEMENT CALCULE : {taux_endettement:.2f}%")

    # ── VALIDATION ────────────────────────────────────────────────────────
    st.markdown('<span class="le-section-tag">// VALIDATION & OCTROI</span>', unsafe_allow_html=True)

    with st.form("valid_pret"):
        submit = rendre_form_submit_protege("[ OCTROYER & GENERER DOCS ]", cle=f"octroi_direct_{client_id}")

    if submit:
        try:
            ws_prets = sh.worksheet("Prets_Master")
            new_id   = generate_next_id(ws_prets, "PRT")

            row_data = [
                new_id,                                              # ID_Pret
                client_id,                                           # ID_Client
                client_info['Nom_Complet'],                          # Nom_Complet
                offre_selectionnee,                                  # Offre [OK]
                type_code,                                           # Type_Pret
                motif,                                               # Motif
                montant,                                             # Montant_Capital
                taux_hebdo,                                          # Taux_Hebdo
                round(taux_endettement, 2),                          # Taux_Endettement
                duree_semaines,                                      # Duree_Semaines
                round(montant_versement),                            # Montant_Versement
                round(montant_total),                                # Montant_Total
                round(cout_credit),                                  # Cout_Credit
                nb_versements,                                       # Nb_Versements
                ";".join([d.strftime("%d/%m/%Y") for d in dates_versements]) if dates_versements else "",  # Dates_Versements
                date_debut.strftime("%d/%m/%Y"),                     # Date_Deblocage
                date_fin.strftime("%d/%m/%Y"),                       # Date_Fin
                moyen_transfert,                                     # Moyen_Transfert
                sg.STATUT_PRET_EN_ATTENTE,                           # Statut : ACTIF seulement apres signature
                garant_id,                                           # ID_Garant
                datetime.now().strftime("%d/%m/%Y %H:%M:%S"),        # Date_Creation
                datetime.now().strftime("%d/%m/%Y %H:%M:%S"),        # Date_Update
            ]
            ws_prets.append_row(row_data)
            get_cached_data.clear()
            clear_sheets_cache()

            st.session_state.loan_validated = True
            st.session_state.loan_id        = new_id
            st.session_state.loan_data      = {
                "ID_Pret":          new_id,
                "Offre":            offre_selectionnee,
                "Montant_Capital":  montant,
                "Montant_Total":    montant_total,
                "Taux_Hebdo":       taux_hebdo,
                "Taux_Endettement": taux_endettement,
                "Duree_Semaines":   duree_semaines,
                "Motif":            motif,
                "Date_Deblocage":   date_debut.strftime("%d/%m/%Y"),
                "Date_Fin":         date_fin.strftime("%d/%m/%Y"),
            }
            st.session_state.client_data = client_info.to_dict()
            st.session_state.garant_data = selected_garant.to_dict() if selected_garant is not None else None
            st.session_state.df_amort    = df_amort.copy()

            # Signature electronique : le pret reste EN_ATTENTE_SIGNATURE (bloque) tant que le client
            # (et le garant) n'ont pas signe via le lien recu par email.
            snapshot_sig = sg.construire_snapshot(
                {**st.session_state.loan_data, "ID_Client": client_id, "ID_Garant": garant_id,
                 "Type_Pret": type_code, "Montant_Versement": round(montant_versement),
                 "Nb_Versements": nb_versements, "Cout_Credit": round(cout_credit),
                 "Moyen_Transfert": moyen_transfert},
                st.session_state.client_data, st.session_state.garant_data, df_amort)
            st.session_state.signature_snapshot = snapshot_sig
            try:
                st.session_state.signature_resultats = svc.lancer_signature_pret(
                    sh, id_pret=new_id, source=svc.SOURCE_MASTER, snapshot=snapshot_sig)
            except Exception as exc:
                from core.errors import log_swallowed
                log_swallowed(f"Lancement de la signature du pret {new_id} echoue", exc)
                st.session_state.signature_resultats = [
                    {"role": sg.ROLE_EMPRUNTEUR, "ok": False, "detail": f"Erreur technique : {exc}", "id_signature": None}]

            marquer_fait(f"octroi_direct_{client_id}")
            st.success(f"PRET {new_id} ENREGISTRE β€” EN ATTENTE DE SIGNATURE β€” OFFRE : {offre_selectionnee}")
        except Exception as e:
            liberer(f"octroi_direct_{client_id}")
            st.error(f"Erreur lors de l'octroi : {e}")

    # ── DOCUMENTS PDF & ENVOI MAIL ────────────────────────────────────────
    if st.session_state.get('loan_validated', False):
        st.markdown('<span class="le-section-tag">// DOCUMENTS & TRANSMISSION</span>', unsafe_allow_html=True)
        st.markdown(f"PRET **{st.session_state.loan_id}** β€” OFFRE : **{st.session_state.loan_data.get('Offre', '')}**")

        loan_data       = st.session_state.loan_data
        client_data     = st.session_state.client_data
        garant_data     = st.session_state.garant_data
        df_amort_saved  = st.session_state.df_amort

        # GΓ©nΓ©ration unique des PDF en mΓ©moire
        if st.session_state.get('pdf_contrat_for') != st.session_state.loan_id:
            for _k in ['pdf_contrat', 'pdf_dette', 'pdf_caution', 'pdf_contrat_for']:
                st.session_state.pop(_k, None)

        if 'pdf_contrat' not in st.session_state:
            with st.spinner("GΓ©nΓ©ration des documents PDF..."):
                st.session_state.pdf_contrat = generer_contrat_pret(loan_data, client_data, df_amort_saved)
                st.session_state.pdf_dette = generer_reconnaissance_dette(loan_data, client_data)
                if garant_data is not None:
                    st.session_state.pdf_caution = generer_contrat_caution(loan_data, garant_data)
                else:
                    st.session_state.pdf_caution = None
                st.session_state.pdf_contrat_for = st.session_state.loan_id

        col_dl1, col_dl2, col_dl3 = st.columns(3)

        with col_dl1:
            st.download_button(
                "TΓ©lΓ©charger Contrat", st.session_state.pdf_contrat,
                f"Contrat_{st.session_state.loan_id}.pdf", "application/pdf",
                use_container_width=True
            )
        with col_dl2:
            st.download_button(
                "TΓ©lΓ©charger Dette", st.session_state.pdf_dette,
                f"Dette_{st.session_state.loan_id}.pdf", "application/pdf",
                use_container_width=True
            )
        with col_dl3:
            if st.session_state.pdf_caution:
                st.download_button(
                    "TΓ©lΓ©charger Caution", st.session_state.pdf_caution,
                    f"Caution_{st.session_state.loan_id}.pdf", "application/pdf",
                    use_container_width=True
                )
            else:
                st.info("Aucun garant associΓ©")

        st.divider()

        # ── Signature electronique ────────────────────────────────────────
        st.markdown('<span class="le-section-tag">// SIGNATURE ELECTRONIQUE</span>', unsafe_allow_html=True)
        resultats_sig = st.session_state.get('signature_resultats') or []
        if not resultats_sig:
            st.warning("Aucune demande de signature lancee pour ce pret.")
        for r in resultats_sig:
            if r["ok"]:
                st.success(f"{r['role'].title()} : lien de signature envoye par email.")
            else:
                st.error(f"{r['role'].title()} : {r['detail']}")
        st.caption("Le pret reste EN_ATTENTE_SIGNATURE (aucun remboursement possible) jusqu'a la signature de toutes "
                   "les parties. Suivi, relances et renvois : module Signatures.")

        col_sig, col_reset = st.columns([2, 1])

        with col_sig:
            if (not resultats_sig or any(not r["ok"] for r in resultats_sig)) and st.session_state.get('signature_snapshot'):
                if rendre_bouton_protege(
                    "RELANCER L'ENVOI DES LIENS", cle=f"lock_relance_sig_{loan_data['ID_Pret']}", use_container_width=True,
                ):
                    try:
                        st.session_state.signature_resultats = svc.lancer_signature_pret(
                            sh, id_pret=loan_data['ID_Pret'], source=svc.SOURCE_MASTER,
                            snapshot=st.session_state.signature_snapshot)
                    except Exception as exc:
                        st.error(f"Erreur technique : {exc}")
                    liberer(f"lock_relance_sig_{loan_data['ID_Pret']}")
                    st.rerun()

        with col_reset:
            if st.button("Octroyer un nouveau prΓͺt", use_container_width=True, key="loans_engine_nouvel_octroi"):
                liberer(f"octroi_direct_{client_id}")
                for key in ['loan_validated', 'loan_id', 'loan_data', 'client_data', 'garant_data',
                            'df_amort', 'pdf_contrat', 'pdf_dette', 'pdf_caution', 'pdf_contrat_for',
                            'dates_perso', 'selected_offre', 'signature_snapshot', 'signature_resultats']:
                    st.session_state.pop(key, None)
                st.rerun()

    render_scoped_widget(
        client, sheet_name,
        scope_label=f"Octroi de prΓͺt en cours β€” {client_info.get('Nom_Complet', client_id)}",
        context_data={
            "client": {"id": client_id},  # pas de nom : donnee personnelle non envoyee au LLM
            "pret": {
                "offre": offre_selectionnee,
                "montant_xof": montant,
                "montant_total_xof": montant_total,
                "taux_hebdo_pct": taux_hebdo,
                "type_pret": type_code,
                "taux_endettement_pct": taux_endettement,
                "statut_analyse": _statut,
            },
            "guide_page": (
                "Moteur d'octroi : simulation puis crΓ©ation effective d'un nouveau prΓͺt. L'agent "
                "choisit le type de remboursement et le montant, le système calcule l'échéancier, "
                "le taux d'endettement et un statut de capacitΓ©, puis 'OCTROYER & GENERER DOCS' "
                "Γ©crit le prΓͺt dans Prets_Master (statut ACTIF) et gΓ©nΓ¨re les documents contractuels."
            ),
            "definitions_champs": {
                "montant_xof": "Capital demandΓ©, saisi par l'agent.",
                "montant_total_xof": "Capital + coΓ»t du crΓ©dit β€” montant total Γ  rembourser sur toute la durΓ©e.",
                "taux_hebdo_pct": "Taux d'intΓ©rΓͺt hebdomadaire saisi par l'agent.",
                "type_pret": (
                    "Mode de remboursement : IN_FINE (versement unique en fin de pΓ©riode, capital+intΓ©rΓͺts) ; "
                    "MENSUEL_INTERETS (mensualitΓ©s d'intΓ©rΓͺts seuls, capital in fine) ; "
                    "MENSUEL_CONSTANT (mensualitΓ©s constantes, capital+intΓ©rΓͺts amortis) ; "
                    "HEBDOMADAIRE (versements hebdomadaires constants) ; PERSONNALISE (Γ©chΓ©ancier Γ  dates libres)."
                ),
                "taux_endettement_pct": "Charge mensuelle de ce prΓͺt / revenus mensuels du client (ajustΓ©s des personnes Γ  charge), en %.",
                "statut_analyse": "Verdict de capacitΓ© de remboursement : EXCELLENT, BON, ACCEPTABLE ou INSUFFISANT (risque Γ©levΓ©).",
            },
        },
        key_prefix="loans_engine",
    )