File size: 57,247 Bytes
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
f5a1357
 
 
 
 
 
 
4924e8e
f5a1357
4924e8e
 
f5a1357
4924e8e
 
 
f5a1357
 
4924e8e
 
f5a1357
4924e8e
 
 
f5a1357
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
4924e8e
 
f5a1357
4924e8e
 
 
f5a1357
 
4924e8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a1357
4924e8e
 
 
 
 
 
 
f5a1357
4924e8e
 
f5a1357
 
 
 
 
 
4924e8e
 
 
 
 
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
f5a1357
 
 
 
 
4924e8e
f5a1357
4924e8e
 
 
 
 
 
 
f5a1357
4924e8e
f5a1357
4924e8e
 
 
 
f5a1357
 
 
 
 
4924e8e
f5a1357
4924e8e
 
 
 
f5a1357
 
 
 
4924e8e
f5a1357
4924e8e
 
 
 
 
 
 
f5a1357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4924e8e
 
 
 
f5a1357
 
 
 
 
 
 
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
"""
flowchart_engine.py - Moteur du logigramme d'aide à la détermination de l'impact carbone.

Suit le logigramme JSON pour déterminer quelle valeur d'impact carbone utiliser
en fonction de la provenance, du niveau de transformation, et des données disponibles.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import List, Optional, Tuple

import config
import data_loader
import llm_service


@dataclass
class StepLog:
    """Un pas dans le parcours du logigramme."""
    node_id: str
    question: Optional[str]
    answer: Optional[str]
    action: Optional[str] = None
    result: Optional[str] = None


@dataclass
class CarbonResult:
    """Résultat complet de l'évaluation carbone d'une matière première."""
    matiere_premiere: str
    pays_production: Optional[str]
    pays_transformation: Optional[str]
    classification: str  # "brut" | "transforme"
    classification_justification: str
    
    # Valeur finale
    impact_kg_co2_eq: Optional[float] = None
    impact_tonne_co2_eq: Optional[float] = None  # conversion en tonnes
    unite_source: str = ""  # "kg CO2 eq / kg" ou "kg CO2 eq / tonne"
    
    # Traçabilité
    source_db: str = ""  # "ECOALIM" | "GFLI"
    intrant_utilise: str = ""  # nom exact dans la BDD
    match_exact: bool = True
    justification_alternative: Optional[str] = None
    
    # Parcours de logique
    parcours: List[StepLog] = field(default_factory=list)
    node_resultat: str = ""  # node_id du résultat
    actions_appliquees: List[str] = field(default_factory=list)
    
    # Candidats alternatifs (pour affichage comparatif quand match non exact)
    candidats_alternatifs: List[dict] = field(default_factory=list)
    candidat_recommande: Optional[str] = None
    candidats_reflexion: Optional[str] = None
    
    # 4 propositions d'alternatives (itinerary, locality, form, combined)
    alternatives_itinerary: Optional[dict] = None
    alternatives_locality: Optional[dict] = None
    alternatives_form: Optional[dict] = None
    alternatives_combined: Optional[dict] = None
    
    erreur: Optional[str] = None


def _is_france(pays: Optional[str]) -> bool:
    """Vérifie si le pays est la France."""
    if not pays:
        return False
    return pays.lower().strip() in ("france", "fr")


def _is_european(pays: Optional[str]) -> bool:
    """Vérifie si le pays est européen."""
    if not pays:
        return False
    pays_low = pays.lower().strip()
    if pays_low in config.EUROPEAN_COUNTRIES_FR:
        return True
    pays_iso = config.PAYS_FR_TO_ISO.get(pays_low, "").upper()
    return pays_iso in config.EUROPEAN_COUNTRIES_ISO


def _get_country_iso(pays: Optional[str]) -> Optional[str]:
    """Convertit un nom de pays FR en code ISO."""
    if not pays:
        return None
    return config.PAYS_FR_TO_ISO.get(pays.lower().strip())


def _is_name_match(matiere: str, intrant_name: str) -> bool:
    """
    Vérifie si le nom de la matière est une correspondance réelle (mot entier)
    dans le nom de l'intrant, et non un simple sous-chaîne accidentelle.
    Délègue à data_loader.is_name_match.
    """
    return data_loader.is_name_match(matiere, intrant_name)


# ============================================================================
# Fonctions de résolution par node de résultat
# ============================================================================

def _resolve_node_4(matiere: str, result: CarbonResult) -> CarbonResult:
    """
    Node 4 : Provenance inconnue + intrant brut.
    1. Valeur la plus défavorable dans GFLI
    2. Sinon la plus défavorable dans ECOALIM
    3. Sinon valeur GFLI de l'intrant au schéma cultural le plus proche (LLM)
    """
    # Étape 1 : GFLI worst
    result.actions_appliquees.append("1. Recherche de la valeur la plus défavorable dans GFLI")
    gfli_worst = data_loader.get_gfli_worst_value(matiere)

    # Rejeter les faux positifs (ex : "blé" → "blend")
    if gfli_worst and not _is_name_match(matiere, gfli_worst[1]):
        result.actions_appliquees.append(f"   ⚠ Faux positif rejeté : {gfli_worst[1]}")
        gfli_worst = None

    llm_justification = None
    llm_match_exact = None
    if not gfli_worst:
        gfli_smart = llm_service.smart_search_gfli(matiere)
        if gfli_smart and "valeur_kg_co2_eq_par_tonne" in gfli_smart:
            llm_match_exact = gfli_smart.get("match_exact", False)
            llm_justification = gfli_smart.get("justification")
            base_name = gfli_smart["nom_intrant"].split(",")[0].split("/")[0].strip()
            gfli_worst = data_loader.get_gfli_worst_value(base_name)
            if not gfli_worst:
                # Utiliser directement la valeur du LLM
                gfli_worst = (
                    gfli_smart["valeur_kg_co2_eq_par_tonne"],
                    gfli_smart["nom_intrant"],
                    gfli_smart.get("source", "GFLI"),
                )

    if gfli_worst:
        val, nom, src = gfli_worst
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = src
        result.intrant_utilise = nom
        # Déterminer si le match est exact
        if llm_match_exact is not None:
            result.match_exact = llm_match_exact
        else:
            result.match_exact = _is_name_match(matiere, nom)
        if llm_justification:
            result.justification_alternative = llm_justification
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {nom} = {val:.2f} kg CO2 eq/t")
        return result

    # Étape 2 : ECOALIM worst
    result.actions_appliquees.append("2. Recherche de la valeur la plus défavorable dans ECOALIM")
    eco_worst = data_loader.get_ecoalim_worst_value(matiere)

    # Rejeter les faux positifs
    if eco_worst and not _is_name_match(matiere, eco_worst[1]):
        result.actions_appliquees.append(f"   ⚠ Faux positif rejeté : {eco_worst[1]}")
        eco_worst = None

    llm_justification_eco = None
    llm_match_exact_eco = None
    if not eco_worst:
        eco_smart = llm_service.smart_search_ecoalim(matiere)
        if eco_smart:
            llm_match_exact_eco = eco_smart.get("match_exact", False)
            llm_justification_eco = eco_smart.get("justification")
            eco_worst = data_loader.get_ecoalim_worst_value(
                eco_smart["nom_intrant"].split(",")[0].strip()
            )
            if not eco_worst:
                eco_worst = (
                    eco_smart["valeur_kg_co2_eq"],
                    eco_smart["nom_intrant"],
                    eco_smart.get("source", "ECOALIM"),
                )

    if eco_worst:
        val, nom, src = eco_worst
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = src
        result.intrant_utilise = nom
        if llm_match_exact_eco is not None:
            result.match_exact = llm_match_exact_eco
        else:
            result.match_exact = _is_name_match(matiere, nom)
        if llm_justification_eco:
            result.justification_alternative = llm_justification_eco
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {nom} = {val:.4f} kg CO2 eq/kg")
        return result

    # Étape 3 : LLM pour trouver le schéma cultural le plus proche
    result.actions_appliquees.append("3. Recherche via LLM de l'intrant au schéma cultural le plus proche (GFLI)")
    gfli_smart = llm_service.smart_search_gfli(matiere)
    if gfli_smart and "valeur_kg_co2_eq_par_tonne" in gfli_smart:
        val = gfli_smart["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_smart["source"]
        result.intrant_utilise = gfli_smart["nom_intrant"]
        result.match_exact = gfli_smart.get("match_exact", False)
        result.justification_alternative = gfli_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {gfli_smart['nom_intrant']} = {val:.2f} kg CO2 eq/t")
        return result

    # Étape 4 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append("4. Fallback - Recherche via LLM de 4 alternatives")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI")
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' dans GFLI ni ECOALIM."
    return result


def _resolve_node_5(matiere: str, result: CarbonResult) -> CarbonResult:
    """
    Node 5 : Provenance inconnue + intrant transformé.
    Mêmes étapes que node_4 mais pour un intrant transformé.
    """
    # Étape 1 : GFLI worst
    result.actions_appliquees.append("1. Recherche de la valeur la plus défavorable pour l'intrant transformé dans GFLI")
    gfli_worst = data_loader.get_gfli_worst_value(matiere)

    # Rejeter les faux positifs
    if gfli_worst and not _is_name_match(matiere, gfli_worst[1]):
        result.actions_appliquees.append(f"   ⚠ Faux positif rejeté : {gfli_worst[1]}")
        gfli_worst = None

    llm_justification = None
    llm_match_exact = None
    if not gfli_worst:
        gfli_smart = llm_service.smart_search_gfli(matiere)
        if gfli_smart and "valeur_kg_co2_eq_par_tonne" in gfli_smart:
            llm_match_exact = gfli_smart.get("match_exact", False)
            llm_justification = gfli_smart.get("justification")
            base_name = gfli_smart["nom_intrant"].split(",")[0].split("/")[0].strip()
            gfli_worst = data_loader.get_gfli_worst_value(base_name)
            if not gfli_worst:
                gfli_worst = (
                    gfli_smart["valeur_kg_co2_eq_par_tonne"],
                    gfli_smart["nom_intrant"],
                    gfli_smart.get("source", "GFLI"),
                )

    if gfli_worst:
        val, nom, src = gfli_worst
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = src
        result.intrant_utilise = nom
        if llm_match_exact is not None:
            result.match_exact = llm_match_exact
        else:
            result.match_exact = _is_name_match(matiere, nom)
        if llm_justification:
            result.justification_alternative = llm_justification
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {nom} = {val:.2f} kg CO2 eq/t")
        return result

    # Étape 2 : ECOALIM worst
    result.actions_appliquees.append("2. Recherche de la valeur la plus défavorable dans ECOALIM")
    eco_worst = data_loader.get_ecoalim_worst_value(matiere)

    if eco_worst and not _is_name_match(matiere, eco_worst[1]):
        result.actions_appliquees.append(f"   ⚠ Faux positif rejeté : {eco_worst[1]}")
        eco_worst = None

    llm_justification_eco = None
    llm_match_exact_eco = None
    if not eco_worst:
        eco_smart = llm_service.smart_search_ecoalim(matiere)
        if eco_smart:
            llm_match_exact_eco = eco_smart.get("match_exact", False)
            llm_justification_eco = eco_smart.get("justification")
            eco_worst = data_loader.get_ecoalim_worst_value(
                eco_smart["nom_intrant"].split(",")[0].strip()
            )
            if not eco_worst:
                eco_worst = (
                    eco_smart["valeur_kg_co2_eq"],
                    eco_smart["nom_intrant"],
                    eco_smart.get("source", "ECOALIM"),
                )

    if eco_worst:
        val, nom, src = eco_worst
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = src
        result.intrant_utilise = nom
        if llm_match_exact_eco is not None:
            result.match_exact = llm_match_exact_eco
        else:
            result.match_exact = _is_name_match(matiere, nom)
        if llm_justification_eco:
            result.justification_alternative = llm_justification_eco
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {nom} = {val:.4f} kg CO2 eq/kg")
        return result

    # Étape 3 : LLM
    result.actions_appliquees.append("3. Recherche via LLM de l'intrant transformé au process le plus proche (GFLI)")
    gfli_smart = llm_service.smart_search_gfli(matiere)
    if gfli_smart and "valeur_kg_co2_eq_par_tonne" in gfli_smart:
        val = gfli_smart["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_smart["source"]
        result.intrant_utilise = gfli_smart["nom_intrant"]
        result.match_exact = gfli_smart.get("match_exact", False)
        result.justification_alternative = gfli_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {gfli_smart['nom_intrant']}")
        return result

    # Étape 4 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append("4. Fallback - Recherche via LLM de 4 alternatives (transformée)")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI")
    
    if alternatives:
        # Stocker les 4 alternatives
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (transformé, provenance inconnue)."
    return result


def _resolve_node_8(matiere: str, result: CarbonResult) -> CarbonResult:
    """
    Node 8 : Provenance connue + brut + cultivé en France.
    1. EcoALIM
    2. GFLI
    3. Intrant à la pratique culturale la plus proche dans EcoALIM (LLM)
    """
    result.actions_appliquees.append("1. Recherche dans ECOALIM pour la France")
    eco_result = llm_service.smart_search_ecoalim(matiere, pays_production="France")
    if eco_result:
        val = eco_result["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_result["source"]
        result.intrant_utilise = eco_result["nom_intrant"]
        result.match_exact = eco_result["match_exact"]
        result.justification_alternative = eco_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {eco_result['nom_intrant']} = {val:.4f} kg CO2 eq/kg")
        return result

    result.actions_appliquees.append("2. Recherche dans GFLI pour FR")
    gfli_result = llm_service.smart_search_gfli(matiere, country_iso="FR")
    if gfli_result:
        val = gfli_result["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_result["source"]
        result.intrant_utilise = gfli_result["nom_intrant"]
        result.match_exact = gfli_result["match_exact"]
        result.justification_alternative = gfli_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {gfli_result['nom_intrant']}")
        return result

    result.actions_appliquees.append("3. Recherche via LLM de la pratique culturale la plus proche dans ECOALIM")
    eco_smart = llm_service.smart_search_ecoalim(matiere)
    if eco_smart:
        val = eco_smart["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_smart["source"]
        result.intrant_utilise = eco_smart["nom_intrant"]
        result.match_exact = False
        result.justification_alternative = eco_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {eco_smart['nom_intrant']}")
        return result

    # Étape 4 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append("4. Fallback - Recherche via LLM de 4 alternatives (France)")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI", country_hint="France")
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (brut, France)."
    return result


def _resolve_node_9(matiere: str, pays_production: str, result: CarbonResult) -> CarbonResult:
    """
    Node 9 : Provenance connue + brut + cultivé hors France.
    1. GFLI du pays correspondant
    2. RER (Europe) ou GLO (autre continent)
    3. EcoALIM
    """
    country_iso = _get_country_iso(pays_production)

    result.actions_appliquees.append(f"1. Recherche dans GFLI pour le pays {pays_production} (ISO: {country_iso})")
    gfli_result = llm_service.smart_search_gfli(matiere, country_iso=country_iso)
    if gfli_result:
        val = gfli_result["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_result["source"]
        result.intrant_utilise = gfli_result["nom_intrant"]
        result.match_exact = gfli_result["match_exact"]
        result.justification_alternative = gfli_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {gfli_result['nom_intrant']}")
        return result

    # Étape 2 : RER ou GLO
    is_eu = _is_european(pays_production)
    if is_eu:
        result.actions_appliquees.append("2. Pays européen → Recherche Mix Européen (RER) dans GFLI")
        rer = llm_service.smart_search_gfli(matiere, country_iso="RER")
        if rer:
            val = rer["valeur_kg_co2_eq_par_tonne"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = rer["source"] + " (Mix Européen RER)"
            result.intrant_utilise = rer["nom_intrant"]
            result.match_exact = rer["match_exact"]
            result.justification_alternative = rer.get("justification")
            result.actions_appliquees.append(f"   → Trouvé RER : {rer['nom_intrant']}")
            return result
    else:
        result.actions_appliquees.append("2. Pays hors Europe → Recherche Mix Monde (GLO) dans GFLI")
        glo = llm_service.smart_search_gfli(matiere, country_iso="GLO")
        if glo:
            val = glo["valeur_kg_co2_eq_par_tonne"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = glo["source"] + " (Mix Monde GLO)"
            result.intrant_utilise = glo["nom_intrant"]
            result.match_exact = glo["match_exact"]
            result.justification_alternative = glo.get("justification")
            result.actions_appliquees.append(f"   → Trouvé GLO : {glo['nom_intrant']}")
            return result

    result.actions_appliquees.append("3. Recherche dans ECOALIM")
    eco_result = llm_service.smart_search_ecoalim(matiere, pays_production=pays_production)
    if eco_result:
        val = eco_result["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_result["source"]
        result.intrant_utilise = eco_result["nom_intrant"]
        result.match_exact = eco_result["match_exact"]
        result.justification_alternative = eco_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {eco_result['nom_intrant']}")
        return result

    # Étape 4 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append(f"4. Fallback - Recherche via LLM de 4 alternatives ({pays_production})")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI", country_hint=pays_production)
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (brut, {pays_production})."
    return result


def _resolve_node_10(matiere: str, result: CarbonResult) -> CarbonResult:
    """
    Node 10 : Provenance connue + transformé + France/France.
    1. EcoALIM pour l'intrant transformé
    2. A/ impact process connu : brut EcoALIM + process / B/ sinon GFLI
    3. Intrant au process le plus proche dans EcoALIM (LLM)
    """
    result.actions_appliquees.append("1. Recherche dans ECOALIM (transformé France/France)")
    eco_result = llm_service.smart_search_ecoalim(matiere, pays_production="France", pays_transformation="France")
    if eco_result:
        val = eco_result["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_result["source"]
        result.intrant_utilise = eco_result["nom_intrant"]
        result.match_exact = eco_result["match_exact"]
        result.justification_alternative = eco_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {eco_result['nom_intrant']} = {val:.4f}")
        return result

    # Étape 2 : GFLI France
    result.actions_appliquees.append("2. Impact process non connu → Recherche dans GFLI (FR)")
    gfli_result = llm_service.smart_search_gfli(matiere, country_iso="FR")
    if gfli_result:
        val = gfli_result["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_result["source"]
        result.intrant_utilise = gfli_result["nom_intrant"]
        result.match_exact = gfli_result["match_exact"]
        result.justification_alternative = gfli_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {gfli_result['nom_intrant']}")
        return result

    # Étape 3 : LLM process le plus proche
    result.actions_appliquees.append("3. Recherche via LLM du process le plus proche dans ECOALIM")
    eco_smart = llm_service.smart_search_ecoalim(matiere)
    if eco_smart:
        val = eco_smart["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_smart["source"]
        result.intrant_utilise = eco_smart["nom_intrant"]
        result.match_exact = False
        result.justification_alternative = eco_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {eco_smart['nom_intrant']}")
        return result

    # Étape 4 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append("4. Fallback - Recherche via LLM de 4 alternatives (France)")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI", country_hint="France")
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val
            result.unite_source = "kg CO2 eq / kg de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.4f} kg CO2 eq/kg")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (transformé, France/France)."
    return result


def _resolve_node_11(matiere: str, result: CarbonResult) -> CarbonResult:
    """
    Node 11 : Transformé en France, MP brute non FR ou inconnue.
    1. GFLI France
    2. A/ process connu → brut GFLI + process / B/ sinon RER
    3. EcoALIM
    4. Pratique culturale la plus proche GFLI (LLM)
    """
    result.actions_appliquees.append("1. Recherche dans GFLI (France)")
    gfli_result = llm_service.smart_search_gfli(matiere, country_iso="FR")
    if gfli_result:
        val = gfli_result["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_result["source"]
        result.intrant_utilise = gfli_result["nom_intrant"]
        result.match_exact = gfli_result["match_exact"]
        result.justification_alternative = gfli_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {gfli_result['nom_intrant']}")
        return result

    # Étape 2 : RER
    result.actions_appliquees.append("2. Impact process non connu → Recherche Mix Européen (RER) dans GFLI")
    rer = llm_service.smart_search_gfli(matiere, country_iso="RER")
    if rer:
        val = rer["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = rer["source"] + " (Mix Européen RER)"
        result.intrant_utilise = rer["nom_intrant"]
        result.match_exact = rer["match_exact"]
        result.justification_alternative = rer.get("justification")
        result.actions_appliquees.append(f"   → Trouvé RER : {rer['nom_intrant']}")
        return result

    # Étape 3 : EcoALIM
    result.actions_appliquees.append("3. Recherche dans ECOALIM")
    eco_result = llm_service.smart_search_ecoalim(matiere)
    if eco_result:
        val = eco_result["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_result["source"]
        result.intrant_utilise = eco_result["nom_intrant"]
        result.match_exact = eco_result["match_exact"]
        result.justification_alternative = eco_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {eco_result['nom_intrant']}")
        return result

    # Étape 4 : LLM
    result.actions_appliquees.append("4. Recherche via LLM de la pratique culturale la plus proche (GFLI)")
    gfli_smart = llm_service.smart_search_gfli(matiere)
    if gfli_smart:
        val = gfli_smart["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_smart["source"]
        result.intrant_utilise = gfli_smart["nom_intrant"]
        result.match_exact = False
        result.justification_alternative = gfli_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {gfli_smart['nom_intrant']}")
        return result

    # Étape 5 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append("5. Fallback - Recherche via LLM de 4 alternatives (France)")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI", country_hint="France")
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (transformé France, MP brute hors FR)."
    return result


def _resolve_node_12(matiere: str, pays_transformation: str, result: CarbonResult) -> CarbonResult:
    """
    Node 12 : Transformé hors France.
    1. GFLI du pays correspondant
    2. A/ process connu / B/ sinon RER (Europe) ou GLO (autre)
    3. EcoALIM
    4. Pratique culturale la plus proche GFLI (LLM)
    """
    country_iso = _get_country_iso(pays_transformation)

    result.actions_appliquees.append(f"1. Recherche dans GFLI pour {pays_transformation} (ISO: {country_iso})")
    gfli_result = llm_service.smart_search_gfli(matiere, country_iso=country_iso)
    if gfli_result:
        val = gfli_result["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_result["source"]
        result.intrant_utilise = gfli_result["nom_intrant"]
        result.match_exact = gfli_result["match_exact"]
        result.justification_alternative = gfli_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans GFLI : {gfli_result['nom_intrant']}")
        return result

    # Étape 2 : RER ou GLO
    is_eu = _is_european(pays_transformation)
    if is_eu:
        result.actions_appliquees.append("2. Pays européen → Recherche Mix Européen (RER)")
        fallback = llm_service.smart_search_gfli(matiere, country_iso="RER")
    else:
        result.actions_appliquees.append("2. Pays hors Europe → Recherche Mix Monde (GLO)")
        fallback = llm_service.smart_search_gfli(matiere, country_iso="GLO")

    if fallback:
        val = fallback["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        mix_type = "RER" if is_eu else "GLO"
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = fallback["source"] + f" (Mix {mix_type})"
        result.intrant_utilise = fallback["nom_intrant"]
        result.match_exact = fallback["match_exact"]
        result.justification_alternative = fallback.get("justification")
        result.actions_appliquees.append(f"   → Trouvé {mix_type} : {fallback['nom_intrant']}")
        return result

    # Étape 3 : EcoALIM
    result.actions_appliquees.append("3. Recherche dans ECOALIM")
    eco_result = llm_service.smart_search_ecoalim(matiere)
    if eco_result:
        val = eco_result["valeur_kg_co2_eq"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / kg de produit"
        result.source_db = eco_result["source"]
        result.intrant_utilise = eco_result["nom_intrant"]
        result.match_exact = eco_result["match_exact"]
        result.justification_alternative = eco_result.get("justification")
        result.actions_appliquees.append(f"   → Trouvé dans ECOALIM : {eco_result['nom_intrant']}")
        return result

    # Étape 4 : LLM
    result.actions_appliquees.append("4. Recherche via LLM de la pratique culturale la plus proche (GFLI)")
    gfli_smart = llm_service.smart_search_gfli(matiere)
    if gfli_smart:
        val = gfli_smart["valeur_kg_co2_eq_par_tonne"]
        result.impact_kg_co2_eq = val
        result.impact_tonne_co2_eq = val / 1000.0
        result.unite_source = "kg CO2 eq / tonne de produit"
        result.source_db = gfli_smart["source"]
        result.intrant_utilise = gfli_smart["nom_intrant"]
        result.match_exact = False
        result.justification_alternative = gfli_smart.get("justification")
        result.actions_appliquees.append(f"   → Via LLM : {gfli_smart['nom_intrant']}")
        return result

    # Étape 5 : Fallback - Proposer des matières alternatives
    result.actions_appliquees.append(f"5. Fallback - Recherche via LLM de 4 alternatives ({pays_transformation})")
    alternatives = llm_service.find_alternative_materials(matiere, db_name="GFLI", country_hint=pays_transformation)
    
    if alternatives:
        # Stocker les 4 alternatives dans CarbonResult
        if alternatives.get("itinerary"):
            alt = alternatives["itinerary"]
            result.alternatives_itinerary = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("locality"):
            alt = alternatives["locality"]
            result.alternatives_locality = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("form"):
            alt = alternatives["form"]
            result.alternatives_form = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
        if alternatives.get("combined"):
            alt = alternatives["combined"]
            result.alternatives_combined = {
                "name": alt["name"],
                "impact": alt["impact"],
                "source": alt["source"],
                "reasoning": alt["reasoning"],
            }
            # Utiliser la combined comme valeur principale
            val = alt["impact"]
            result.impact_kg_co2_eq = val
            result.impact_tonne_co2_eq = val / 1000.0
            result.unite_source = "kg CO2 eq / tonne de produit"
            result.source_db = alt["source"]
            result.intrant_utilise = alt["name"]
            result.match_exact = False
            result.justification_alternative = alt["reasoning"]
            result.actions_appliquees.append(f"   → Matière proposée (combo) : {alt['name']} = {val:.2f} kg CO2 eq/t")
            return result

    result.erreur = f"Aucune valeur trouvée pour '{matiere}' (transformé hors France)."
    return result


# ============================================================================
# Moteur principal
# ============================================================================

def evaluate_carbon_impact(
    matiere_premiere: str,
    pays_production: Optional[str] = None,
    pays_transformation: Optional[str] = None,
) -> CarbonResult:
    """
    Point d'entrée principal : évalue l'impact carbone d'une matière première
    en suivant le logigramme.
    
    Args:
        matiere_premiere: Nom de la matière première (ex: "BLE", "T.TNSL DEC.", "SOJA")
        pays_production: Pays de production de la MP brute (ex: "France", "Brésil") ou None si inconnu
        pays_transformation: Pays de transformation (ex: "France") ou None si pas de transformation
    
    Returns:
        CarbonResult avec toutes les informations
    """
    result = CarbonResult(
        matiere_premiere=matiere_premiere,
        pays_production=pays_production,
        pays_transformation=pays_transformation,
        classification="",
        classification_justification="",
    )

    # -----------------------------------------------------------------------
    # Étape 1 : Classifier brut vs transformé via LLM + PDF CIR
    # -----------------------------------------------------------------------
    classification = llm_service.determine_brut_ou_transforme(matiere_premiere)
    result.classification = classification.get("classification", "brut")
    result.classification_justification = classification.get("justification", "")
    is_transformed = result.classification == "transforme"

    result.parcours.append(StepLog(
        node_id="classification",
        question="La matière est-elle brute ou transformée ?",
        answer=f"{'Transformée' if is_transformed else 'Brute'}{result.classification_justification}",
    ))

    # -----------------------------------------------------------------------
    # Étape 2 : Node 1 - Connaît-on la provenance ?
    # -----------------------------------------------------------------------
    provenance_connue = bool(pays_production)

    if not provenance_connue:
        result.parcours.append(StepLog(
            node_id="node_1",
            question="Connaissez-vous l'endroit où l'intrant a été cultivé ou produit ?",
            answer="Non — provenance inconnue",
        ))

        # Node 2 : brut ou transformé ?
        if not is_transformed:
            result.parcours.append(StepLog(
                node_id="node_2",
                question="Quel est le niveau de transformation ?",
                answer="Intrant brut/non transformé",
            ))
            result.node_resultat = "node_4"
            result = _resolve_node_4(matiere_premiere, result)
        else:
            result.parcours.append(StepLog(
                node_id="node_2",
                question="Quel est le niveau de transformation ?",
                answer="Coproduit/intrant transformé",
            ))
            result.node_resultat = "node_5"
            result = _resolve_node_5(matiere_premiere, result)

    else:
        # Provenance connue
        result.parcours.append(StepLog(
            node_id="node_1",
            question="Connaissez-vous l'endroit où l'intrant a été cultivé ou produit ?",
            answer=f"Oui — Production: {pays_production}" + (f", Transformation: {pays_transformation}" if pays_transformation else ""),
        ))

        if not is_transformed:
            # Node 3 → Node 6 : où a-t-il été cultivé ?
            result.parcours.append(StepLog(
                node_id="node_3",
                question="Quel est le niveau de transformation ?",
                answer="Intrant brut/non transformé",
            ))

            if _is_france(pays_production):
                result.parcours.append(StepLog(
                    node_id="node_6",
                    question="Où l'intrant brut a-t-il été cultivé ?",
                    answer="En France",
                ))
                result.node_resultat = "node_8"
                result = _resolve_node_8(matiere_premiere, result)
            else:
                result.parcours.append(StepLog(
                    node_id="node_6",
                    question="Où l'intrant brut a-t-il été cultivé ?",
                    answer=f"Hors France — {pays_production}",
                ))
                result.node_resultat = "node_9"
                result = _resolve_node_9(matiere_premiere, pays_production, result)

        else:
            # Node 3 → Node 7 : où transformé + origine MP brute ?
            result.parcours.append(StepLog(
                node_id="node_3",
                question="Quel est le niveau de transformation ?",
                answer="Coproduit/intrant transformé",
            ))

            if _is_france(pays_transformation) and _is_france(pays_production):
                result.parcours.append(StepLog(
                    node_id="node_7",
                    question="Où l'intrant a-t-il été transformé et d'où provient la MP brute ?",
                    answer="Transformé en France à partir de MP brute française",
                ))
                result.node_resultat = "node_10"
                result = _resolve_node_10(matiere_premiere, result)

            elif _is_france(pays_transformation):
                result.parcours.append(StepLog(
                    node_id="node_7",
                    question="Où l'intrant a-t-il été transformé et d'où provient la MP brute ?",
                    answer=f"Transformé en France, MP brute de {pays_production or 'origine inconnue'}",
                ))
                result.node_resultat = "node_11"
                result = _resolve_node_11(matiere_premiere, result)

            else:
                result.parcours.append(StepLog(
                    node_id="node_7",
                    question="Où l'intrant a-t-il été transformé et d'où provient la MP brute ?",
                    answer=f"Transformé hors France — {pays_transformation}",
                ))
                result.node_resultat = "node_12"
                result = _resolve_node_12(matiere_premiere, pays_transformation or pays_production or "", result)

    # ------------------------------------------------------------------
    # Post-processing : normaliser les unités (t CO2 eq / t produit)
    # ------------------------------------------------------------------
    if result.impact_kg_co2_eq is not None and result.unite_source:
        if "tonne" in result.unite_source:
            # GFLI : kg CO2 eq / tonne -> t CO2 eq / t
            result.impact_tonne_co2_eq = result.impact_kg_co2_eq / 1000.0
        else:
            # EcoALIM : kg CO2 eq / kg -> t CO2 eq / t (même valeur numérique)
            result.impact_tonne_co2_eq = result.impact_kg_co2_eq

    # ------------------------------------------------------------------
    # Post-processing : collecter les candidats alternatifs
    # ------------------------------------------------------------------
    result = _collect_candidates(result)

    # Demander au LLM quel candidat est le plus pertinent en cas de doute
    if not result.match_exact and result.candidats_alternatifs:
        try:
            names = [c.get("nom", "") for c in result.candidats_alternatifs if c.get("nom")]
            rank = llm_service.rank_candidates(result.matiere_premiere, names)
            result.candidat_recommande = rank.get("best_name")
            result.candidats_reflexion = rank.get("reasoning")
        except Exception:
            result.candidat_recommande = None
            result.candidats_reflexion = None

    # Générer une justification LLM si le match n'est pas exact et qu'il n'y en a pas
    if not result.match_exact and not result.justification_alternative and not result.erreur:
        if result.intrant_utilise and result.impact_kg_co2_eq is not None:
            try:
                result.justification_alternative = llm_service.justify_alternative_value(
                    result.matiere_premiere,
                    result.intrant_utilise,
                    result.impact_kg_co2_eq,
                    result.source_db,
                )
            except Exception:
                result.justification_alternative = (
                    f"Valeur de '{result.intrant_utilise}' utilisée comme proxy pour "
                    f"'{result.matiere_premiere}' (matière la plus proche dans {result.source_db})."
                )

    return result


def _collect_candidates(result: CarbonResult) -> CarbonResult:
    """
    Après résolution, cherche les autres produits correspondants dans la même
    base de données pour proposer des alternatives triées par pertinence.
    """
    if result.erreur or result.intrant_utilise is None:
        return result

    matiere = result.matiere_premiere
    source = result.source_db or ""

    candidates: list[dict] = []

    # Déterminer le pays ISO pour GFLI
    country_iso = None
    if result.pays_production:
        country_iso = _get_country_iso(result.pays_production)
    if result.pays_transformation:
        country_iso = _get_country_iso(result.pays_transformation) or country_iso

    # Collecter depuis la source utilisée + l'autre source
    # D'abord la source principalement utilisée
    unbounded = not result.match_exact
    matiere_fr = llm_service.translate_matiere_to_french(matiere)
    matiere_en = llm_service.translate_matiere_to_english(matiere)
    if "ECOALIM" in source.upper():
        candidates.extend(data_loader.get_top_ecoalim_candidates(
            matiere,
            pays_production=result.pays_production,
            pays_transformation=result.pays_transformation,
            top_n=None if unbounded else 8,
        ))
        if matiere_fr.lower() != matiere.lower():
            candidates.extend(data_loader.get_top_ecoalim_candidates(
                matiere_fr,
                pays_production=result.pays_production,
                pays_transformation=result.pays_transformation,
                top_n=None if unbounded else 8,
            ))
        candidates.extend(data_loader.get_top_gfli_candidates(
            matiere, country_iso=country_iso, top_n=None if unbounded else 4,
        ))
        if matiere_en.lower() != matiere.lower():
            candidates.extend(data_loader.get_top_gfli_candidates(
                matiere_en, country_iso=country_iso, top_n=None if unbounded else 4,
            ))
    else:
        # Essayer aussi avec le nom traduit si on est sur GFLI
        # Le nom d'intrant utilisé contient le terme anglais
        intrant_base = result.intrant_utilise.split(",")[0].split("/")[0].strip()
        candidates.extend(data_loader.get_top_gfli_candidates(
            intrant_base, country_iso=country_iso, top_n=None if unbounded else 8,
        ))
        if matiere_en.lower() != matiere.lower():
            candidates.extend(data_loader.get_top_gfli_candidates(
                matiere_en, country_iso=country_iso, top_n=None if unbounded else 8,
            ))
        candidates.extend(data_loader.get_top_ecoalim_candidates(
            matiere,
            pays_production=result.pays_production,
            pays_transformation=result.pays_transformation,
            top_n=None if unbounded else 4,
        ))
        if matiere_fr.lower() != matiere.lower():
            candidates.extend(data_loader.get_top_ecoalim_candidates(
                matiere_fr,
                pays_production=result.pays_production,
                pays_transformation=result.pays_transformation,
                top_n=None if unbounded else 4,
            ))

    # Dédupliquer, exclure l'intrant sélectionné, et filtrer les faux positifs
    seen = set()
    unique_candidates = []
    intrant_base = ""
    if result.intrant_utilise:
        intrant_base = result.intrant_utilise.split(",")[0].split("/")[0].strip().lower()

    for c in candidates:
        key = (c["nom"], c["source"])
        if key in seen or c["nom"] == result.intrant_utilise:
            continue
        # Pour GFLI, vérifier que le candidat est pertinent
        if c["source"] == "GFLI" and not _is_name_match(matiere, c["nom"]):
            # Accepter quand même si ça matche le nom de base de l'intrant validé
            if intrant_base and _is_name_match(intrant_base, c["nom"]):
                pass  # OK, même famille de produit
            elif matiere_en and _is_name_match(matiere_en, c["nom"]):
                pass  # OK, match en anglais
            elif matiere_fr and _is_name_match(matiere_fr, c["nom"]):
                pass  # OK, match en français
            else:
                continue  # Faux positif
        seen.add(key)
        unique_candidates.append(c)

    result.candidats_alternatifs = unique_candidates
    return result