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
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
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
import asyncio
import json
import threading
from contextlib import asynccontextmanager
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any

from fastapi import FastAPI, File, HTTPException, Query, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

from api.auth import ApiKeyMiddleware, api_key_enabled
from api.data_pulse import (
    DataPulseMiddleware,
    build_pulse_snapshot,
    invalidate_pulse_meta_cache,
)
from api.lake_cache import get_lake_counts, invalidate_lake_counts
from config import settings
from ingest.fixtures.brasileirao import load_fixtures
from ingest.odds.the_odds_api import fetch_live_h2h_odds, merge_schedule_with_odds, save_odds_file
from ingest.meta import collection_stats
from models.corners_predictor import CornersPredictor
from models.ev_value import MatchValueReport, evaluate_match
from models.baseline import predict_baseline, predict_baseline_probs

if TYPE_CHECKING:
    from models.wc_predictor import WcPrediction, WcPredictor
from schemas.wc_kxl_dynamic import WcKxlMatchInput
from pipelines.gold import build_gold_for_match
from ingest.news_sync import sync_news_sources
from pipelines.news_feed import (
    build_news_all,
    build_news_cards,
    build_news_feed,
    resolve_news_teams,
)
from pipelines.silver import load_silver
from pipelines.wc_squads import get_squad_by_team, list_squad_teams, load_wc_squads
from pipelines.wc_schedule import build_schedule_response, load_wc_schedule, official_match_exists
from pipelines.wc_group_pressure import lookup_2026_group
from pipelines.wc_group_standings import build_group_standings
from schemas.national_teams import normalize_national_team
from schemas.user_bet import UserOpenBetRequest

WC_ROUND_FILE = Path("data/rounds/wc_2026.json")

_wc_models_ready = False
_wc_predictor: Any = None
_wc_artifact_meta: dict = {}
_wc_train_lock = threading.Lock()
_wc_train_thread: threading.Thread | None = None


def _wc_round_cache():
    from api import wc_round_cache

    return wc_round_cache


def _warm_sofascore_imports() -> None:
    """Carrega módulos Sofascore no thread principal (evita deadlock no thread pool)."""
    try:
        import ingest.sofascore.client  # noqa: F401
        import ingest.sofascore.fept_ingest  # noqa: F401
        import ingest.sofascore.stats_ingest  # noqa: F401
    except ImportError:
        pass


def _warm_wc_models() -> None:
    global _wc_models_ready
    _warm_sofascore_imports()
    try:
        CornersPredictor()
        get_wc_predictor()
        _wc_round_cache().warm_from_disk()
        _wc_models_ready = True
    except ValueError:
        _wc_models_ready = False


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Carrega modelos WC em background para a API aceitar tráfego imediatamente (deploy/health)."""
    loop = asyncio.get_event_loop()
    loop.run_in_executor(None, _warm_wc_models)
    yield


app = FastAPI(
    title="Bolão News API",
    description="API de contexto e previsão baseada em notícias esportivas",
    version="0.2.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=[
        "X-Data-Pulse-At",
        "X-Articles-Silver",
        "X-Fixtures",
        "X-WC-Models-Ready",
        "X-Collections-Last-Run",
        "X-Latest-Silver-At",
    ],
)

app.add_middleware(
    DataPulseMiddleware,
    wc_models_ready=lambda: _wc_models_ready,
)

app.add_middleware(ApiKeyMiddleware)


def _custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    from fastapi.openapi.utils import get_openapi

    schema = get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )
    if api_key_enabled():
        schema.setdefault("components", {})["securitySchemes"] = {
            "ApiKeyHeader": {
                "type": "apiKey",
                "in": "header",
                "name": "X-API-Key",
            },
            "BearerAuth": {
                "type": "http",
                "scheme": "bearer",
            },
        }
        schema["security"] = [{"ApiKeyHeader": []}, {"BearerAuth": []}]
    app.openapi_schema = schema
    return app.openapi_schema


app.openapi = _custom_openapi


def get_wc_predictor(*, force: bool = False) -> "WcPredictor":
    global _wc_predictor, _wc_artifact_meta
    from models.wc_artifact import load_or_train_wc_predictor

    if force or _wc_predictor is None:
        _wc_predictor, _wc_artifact_meta = load_or_train_wc_predictor(
            force=force or settings.wc_artifact_force_retrain,
            allow_train=force or settings.wc_artifact_force_retrain,
        )
    return _wc_predictor


def _get_wc_predictor() -> "WcPredictor":
    return get_wc_predictor()


class MatchRequest(BaseModel):
    home_team: str = Field(..., examples=["Flamengo"])
    away_team: str = Field(..., examples=["Palmeiras"])
    round_number: int = Field(1, ge=1)
    competition: str = Field("Brasileirão", examples=["Brasileirão"])
    season: int | None = None


class MatchContextResponse(BaseModel):
    match_id: str
    home_team: str
    away_team: str
    context_text: str
    news_count_home: int
    news_count_away: int
    injury_mentions_home: int
    injury_mentions_away: int
    sentiment_home: float | None
    sentiment_away: float | None
    home_position: int | None = None
    away_position: int | None = None
    home_form: str | None = None
    away_form: str | None = None
    prediction: str | None = None
    confidence: float | None = None
    reason: str | None = None
    model_source: str | None = None
    probabilities: dict[str, float] | None = None


class RoundPrediction(BaseModel):
    home_team: str
    away_team: str
    prediction: str
    confidence: float
    reason: str
    news_count: int


class RoundResponse(BaseModel):
    round_number: int
    competition: str
    predictions: list[RoundPrediction]


class WcValueRequest(BaseModel):
    schedule_file: str = Field("data/rounds/wc_2026.json", examples=["data/rounds/wc_2026.json"])
    output_odds_file: str = Field(
        "data/rounds/wc_2026_odds.json",
        examples=["data/rounds/wc_2026_odds.json"],
    )
    sport_key: str | None = Field(None, examples=["soccer_fifa_world_cup"])
    bookmaker: str | None = Field(None, examples=["bet365"])
    regions: str | None = Field(None, examples=["eu"])
    min_edge: float = Field(0.03, ge=0.0, le=1.0)
    save_odds_file: bool = True


class WcOutcomeValue(BaseModel):
    outcome: str
    odd: float
    model_prob: float
    implied_prob: float
    expected_value: float
    fair_odd: float
    kelly_quarter: float


class WcMatchValueResponse(BaseModel):
    home_team: str
    away_team: str
    best: WcOutcomeValue | None = None
    outcomes: list[WcOutcomeValue]


class WcValueResponse(BaseModel):
    matched_games: int
    total_schedule_games: int
    source: str
    captured_at: str | None = None
    edges: list[WcMatchValueResponse]


class WcCornersPredictRequest(BaseModel):
    home_team: str = Field(..., examples=["Brasil"])
    away_team: str = Field(..., examples=["Marrocos"])
    phase: str = Field("group", examples=["group"])


class WcCornerFactors(BaseModel):
    league_avg: float
    home_attack: float
    away_attack: float
    home_defense: float
    away_defense: float
    home_advantage: float
    elo_factor_home: float
    elo_factor_away: float
    lambda_home: float
    lambda_away: float
    training_matches: int
    blend_with_goal_proxy: float


class WcCornersPredictResponse(BaseModel):
    home_team: str
    away_team: str
    data_source: str
    expected_corners: str
    expected_total_corners: float
    most_likely_corners: str
    prob_home_more_corners: float
    prob_draw_corners: float
    prob_away_more_corners: float
    line_probs: dict[str, float]
    factors: WcCornerFactors
    training_summary: dict


class WcPredictRequest(BaseModel):
    home_team: str = Field(..., examples=["Brasil"])
    away_team: str = Field(..., examples=["Marrocos"])
    phase: str = Field("group", examples=["group"])
    match_date: str | None = Field(
        None,
        description="Data do confronto (ISO); usada em /simulate e busca Sofascore",
        examples=["2026-06-06"],
    )
    fifa_match_id: str | None = Field(
        None,
        description="IdMatch FIFA; evita busca na janela quando conhecido",
        examples=["400123456"],
    )
    sofascore_event_id: int | None = Field(
        None,
        description="ID do evento Sofascore; preenche FEPT automaticamente se kxl_match.fept ausente",
        examples=[11774480],
    )
    kxl_match: WcKxlMatchInput | None = Field(
        None,
        description="Entrada dinâmica KXL (FECL, FEJU, FEDE, FEPT, FEEM) — opcional",
    )


class WcInPlayRequest(BaseModel):
    home_team: str = Field(..., examples=["Brasil"])
    away_team: str = Field(..., examples=["Egito"])
    home_score: int = Field(..., ge=0, examples=[1])
    away_score: int = Field(..., ge=0, examples=[1])
    minute: int = Field(..., ge=0, le=120, description="Minuto de jogo (0–120)", examples=[17])
    phase: str = Field("group", examples=["group"])
    match_minutes: int = Field(90, ge=45, le=120, examples=[90])
    ht_home_score: int | None = Field(
        None,
        ge=0,
        description="Placar no intervalo (casa). Recomendado quando minute > 45.",
    )
    ht_away_score: int | None = Field(
        None,
        ge=0,
        description="Placar no intervalo (fora). Recomendado quando minute > 45.",
    )
    superbet_event_id: int | None = Field(
        None,
        description="ID Superbet: preenche placar/minuto ao vivo e benchmark de mercado",
        examples=[13247229],
    )
    merge_superbet_odds: bool = Field(
        False,
        description="Salva snapshot nas odds de mercado (superbet_odds.json) para treino",
    )


class WcInPlayResponse(BaseModel):
    home_team: str
    away_team: str
    current_score: str
    minute: int
    match_minutes: int
    remaining_fraction: float
    lambda_full_home: float
    lambda_full_away: float
    lambda_remaining_home: float
    lambda_remaining_away: float
    rho_used: float
    prob_final_home: float
    prob_final_draw: float
    prob_final_away: float
    prob_ht_home: float
    prob_ht_draw: float
    prob_ht_away: float
    prob_no_more_goals: float
    prob_next_goal_home: float
    prob_next_goal_away: float
    final_line_probs: dict[str, float]
    remainder_line_probs: dict[str, float]
    ht_line_probs: dict[str, float]
    second_half_line_probs: dict[str, float]
    team_final_line_probs: dict[str, float]
    top_final_scores: dict[str, float]
    top_ht_ft: dict[str, float]
    combo_markets: dict[str, float]
    btts_final: float
    n_simulations: int
    market_benchmark: dict | None = None
    superbet: dict | None = None


class UserBetRequest(BaseModel):
    market: str = Field(..., examples=["h2h"], description="h2h, over_2_5, btts, next_goal, combo_btts_over_3_5")
    outcome: str = Field(..., examples=["1"], description="1, X, 2, yes, no, home, away")
    stake: float = Field(..., gt=0, examples=[100])
    odds_placed: float = Field(..., gt=1, examples=[2.1])


class WcBetAdviceRequest(BaseModel):
    home_team: str = Field(..., examples=["Brasil"])
    away_team: str = Field(..., examples=["Egito"])
    superbet_event_id: int = Field(..., examples=[13247229])
    phase: str = Field("friendly", examples=["friendly"])
    bankroll: float = Field(1000, gt=0, examples=[1000])
    user_bet: UserBetRequest | None = None


class WcBetAdviceResponse(BaseModel):
    home_team: str
    away_team: str
    minute: int
    current_score: str | None
    cashout: dict | None
    aportes: list[dict]
    inplay_summary: dict
    superbet_event_id: int
    confidence: dict | None = None


class WcSuperbetLiveAdviceResponse(WcBetAdviceResponse):
    period_label: str | None = None
    status: str | None = None
    is_finished: bool = False
    is_live: bool = True
    h2h_odds: dict[str, float] = Field(default_factory=dict)
    h2h_implied: dict[str, float] = Field(default_factory=dict)
    h2h_overround: float | None = None
    generosity_probs: dict[str, float] = Field(default_factory=dict)
    market_benchmark: dict | None = None
    strategy: dict | None = None
    captured_at: str | None = None
    betradar_id: str | None = None
    raw_market_count: int = 0
    btts_odds: dict[str, float] = Field(default_factory=dict)
    next_goal_odds: dict[str, float] = Field(default_factory=dict)
    analysis_coverage: dict[str, bool | list[str]] | None = None


class WcSuperbetLiveEventResponse(BaseModel):
    event_id: int
    home_team: str
    away_team: str
    event_name: str
    sport_id: int
    tournament_id: int | None
    utc_date: str | None
    betradar_id: str | None
    minute: int
    home_score: int
    away_score: int
    period_label: str | None
    status: str | None
    market_count: int
    h2h_odds: dict[str, float]
    captured_at: str


class WcSuperbetLiveResponse(BaseModel):
    count: int
    sport_id: int | None
    events: list[WcSuperbetLiveEventResponse]
    captured_at: str


class WcSuperbetEventResponse(BaseModel):
    event_id: int
    home_team: str
    away_team: str
    event_name: str
    utc_date: str | None
    betradar_id: str | None
    is_live: bool
    inplay: dict | None
    h2h_odds: dict[str, float]
    h2h_implied: dict[str, float]
    totals_implied: dict[str, dict[str, float]]
    corners_implied: dict[str, dict[str, float]]
    combo_markets: dict[str, dict[str, float]]
    generosity_probs: dict[str, float]
    raw_market_count: int
    captured_at: str


class WcGoalFactors(BaseModel):
    league_avg: float
    home_attack: float
    away_attack: float
    home_defense: float
    away_defense: float
    home_advantage: float
    elo_factor_home: float
    elo_factor_away: float
    lambda_home: float
    lambda_away: float
    rho: float


class WcMonteCarloBreakdown(BaseModel):
    prob_home: float
    prob_draw: float
    prob_away: float
    expected_goals_home: float
    expected_goals_away: float
    over_2_5: float
    under_2_5: float
    both_teams_score: float
    clean_sheet_home: float
    clean_sheet_away: float
    top_scores: dict[str, float]
    n_simulations: int
    rho_used: float


class WcModelBreakdown(BaseModel):
    dixon_coles: dict[str, float]
    logistic: dict[str, float]
    dixon_coles_rho: float | None = None
    poisson_factors: WcGoalFactors | None = None
    holdout_2022_accuracy: float | None = None
    ensemble_weights: dict[str, float]
    ensemble_brier: float | None = None
    kxl_baseline: dict | None = None
    kxl_collision: dict | None = None
    kxl_dynamic: dict | None = None
    kxl_fept: dict | None = None
    monte_carlo: WcMonteCarloBreakdown | None = None


class WcPredictionResponse(BaseModel):
    home_team: str
    away_team: str
    prediction: str
    confidence: float
    prob_home: float
    prob_draw: float
    prob_away: float
    poisson_score: str
    expected_goals: str
    context: str
    h2h_summary: str
    model_breakdown: WcModelBreakdown


class WcSimulationScore(BaseModel):
    score: str
    prob: float


class WcSimulationScenario(BaseModel):
    name: str
    description: str
    prob: float


class WcSimulationResponse(BaseModel):
    home_team: str
    away_team: str
    match_date: str | None
    prediction: str
    confidence: float
    prob_home: float
    prob_draw: float
    prob_away: float
    poisson_score: str | None = None
    expected_goals: str | None = None

    # Dados reais da FIFA
    fifa_home_lineup: list[dict[str, Any]] | None = None
    fifa_away_lineup: list[dict[str, Any]] | None = None
    fifa_home_bench: list[dict[str, Any]] | None = None
    fifa_away_bench: list[dict[str, Any]] | None = None
    fifa_home_goals: list[dict[str, Any]] | None = None
    fifa_away_goals: list[dict[str, Any]] | None = None
    fifa_home_tactics: str | None = None
    fifa_away_tactics: str | None = None
    fifa_home_coach: str | None = None
    fifa_away_coach: str | None = None
    fifa_stadium: str | None = None
    fifa_attendance: int | None = None
    fifa_home_points: float | None = None
    fifa_away_points: float | None = None
    fifa_points_diff: float | None = None
    lineup_source: str | None = Field(
        None,
        description="Origem das escalações exibidas: fifa ou sofascore",
    )

    # Dados enriquecidos
    enrich_features: dict[str, Any] | None = None
    stats_features: dict[str, Any] | None = None
    model_breakdown: dict[str, Any]
    warnings: list[str]


class WcRoundResponse(BaseModel):
    season: int
    competition: str
    phase: str
    round: int
    predictions: list[WcPredictionResponse]


class WcGroupStandingRow(BaseModel):
    position: int
    team: str
    played: int
    won: int
    drawn: int
    lost: int
    gf: int
    ga: int
    gd: int
    points: int


class WcGroupStandingsBlock(BaseModel):
    group: str
    standings: list[WcGroupStandingRow]


class WcGroupStandingsResponse(BaseModel):
    season: int
    competition: str
    simulated: bool = True
    note: str
    groups: list[WcGroupStandingsBlock]


class WcTeamsResponse(BaseModel):
    teams: list[str]
    count: int


class WcFriendlyItem(BaseModel):
    event_id: int | None = None
    fifa_match_id: str | None = None
    sources: list[str] = Field(default_factory=lambda: ["sofascore"])
    home_team: str
    away_team: str
    match_date: str | None = None
    status: str
    home_score: int | None = None
    away_score: int | None = None
    tournament: str
    is_home: bool


class WcFriendliesResponse(BaseModel):
    team: str
    year: int
    count: int
    friendlies: list[WcFriendlyItem]
    source: str = "sofascore+fifa"


class WcScheduleGroup(BaseModel):
    id: str
    teams: list[str]


class WcScheduleMatchItem(BaseModel):
    match_id: str
    home_team: str
    away_team: str
    group: str | None = None
    round: int
    phase: str
    kickoff: str | None = None
    venue: str | None = None
    city: str | None = None


class WcScheduleResponse(BaseModel):
    season: int
    competition: str
    phase: str
    groups: list[WcScheduleGroup]
    matchdays: list[int]
    matches: list[WcScheduleMatchItem]
    total_matches: int


class WcSquadPlayerItem(BaseModel):
    name: str
    club: str | None = None


class WcSquadSectionItem(BaseModel):
    role: str
    position: str
    players: list[WcSquadPlayerItem]


class WcSquadTeamItem(BaseModel):
    team: str
    player_count: int
    sections: list[WcSquadSectionItem]


class WcSquadTeamsResponse(BaseModel):
    season: int
    competition: str
    source_url: str
    updated_at: str
    team_count: int
    teams: list[dict]


class WcSquadDetailResponse(BaseModel):
    season: int
    competition: str
    source_url: str
    updated_at: str
    squad: WcSquadTeamItem


class WcEditionItem(BaseModel):
    season: int
    label: str
    match_count: int


class WcEditionsResponse(BaseModel):
    editions: list[WcEditionItem]


class WcHistoricalMatchItem(BaseModel):
    match_id: str
    season: int
    home_team: str
    away_team: str
    match_date: str
    phase: str
    phase_label: str
    group_name: str | None = None
    home_score: int
    away_score: int
    result: str
    result_label: str
    score: str


class WcEditionMatchesResponse(BaseModel):
    season: int
    matches: list[WcHistoricalMatchItem]


class WcValidateRequest(BaseModel):
    season: int = Field(..., ge=1930, le=2022)
    match_id: str | None = None
    home_team: str | None = None
    away_team: str | None = None


class WcValidateMatchInfo(BaseModel):
    match_id: str
    season: int
    home_team: str
    away_team: str
    match_date: str
    phase: str
    phase_label: str
    group_name: str | None = None
    home_score: int
    away_score: int
    actual_result: str
    actual_result_label: str
    actual_score: str


class NewsArticleItem(BaseModel):
    id: str
    source: str
    source_name: str
    source_url: str
    title: str
    summary: str | None = None
    body_preview: str
    published_at: str | None = None
    scraped_at: str | None = None
    teams_mentioned: list[str] = Field(default_factory=list)
    national_teams_mentioned: list[str] = Field(default_factory=list)
    categories: list[str] = Field(default_factory=list)
    sentiment_score: float | None = None
    sentiment_label: str


class NewsSourceItem(BaseModel):
    id: str
    name: str
    count: int


class NewsFeedResponse(BaseModel):
    total: int
    limit: int
    offset: int
    sources: list[NewsSourceItem]
    articles: list[NewsArticleItem]


class NewsCardsResponse(BaseModel):
    """Notícias formatadas para NewsArticleCard no frontend."""

    total: int
    limit: int
    offset: int
    teams: list[str] = Field(default_factory=list)
    cards: list[NewsArticleItem]


class NewsSyncResponse(BaseModel):
    collected: int
    by_source: dict[str, int]
    silver_updated: bool
    silver_path: str | None = None
    articles_silver: int
    synced_at: str


class WcValidateResponse(BaseModel):
    match: WcValidateMatchInfo
    prediction: str
    confidence: float
    prob_home: float
    prob_draw: float
    prob_away: float
    poisson_score: str
    expected_goals: str
    correct: bool
    context: str
    h2h_summary: str
    model_breakdown: WcModelBreakdown
    cutoff_date: str
    cutoff_note: str


def _context_to_response(context, include_prediction: bool = False) -> MatchContextResponse:
    resp = MatchContextResponse(
        match_id=context.match_id,
        home_team=context.home_team,
        away_team=context.away_team,
        context_text=context.context_text,
        news_count_home=context.features.news_count_home,
        news_count_away=context.features.news_count_away,
        injury_mentions_home=context.features.injury_mentions_home,
        injury_mentions_away=context.features.injury_mentions_away,
        sentiment_home=context.features.sentiment_home,
        sentiment_away=context.features.sentiment_away,
        home_position=context.features.home_position,
        away_position=context.features.away_position,
        home_form=context.features.home_form,
        away_form=context.features.away_form,
    )
    if include_prediction:
        pred, conf, reason = predict_baseline(context.features)
        resp.prediction = pred
        resp.confidence = conf
        resp.reason = reason
        resp.model_source = "baseline"
        resp.probabilities = predict_baseline_probs(context.features)
    return resp


def _breakdown_to_response(breakdown: dict) -> WcModelBreakdown:
    pf = breakdown.get("poisson_factors")
    mc = breakdown.get("monte_carlo")
    return WcModelBreakdown(
        dixon_coles=breakdown["dixon_coles"],
        logistic=breakdown["logistic"],
        dixon_coles_rho=breakdown.get("dixon_coles_rho"),
        poisson_factors=WcGoalFactors(**pf) if pf else None,
        holdout_2022_accuracy=breakdown.get("holdout_2022_accuracy"),
        ensemble_weights=breakdown["ensemble_weights"],
        ensemble_brier=breakdown.get("ensemble_brier"),
        kxl_baseline=breakdown.get("kxl_baseline"),
        kxl_collision=breakdown.get("kxl_collision"),
        kxl_dynamic=breakdown.get("kxl_dynamic"),
        kxl_fept=breakdown.get("kxl_fept"),
        monte_carlo=WcMonteCarloBreakdown(**mc) if mc else None,
    )


def _wc_prediction_to_response(pred: "WcPrediction") -> WcPredictionResponse:
    breakdown = pred.model_breakdown
    return WcPredictionResponse(
        home_team=pred.home_team,
        away_team=pred.away_team,
        prediction=pred.prediction,
        confidence=round(pred.confidence, 4),
        prob_home=round(pred.prob_home, 4),
        prob_draw=round(pred.prob_draw, 4),
        prob_away=round(pred.prob_away, 4),
        poisson_score=pred.poisson_score,
        expected_goals=pred.expected_goals,
        context=pred.context,
        h2h_summary=pred.h2h_summary,
        model_breakdown=_breakdown_to_response(breakdown),
    )


def _load_wc_round(path: Path = WC_ROUND_FILE) -> dict:
    if not path.exists():
        raise HTTPException(status_code=404, detail=f"Rodada WC não encontrada: {path}")
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        raise HTTPException(status_code=400, detail=f"Falha ao ler rodada WC: {exc}") from exc


def _match_value_to_response(report: MatchValueReport) -> WcMatchValueResponse:
    best = None
    if report.best:
        best = WcOutcomeValue(
            outcome=report.best.outcome,
            odd=report.best.odd,
            model_prob=report.best.model_prob,
            implied_prob=report.best.implied_prob,
            expected_value=report.best.expected_value,
            fair_odd=report.best.fair_odd,
            kelly_quarter=report.best.kelly_quarter,
        )
    outcomes = [
        WcOutcomeValue(
            outcome=item.outcome,
            odd=item.odd,
            model_prob=item.model_prob,
            implied_prob=item.implied_prob,
            expected_value=item.expected_value,
            fair_odd=item.fair_odd,
            kelly_quarter=item.kelly_quarter,
        )
        for item in report.outcomes
    ]
    return WcMatchValueResponse(
        home_team=report.home_team,
        away_team=report.away_team,
        best=best,
        outcomes=outcomes,
    )


def _sanitize_match_item(data: dict) -> dict:
    import math

    out = dict(data)
    group = out.get("group_name")
    if group is None or (isinstance(group, float) and math.isnan(group)):
        out["group_name"] = None
    else:
        out["group_name"] = str(group)
    return out


@app.get("/health/live")
def health_live():
    """Liveness para o proxy Fly — sem I/O no lake (sobe antes do warm de modelos)."""
    return {"status": "ok"}


@app.get("/health")
async def health():
    stats = collection_stats()
    articles_silver, fixtures = await asyncio.to_thread(get_lake_counts)
    return {
        "status": "ok",
        "lake_root": str(settings.lake_root),
        "articles_silver": articles_silver,
        "fixtures": fixtures,
        "collections": stats,
        "wc_models_ready": _wc_models_ready,
        "wc_artifact": _wc_artifact_meta if _wc_models_ready else None,
    }


@app.get("/data/pulse")
async def data_pulse():
    """Heartbeat do datalake (GET) — mesmo snapshot anexado via headers em cada requisição."""
    return await asyncio.to_thread(
        build_pulse_snapshot,
        wc_models_ready=_wc_models_ready,
        force_lake_counts=True,
    )


@app.get("/")
def root():
    return {
        "name": "api-noticia",
        "status": "running",
        "auth_required": api_key_enabled(),
        "docs": "/docs",
        "health": "/health",
        "data_pulse": "/data/pulse",
        "endpoints": [
            "/data/pulse",
            "/news/feed",
            "/news/cards",
            "/news/all",
            "/news/sync",
            "/context",
            "/predict",
            "/round/predict",
            "/worldcup/predict",
            "/worldcup/inplay",
            "/worldcup/superbet/live",
            "/worldcup/superbet/live/{event_id}/advice",
            "/worldcup/superbet/events/{event_id}",
            "/worldcup/bet/advice",
            "/worldcup/round",
            "/worldcup/schedule",
            "/worldcup/squads",
            "/worldcup/squads/{team}",
            "/worldcup/teams",
            "/worldcup/friendlies",
            "/worldcup/value/live",
            "/worldcup/editions",
            "/worldcup/editions/{season}/matches",
            "/worldcup/validate",
            "/worldcup/walkforward",
            "/worldcup/retrain",
            "/worldcup/group-standings",
        ],
    }


@app.post("/news/sync", response_model=NewsSyncResponse)
async def news_sync(
    full_rebuild: bool = Query(
        False,
        description="Reprocessa todo o bronze no silver (use após purge-news)",
    ),
    fetch_body: bool | None = Query(
        None,
        description="Baixa o HTML de cada URL (texto completo no body_preview; bem mais lento)",
    ),
):
    try:
        do_fetch = (
            settings.news_sync_fetch_body if fetch_body is None else fetch_body
        )
        result = await sync_news_sources(
            fetch_body=do_fetch,
            run_silver=True,
            full_silver_rebuild=full_rebuild,
        )
    except Exception as exc:
        raise HTTPException(status_code=502, detail=f"Falha ao sincronizar fontes: {exc}") from exc
    invalidate_lake_counts()
    invalidate_pulse_meta_cache()
    return NewsSyncResponse(**result)


@app.get("/news/feed", response_model=NewsFeedResponse)
async def news_feed(
    limit: int = 24,
    offset: int = 0,
    source: str | None = None,
    q: str | None = None,
    days: int | None = 30,
):
    limit = min(max(limit, 1), 100)
    offset = max(offset, 0)
    if days is not None:
        days = min(max(days, 1), 365)

    silver_df = await asyncio.to_thread(load_silver)
    payload = await asyncio.to_thread(
        build_news_feed,
        silver_df,
        limit=limit,
        offset=offset,
        source=source,
        query=q,
        days=days,
    )
    return NewsFeedResponse(
        total=payload["total"],
        limit=payload["limit"],
        offset=payload["offset"],
        sources=[NewsSourceItem(**s) for s in payload["sources"]],
        articles=[NewsArticleItem(**a) for a in payload["articles"]],
    )


@app.get("/news/all", response_model=NewsFeedResponse)
async def news_all(
    offset: int = 0,
    source: str | None = None,
    q: str | None = None,
    days: int | None = Query(
        None,
        description="Janela em dias; omita para trazer todo o histórico no lake",
    ),
    team: str | None = None,
    home_team: str | None = None,
    away_team: str | None = None,
    teams: str | None = Query(None, description="Brasil,Marrocos"),
):
    offset = max(offset, 0)
    if days is not None:
        days = min(max(days, 1), 3650)

    team_list: list[str] | None = None
    if teams:
        team_list = [t.strip() for t in teams.split(",") if t.strip()]

    resolved_teams = None
    if team_list or team or home_team or away_team:
        resolved_teams = resolve_news_teams(
            team=normalize_national_team(team) if team else None,
            home_team=normalize_national_team(home_team) if home_team else None,
            away_team=normalize_national_team(away_team) if away_team else None,
            teams=team_list,
        )

    silver_df = await asyncio.to_thread(load_silver)
    payload = await asyncio.to_thread(
        build_news_all,
        silver_df,
        offset=offset,
        source=source,
        query=q,
        days=days,
        teams=resolved_teams,
    )
    return NewsFeedResponse(
        total=payload["total"],
        limit=len(payload["articles"]),
        offset=payload["offset"],
        sources=[NewsSourceItem(**s) for s in payload["sources"]],
        articles=[NewsArticleItem(**a) for a in payload["articles"]],
    )


@app.get("/news/cards", response_model=NewsCardsResponse)
async def news_cards(
    limit: int = 12,
    offset: int = 0,
    source: str | None = None,
    q: str | None = None,
    days: int | None = 14,
    team: str | None = Query(None, description="Filtrar por um time/seleção"),
    home_team: str | None = Query(None, description="Mandante (usa com away_team)"),
    away_team: str | None = Query(None, description="Visitante"),
    teams: str | None = Query(
        None,
        description="Lista separada por vírgula, ex: Brasil,Marrocos",
    ),
):
    limit = min(max(limit, 1), 48)
    offset = max(offset, 0)
    if days is not None:
        days = min(max(days, 1), 90)

    team_list: list[str] | None = None
    if teams:
        team_list = [t.strip() for t in teams.split(",") if t.strip()]

    home = normalize_national_team(home_team) if home_team else None
    away = normalize_national_team(away_team) if away_team else None
    single = normalize_national_team(team) if team else None

    silver_df = await asyncio.to_thread(load_silver)
    payload = await asyncio.to_thread(
        build_news_cards,
        silver_df,
        limit=limit,
        offset=offset,
        source=source,
        query=q,
        days=days,
        team=single,
        home_team=home,
        away_team=away,
        teams=team_list,
    )
    return NewsCardsResponse(
        total=payload["total"],
        limit=payload["limit"],
        offset=payload["offset"],
        teams=payload["teams"],
        cards=[NewsArticleItem(**c) for c in payload["cards"]],
    )


@app.post("/context", response_model=MatchContextResponse)
def get_match_context(req: MatchRequest):
    silver_df = load_silver()
    fixtures_df = load_fixtures()

    match_id = f"{req.home_team}_{req.away_team}_{req.round_number}".lower().replace(" ", "_")
    context = build_gold_for_match(
        match_id=match_id,
        home_team=req.home_team,
        away_team=req.away_team,
        round_number=req.round_number,
        competition=req.competition,
        match_date=datetime.now(timezone.utc),
        silver_df=silver_df,
        season=req.season,
        fixtures_df=fixtures_df if not fixtures_df.empty else None,
        live_mode=True,
    )
    return _context_to_response(context)


@app.post("/predict", response_model=MatchContextResponse)
def predict_match(req: MatchRequest):
    resp = get_match_context(req)
    context = build_gold_for_match(
        match_id=resp.match_id,
        home_team=resp.home_team,
        away_team=resp.away_team,
        round_number=req.round_number,
        competition=req.competition,
        match_date=datetime.now(timezone.utc),
        silver_df=load_silver(),
        season=req.season,
        fixtures_df=load_fixtures(),
        live_mode=True,
    )
    pred, conf, reason = predict_baseline(context.features)
    resp.prediction = pred
    resp.confidence = conf
    resp.reason = reason
    resp.model_source = "baseline"
    resp.probabilities = predict_baseline_probs(context.features)
    return resp


@app.get("/round/predict", response_model=RoundResponse)
def predict_current_round():
    from pipelines.current_round import load_round_schedule, predict_round

    try:
        schedule = load_round_schedule()
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc

    results = predict_round(save=False)
    return RoundResponse(
        round_number=schedule["round"],
        competition=schedule.get("competition", "Brasileirão"),
        predictions=[
            RoundPrediction(
                home_team=r["home_team"],
                away_team=r["away_team"],
                prediction=r["prediction"],
                confidence=r["confidence"],
                reason=r["reason"],
                news_count=r["news_count"],
            )
            for r in results
        ],
    )


class WcSofascoreResolveResponse(BaseModel):
    event_id: int
    home_team: str
    away_team: str
    match_date: str
    sofascore_home: str | None = None
    sofascore_away: str | None = None


class WcSofascoreStatsResponse(BaseModel):
    event_id: int
    home_team: str
    away_team: str
    match_date: str | None = None
    stats: dict[str, float | int | str | None]
    fetched_at: str
    source: str = "sofascore"
    cached: bool = False


@app.get("/worldcup/sofascore/resolve", response_model=WcSofascoreResolveResponse)
def worldcup_sofascore_resolve(
    home_team: str = Query(...),
    away_team: str = Query(...),
    date: str = Query(..., description="Data do jogo (YYYY-MM-DD)"),
):
    from datetime import date as date_type

    from ingest.sofascore.client import SofascoreClient, SofascoreClientError
    from ingest.sofascore.event_helpers import find_event_id
    from ingest.sofascore.teams import event_team_names

    home = normalize_national_team(home_team)
    away = normalize_national_team(away_team)
    try:
        match_date = date_type.fromisoformat(date)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail="Data inválida; use YYYY-MM-DD") from exc

    try:
        client = SofascoreClient()
        event = find_event_id(
            client,
            home_team=home,
            away_team=away,
            match_date=match_date,
        )
    except LookupError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except SofascoreClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    event_home, event_away = event_team_names(event)
    return WcSofascoreResolveResponse(
        event_id=int(event["id"]),
        home_team=home,
        away_team=away,
        match_date=match_date.isoformat(),
        sofascore_home=event_home or None,
        sofascore_away=event_away or None,
    )


@app.get(
    "/worldcup/sofascore/{event_id}/statistics",
    response_model=WcSofascoreStatsResponse,
)
def worldcup_sofascore_statistics(
    event_id: int,
    refresh: bool = Query(False, description="Força nova coleta no Sofascore"),
):
    from datetime import datetime, timezone

    from ingest.sofascore.client import SofascoreClientError
    from ingest.sofascore.stats_ingest import ingest_match_stats, load_match_stats

    if not refresh:
        cached = load_match_stats(event_id)
        if cached:
            fetched_at = cached.get("fetched_at")
            if not isinstance(fetched_at, str):
                fetched_at = datetime.now(timezone.utc).isoformat()
            stats = {
                k: v
                for k, v in cached.items()
                if k
                not in (
                    "event_id",
                    "home_team",
                    "away_team",
                    "match_date",
                    "source",
                    "fetched_at",
                )
            }
            return WcSofascoreStatsResponse(
                event_id=int(cached["event_id"]),
                home_team=str(cached["home_team"]),
                away_team=str(cached["away_team"]),
                match_date=cached.get("match_date"),
                stats=stats,
                fetched_at=fetched_at,
                cached=True,
            )

    try:
        result = ingest_match_stats(event_id=event_id, save=True)
    except LookupError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except SofascoreClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    payload = result.to_payload()
    stats = {
        k: v
        for k, v in payload.items()
        if k
        not in (
            "event_id",
            "home_team",
            "away_team",
            "match_date",
            "source",
            "fetched_at",
        )
    }
    return WcSofascoreStatsResponse(
        event_id=result.event_id,
        home_team=result.home_team,
        away_team=result.away_team,
        match_date=result.match_date,
        stats=stats,
        fetched_at=str(payload["fetched_at"]),
        cached=False,
    )


@app.post("/worldcup/corners/predict", response_model=WcCornersPredictResponse)
def worldcup_corners_predict(req: WcCornersPredictRequest):
    home = normalize_national_team(req.home_team)
    away = normalize_national_team(req.away_team)
    if req.phase == "group" and not official_match_exists(home, away, phase="group"):
        raise HTTPException(
            status_code=400,
            detail=f"Confronto {home} x {away} não consta na tabela oficial da fase de grupos.",
        )

    result = CornersPredictor().predict(home, away, phase=req.phase)
    pred = result.prediction
    factors = result.factors.as_dict()
    return WcCornersPredictResponse(
        home_team=result.home_team,
        away_team=result.away_team,
        data_source=result.data_source,
        expected_corners=f"{pred.expected_home_corners:.1f}x{pred.expected_away_corners:.1f}",
        expected_total_corners=round(pred.expected_total_corners, 2),
        most_likely_corners=pred.most_likely_score,
        prob_home_more_corners=round(pred.prob_home_more, 4),
        prob_draw_corners=round(pred.prob_draw_corners, 4),
        prob_away_more_corners=round(pred.prob_away_more, 4),
        line_probs={k: round(v, 4) for k, v in pred.line_probs.items()},
        factors=WcCornerFactors(**factors),
        training_summary=result.training_summary,
    )


@app.get("/worldcup/superbet/live", response_model=WcSuperbetLiveResponse)
def worldcup_superbet_live(
    sport_id: int = Query(5, description="Filtra por esporte (5=futebol)."),
    all_sports: bool = Query(False, description="Ignora sport_id e retorna todos os esportes."),
):
    """Lista jogos ao vivo na Superbet (feed /live)."""
    from datetime import datetime, timezone

    from ingest.superbet.client import SuperbetClient, SuperbetClientError

    filter_sport = None if all_sports else sport_id
    try:
        events = SuperbetClient().fetch_live_events(sport_id=filter_sport)
    except SuperbetClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    captured_at = datetime.now(timezone.utc).isoformat()
    return WcSuperbetLiveResponse(
        count=len(events),
        sport_id=filter_sport,
        events=[WcSuperbetLiveEventResponse(**event.to_dict()) for event in events],
        captured_at=captured_at,
    )


@app.get("/worldcup/superbet/live/{event_id}/advice", response_model=WcSuperbetLiveAdviceResponse)
def worldcup_superbet_live_advice(
    event_id: int,
    phase: str = Query("friendly", description="Fase do modelo (friendly para amistosos)"),
    bankroll: float = Query(1000, gt=0),
    market: str | None = Query(None, description="Mercado da aposta ativa (h2h, over_2_5, btts, next_goal)"),
    outcome: str | None = Query(None, description="Palpite da aposta (1, X, 2, yes, home, away)"),
    stake: float | None = Query(None, gt=0),
    odds_placed: float | None = Query(None, gt=1),
):
    """Captura evento Superbet ao vivo, roda modelo e retorna cash-out / aportes."""
    from ingest.superbet.advice import run_live_advice
    from ingest.superbet.client import SuperbetClientError
    from models.wc_bet_advice import UserBetInput

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    user_bet = None
    if market and outcome and stake is not None and odds_placed is not None:
        user_bet = UserBetInput(
            market=market,
            outcome=outcome,
            stake=stake,
            odds_placed=odds_placed,
        )

    try:
        payload = run_live_advice(
            event_id,
            predictor,
            phase=phase,
            bankroll=bankroll,
            user_bet=user_bet,
        )
    except SuperbetClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    return WcSuperbetLiveAdviceResponse(**payload)


@app.get("/worldcup/superbet/events/{event_id}", response_model=WcSuperbetEventResponse)
def worldcup_superbet_event(
    event_id: int,
    merge_odds: bool = False,
    save_bronze: bool = True,
):
    """Snapshot Superbet: estado ao vivo, odds e probabilidades implícitas."""
    from ingest.superbet.client import SuperbetClient, SuperbetClientError
    from ingest.superbet.store import merge_snapshot_into_odds_file, save_event_snapshot

    try:
        snapshot = SuperbetClient().fetch_event(event_id)
    except SuperbetClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    if save_bronze:
        save_event_snapshot(snapshot)
    if merge_odds and snapshot.h2h_odds:
        merge_snapshot_into_odds_file(snapshot)
        from pipelines.wc_market_features import load_match_odds_index

        load_match_odds_index.cache_clear()

    return WcSuperbetEventResponse(**snapshot.to_dict())


@app.post("/worldcup/bet/advice", response_model=WcBetAdviceResponse)
def worldcup_bet_advice(req: WcBetAdviceRequest):
    """Captura jogo ao vivo (Superbet), roda modelo e recomenda cash-out / aporte."""
    from ingest.superbet.advice import run_live_advice
    from ingest.superbet.client import SuperbetClientError
    from models.wc_bet_advice import UserBetInput

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    user_bet = None
    if req.user_bet is not None:
        user_bet = UserBetInput(
            market=req.user_bet.market,
            outcome=req.user_bet.outcome,
            stake=req.user_bet.stake,
            odds_placed=req.user_bet.odds_placed,
        )

    try:
        payload = run_live_advice(
            req.superbet_event_id,
            predictor,
            phase=req.phase,
            bankroll=req.bankroll,
            user_bet=user_bet,
        )
    except SuperbetClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    return WcBetAdviceResponse(
        home_team=payload["home_team"],
        away_team=payload["away_team"],
        minute=payload["minute"],
        current_score=payload.get("current_score"),
        cashout=payload.get("cashout"),
        aportes=payload.get("aportes", []),
        inplay_summary=payload.get("inplay_summary", {}),
        superbet_event_id=req.superbet_event_id,
    )


@app.post("/user/open-bets", response_model=dict)
def register_open_bet(req: UserOpenBetRequest):
    """Recebe apostas abertas capturadas da Superbet (extensão ou script)."""
    import uuid

    from api.user_bets_store import add_open_bet

    bet_id = req.id or str(uuid.uuid4())
    pick_dicts = [p.model_dump() for p in req.picks]
    ub = add_open_bet(
        {
            "id": bet_id,
            "superbet_event_id": req.superbet_event_id,
            "event_name": req.event_name,
            "home_team": req.home_team,
            "away_team": req.away_team,
            "picks": pick_dicts,
            "stake": req.stake,
            "odds_placed": req.odds_placed,
            "potential_return": req.potential_return,
            "cashout_value": req.cashout_value,
            "ticket_code": req.ticket_code,
            "status": "open",
            "source": req.source,
            "captured_at": req.captured_at or __import__("datetime", fromlist=["datetime"]).datetime.now().isoformat(),
        }
    )
    return {
        "id": ub.id,
        "message": "Aposta cadastrada com sucesso",
        "event_name": ub.event_name,
        "picks_count": len(ub.picks),
        "stake": ub.stake,
        "odds_placed": ub.odds_placed,
    }


@app.get("/user/open-bets", response_model=dict)
def list_user_open_bets():
    """Lista apostas abertas do usuário."""
    from api.user_bets_store import list_open_bets

    bets = list_open_bets()
    return {
        "count": len(bets),
        "bets": [
            {
                "id": b.id,
                "event_name": b.event_name,
                "home_team": b.home_team,
                "away_team": b.away_team,
                "picks": [p.model_dump() if hasattr(p, "model_dump") else dict(p) for p in b.picks],
                "stake": b.stake,
                "odds_placed": b.odds_placed,
                "potential_return": b.potential_return,
                "cashout_value": b.cashout_value,
                "ticket_code": b.ticket_code,
                "status": b.status,
                "source": b.source,
                "captured_at": b.captured_at,
            }
            for b in bets
        ],
    }


# ---------------------------------------------------------------------------
# Fase 4 — Carteira & Reconciliação (CSV Superbet)
# ---------------------------------------------------------------------------


@app.post("/user/transactions/upload", response_model=dict)
async def upload_user_transactions(
    user_id: str = Query("default", description="ID do usuário dono do CSV"),
    file: UploadFile = File(...),
):
    """Recebe CSV de transações da Superbet e persiste no bronze do datalake."""
    import uuid as _uuid

    from ingest.user_transactions.parser import parse_user_csv
    from ingest.user_transactions.store import save_transactions_bronze

    if not file.filename or not file.filename.lower().endswith(".csv"):
        raise HTTPException(status_code=400, detail="Arquivo deve ser .csv")

    content = await file.read()
    if len(content) > 10 * 1024 * 1024:  # 10 MB
        raise HTTPException(status_code=413, detail="CSV maior que 10MB")

    upload_id = str(_uuid.uuid4())
    rows = parse_user_csv(content, user_id, upload_id)
    if not rows:
        raise HTTPException(status_code=422, detail="Nenhuma linha válida no CSV")

    out_path = save_transactions_bronze(rows, user_id, upload_id)

    n_inplay_placed = sum(1 for r in rows if r.is_inplay_bet and r.is_bet_placed)
    n_wins = sum(1 for r in rows if r.is_win)
    total_staked = sum(r.amount for r in rows if r.is_bet_placed)
    total_won = sum(r.amount for r in rows if r.is_win)

    return {
        "upload_id": upload_id,
        "user_id": user_id,
        "n_rows": len(rows),
        "n_inplay_bets_placed": n_inplay_placed,
        "n_wins": n_wins,
        "total_staked": round(total_staked, 2),
        "total_won": round(total_won, 2),
        "pnl": round(total_won - total_staked, 2),
        "file_path": str(out_path),
        "message": "ok",
    }


@app.get("/user/transactions/summary", response_model=dict)
def get_user_wallet_summary(user_id: str = Query("default")):
    """KPIs agregados da carteira do usuário."""
    from pipelines.user_bet_analytics import compute_wallet_summary
    return compute_wallet_summary(user_id)


@app.post("/user/transactions/reconcile", response_model=dict)
def reconcile_user_bets(user_id: str = Query("default")):
    """Reconcilia transações com snapshots de eventos. Persiste silver."""
    from pipelines.user_bet_reconciliation import (
        reconcile_user_transactions,
        save_reconciliation,
    )

    df = reconcile_user_transactions(user_id)
    if df.empty:
        return {"status": "empty", "n_pairs": 0}

    path = save_reconciliation(df, user_id)
    n_matched = int((df["match_confidence"].fillna(0) >= 0.5).sum())
    return {
        "status": "ok",
        "n_pairs": len(df),
        "n_matched_high_confidence": n_matched,
        "match_rate": round(n_matched / len(df), 3),
        "file_path": str(path),
    }


@app.get("/user/transactions/reconciliation", response_model=dict)
def get_user_reconciliation(
    user_id: str = Query("default"),
    limit: int = Query(50, ge=1, le=500),
    offset: int = Query(0, ge=0),
):
    """Tabela paginada da reconciliação aposta-modelo."""
    from pipelines.user_bet_analytics import compute_reconciliation_table
    return compute_reconciliation_table(user_id, limit=limit, offset=offset)


@app.get("/user/transactions/model-errors", response_model=dict)
def get_user_model_errors(user_id: str = Query("default")):
    """Heatmap de erros do modelo por bucket de minuto/score."""
    from pipelines.user_bet_analytics import compute_model_errors_heatmap
    return compute_model_errors_heatmap(user_id)


@app.post("/worldcup/inplay", response_model=WcInPlayResponse)
def worldcup_inplay(req: WcInPlayRequest):
    """Mercados ao vivo condicionados ao placar e minuto (Monte Carlo no tempo restante)."""
    from ingest.superbet.benchmark import market_benchmark
    from ingest.superbet.client import SuperbetClient, SuperbetClientError
    from ingest.superbet.store import merge_snapshot_into_odds_file, save_event_snapshot
    from models.wc_inplay import inplay_from_predictor

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    home = normalize_national_team(req.home_team)
    away = normalize_national_team(req.away_team)
    home_score = req.home_score
    away_score = req.away_score
    minute = req.minute
    ht_home = req.ht_home_score
    ht_away = req.ht_away_score
    superbet_payload = None
    benchmark = None
    superbet_snapshot = None

    if req.superbet_event_id is not None:
        try:
            superbet_snapshot = SuperbetClient().fetch_event(req.superbet_event_id)
            save_event_snapshot(superbet_snapshot)
            if req.merge_superbet_odds and superbet_snapshot.h2h_odds:
                merge_snapshot_into_odds_file(superbet_snapshot)
                from pipelines.wc_market_features import load_match_odds_index

                load_match_odds_index.cache_clear()
            superbet_payload = superbet_snapshot.to_dict()
            if superbet_snapshot.inplay:
                home_score = superbet_snapshot.inplay.home_score
                away_score = superbet_snapshot.inplay.away_score
                minute = superbet_snapshot.inplay.minute
                if superbet_snapshot.inplay.ht_home_score is not None:
                    ht_home = superbet_snapshot.inplay.ht_home_score
                    ht_away = superbet_snapshot.inplay.ht_away_score
        except SuperbetClientError as exc:
            raise HTTPException(status_code=502, detail=str(exc)) from exc

    result = inplay_from_predictor(
        predictor,
        home_team=home,
        away_team=away,
        home_score=home_score,
        away_score=away_score,
        minute=minute,
        phase=req.phase,
        is_neutral=True,
        match_minutes=req.match_minutes,
        ht_home_score=ht_home,
        ht_away_score=ht_away,
    )
    payload = result.to_dict()
    if superbet_snapshot and superbet_snapshot.h2h_implied:
        benchmark = market_benchmark(
            superbet_snapshot,
            model_h2h={
                "1": payload["prob_final_home"],
                "X": payload["prob_final_draw"],
                "2": payload["prob_final_away"],
            },
            model_totals=payload.get("final_line_probs"),
        )
    payload["market_benchmark"] = benchmark
    payload["superbet"] = superbet_payload
    return WcInPlayResponse(**payload)


@app.post("/worldcup/predict", response_model=WcPredictionResponse)
def worldcup_predict(req: WcPredictRequest):
    from ingest.sofascore.client import SofascoreClientError
    from ingest.sofascore.kxl_merge import merge_sofascore_fept

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    home = normalize_national_team(req.home_team)
    away = normalize_national_team(req.away_team)
    if req.phase == "group" and not official_match_exists(home, away, phase="group"):
        raise HTTPException(
            status_code=400,
            detail=f"Confronto {home} x {away} não consta na tabela oficial da fase de grupos.",
        )

    try:
        kxl_match, fept_meta = merge_sofascore_fept(
            kxl_match=req.kxl_match,
            sofascore_event_id=req.sofascore_event_id,
            home_team=home,
            away_team=away,
        )
    except LookupError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except SofascoreClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    try:
        pred = predictor.predict(
            home,
            away,
            phase=req.phase,
            kxl_match=kxl_match,
            season=2026,
            group_name=lookup_2026_group(home, away) if req.phase == "group" else None,
        )
    except Exception as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    response = _wc_prediction_to_response(pred)
    if fept_meta:
        response.model_breakdown.kxl_fept = fept_meta
    return response


@app.post("/worldcup/simulate", response_model=WcSimulationResponse)
def worldcup_simulate(req: WcPredictRequest):
    """Analisa um confronto entre duas seleções com dados reais da FIFA.

    Diferente de /worldcup/predict, este endpoint:
    - Busca escalações oficiais da FIFA (se jogo constar na janela atual)
    - Busca pontos FIFA ao vivo (atualizados a cada jogo)
    - Busca dados enriquecidos do Sofascore (forma, séries, H2H)
    - Retorna predição dos modelos + dados brutos reais
    """
    from models.wc_match_simulator import simulate_match

    try:
        predictor = _get_wc_predictor()
    except ValueError:
        predictor = None

    from datetime import date as date_type

    home = normalize_national_team(req.home_team)
    away = normalize_national_team(req.away_team)
    parsed_date: date_type | None = None
    if req.match_date:
        try:
            parsed_date = date_type.fromisoformat(req.match_date[:10])
        except ValueError:
            raise HTTPException(status_code=400, detail="match_date inválida") from None

    try:
        result = simulate_match(
            home_team=home,
            away_team=away,
            match_date=parsed_date,
            phase=req.phase,
            is_neutral=True,
            season=2026,
            group_name=lookup_2026_group(home, away) if req.phase == "group" else None,
            predictor=predictor,
            fifa_match_id=req.fifa_match_id,
            sofascore_event_id=req.sofascore_event_id,
        )
    except Exception as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    return WcSimulationResponse(
        home_team=result.home_team,
        away_team=result.away_team,
        match_date=result.match_date,
        prediction=result.prediction,
        confidence=result.confidence,
        prob_home=result.prob_home,
        prob_draw=result.prob_draw,
        prob_away=result.prob_away,
        poisson_score=result.poisson_score,
        expected_goals=result.expected_goals,
        fifa_home_lineup=result.fifa_home_lineup,
        fifa_away_lineup=result.fifa_away_lineup,
        fifa_home_bench=result.fifa_home_bench,
        fifa_away_bench=result.fifa_away_bench,
        fifa_home_goals=result.fifa_home_goals,
        fifa_away_goals=result.fifa_away_goals,
        fifa_home_tactics=result.fifa_home_tactics,
        fifa_away_tactics=result.fifa_away_tactics,
        fifa_home_coach=result.fifa_home_coach,
        fifa_away_coach=result.fifa_away_coach,
        fifa_stadium=result.fifa_stadium,
        fifa_attendance=result.fifa_attendance,
        fifa_home_points=result.fifa_home_points,
        fifa_away_points=result.fifa_away_points,
        fifa_points_diff=result.fifa_points_diff,
        lineup_source=result.lineup_source,
        enrich_features=result.enrich_features,
        stats_features=result.stats_features,
        model_breakdown=result.model_breakdown,
        warnings=result.warnings,
    )


def _build_wc_round_predictions(
    predictor: "WcPredictor",
    round_data: dict,
    *,
    matchday: int | None = None,
) -> list[WcPredictionResponse]:
    cache = _wc_round_cache()
    phase_default = round_data.get("phase", "group")
    matches = round_data.get("matches", [])
    if matchday is not None:
        matches = [m for m in matches if m.get("round") == matchday]

    predictions: list[WcPredictionResponse] = []
    dirty = False

    for match in matches:
        home = normalize_national_team(match["home_team"])
        away = normalize_national_team(match["away_team"])
        match_phase = match.get("phase", phase_default)
        key = cache.match_key(home, away, match_phase)

        cached = cache.get_cached(key)
        if cached is not None:
            predictions.append(WcPredictionResponse(**cached))
            continue

        try:
            pred = predictor.predict(
                home,
                away,
                phase=match_phase,
                season=round_data.get("season", 2026),
                group_name=match.get("group"),
            )
            resp = _wc_prediction_to_response(pred)
            cache.set_cached(key, resp.model_dump())
            predictions.append(resp)
            dirty = True
        except Exception as exc:
            raise HTTPException(
                status_code=400,
                detail=f"Erro ao prever {home} x {away}: {exc}",
            ) from exc

    if dirty:
        cache.persist_to_disk()

    return predictions


@app.get("/worldcup/round", response_model=WcRoundResponse)
def worldcup_round(
    matchday: int | None = Query(None, alias="round", ge=1, le=3),
):
    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    round_data = _load_wc_round()
    phase_default = round_data.get("phase", "group")
    predictions = _build_wc_round_predictions(
        predictor,
        round_data,
        matchday=matchday,
    )

    return WcRoundResponse(
        season=round_data.get("season", 2026),
        competition=round_data.get("competition", "Copa do Mundo"),
        phase=phase_default,
        round=matchday if matchday is not None else round_data.get("round", 0),
        predictions=predictions,
    )


@app.get("/worldcup/group-standings", response_model=WcGroupStandingsResponse)
def worldcup_group_standings():
    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    round_data = _load_wc_round()
    predictions = _build_wc_round_predictions(predictor, round_data, matchday=None)
    pair_group: dict[tuple[str, str], str] = {}
    for match in round_data.get("matches", []):
        home = normalize_national_team(match["home_team"])
        away = normalize_national_team(match["away_team"])
        g = match.get("group")
        if g:
            pair_group[(home, away)] = str(g)

    pred_rows: list[dict] = []
    for pred in predictions:
        key = (pred.home_team, pred.away_team)
        pred_rows.append(
            {
                "home_team": pred.home_team,
                "away_team": pred.away_team,
                "prediction": pred.prediction,
                "group": pair_group.get(key),
            }
        )

    groups_meta = round_data.get("groups", [])
    blocks = build_group_standings(groups_meta, pred_rows)
    return WcGroupStandingsResponse(
        season=int(round_data.get("season", 2026)),
        competition=round_data.get("competition", "Copa do Mundo FIFA 2026"),
        simulated=True,
        note="Pontos simulados pelos palpites do modelo (3 vitória, 1 empate, 0 derrota).",
        groups=[WcGroupStandingsBlock(**block) for block in blocks],
    )


@app.get("/worldcup/teams", response_model=WcTeamsResponse)
def worldcup_teams():
    from ingest.fixtures.world_cup import load_wc_fixtures

    fixtures = load_wc_fixtures()
    teams: set[str] = set()
    if not fixtures.empty:
        teams.update(fixtures["home_team"].dropna().unique())
        teams.update(fixtures["away_team"].dropna().unique())

    round_data = _load_wc_round()
    for match in round_data.get("matches", []):
        teams.add(normalize_national_team(match["home_team"]))
        teams.add(normalize_national_team(match["away_team"]))

    sorted_teams = sorted(teams, key=str.casefold)
    return WcTeamsResponse(teams=sorted_teams, count=len(sorted_teams))


@app.get("/worldcup/friendlies", response_model=WcFriendliesResponse)
def worldcup_friendlies(
    team: str = Query(..., description="Seleção (nome canônico em português)"),
    pages: int = Query(2, ge=1, le=5, description="Páginas de histórico Sofascore por seleção"),
    year: int | None = Query(
        None,
        ge=2000,
        le=2100,
        description="Ano do calendário; padrão: ano corrente (UTC)",
    ),
    include_finished: bool = Query(True, description="Incluir amistosos já disputados"),
    include_upcoming: bool = Query(True, description="Incluir amistosos futuros/agendados"),
):
    from datetime import datetime, timezone

    from ingest.sofascore.client import SofascoreClient, SofascoreClientError
    from ingest.sofascore.friendlies import list_team_friendlies, save_friendlies_snapshot

    canonical = normalize_national_team(team)
    filter_year = year if year is not None else datetime.now(timezone.utc).year
    try:
        friendlies = list_team_friendlies(
            canonical,
            pages=pages,
            year=filter_year,
            include_finished=include_finished,
            include_upcoming=include_upcoming,
            client=SofascoreClient(),
        )
    except LookupError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except SofascoreClientError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc

    try:
        save_friendlies_snapshot(canonical, filter_year, friendlies)
    except OSError:
        pass

    items = [WcFriendlyItem(**row.to_dict()) for row in friendlies]
    return WcFriendliesResponse(
        team=canonical,
        year=filter_year,
        count=len(items),
        friendlies=items,
    )


@app.get("/worldcup/schedule", response_model=WcScheduleResponse)
def worldcup_schedule():
    try:
        data = load_wc_schedule()
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except json.JSONDecodeError as exc:
        raise HTTPException(status_code=500, detail=f"Calendário WC inválido: {exc}") from exc

    payload = build_schedule_response(data)
    return WcScheduleResponse(**payload)


@app.get("/worldcup/squads", response_model=WcSquadTeamsResponse)
def worldcup_squads():
    try:
        data = load_wc_squads()
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except json.JSONDecodeError as exc:
        raise HTTPException(status_code=500, detail=f"Convocações WC inválidas: {exc}") from exc

    return WcSquadTeamsResponse(
        season=data.get("season", 2026),
        competition=data.get("competition", "Copa do Mundo FIFA 2026"),
        source_url=data.get("source_url", ""),
        updated_at=data.get("updated_at", ""),
        team_count=data.get("team_count", len(data.get("squads", []))),
        teams=list_squad_teams(data),
    )


@app.get("/worldcup/squads/{team}", response_model=WcSquadDetailResponse)
def worldcup_squad_detail(team: str):
    try:
        data = load_wc_squads()
    except FileNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc

    squad = get_squad_by_team(data, team)
    if squad is None:
        raise HTTPException(status_code=404, detail=f"Convocação não encontrada: {team}")

    return WcSquadDetailResponse(
        season=data.get("season", 2026),
        competition=data.get("competition", "Copa do Mundo FIFA 2026"),
        source_url=data.get("source_url", ""),
        updated_at=data.get("updated_at", ""),
        squad=WcSquadTeamItem(**squad),
    )


@app.get("/worldcup/editions", response_model=WcEditionsResponse)
def worldcup_editions():
    from pipelines.wc_validate import list_wc_editions

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    editions = list_wc_editions(predictor.fixtures)
    return WcEditionsResponse(
        editions=[WcEditionItem(**e) for e in editions],
    )


@app.get("/worldcup/editions/{season}/matches", response_model=WcEditionMatchesResponse)
def worldcup_edition_matches(season: int):
    from pipelines.wc_validate import list_edition_matches

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    matches = list_edition_matches(predictor.fixtures, season)
    if not matches:
        raise HTTPException(
            status_code=404,
            detail=f"Nenhum jogo encontrado para a edição {season}",
        )
    return WcEditionMatchesResponse(
        season=season,
        matches=[WcHistoricalMatchItem(**_sanitize_match_item(m)) for m in matches],
    )


@app.post("/worldcup/validate", response_model=WcValidateResponse)
def worldcup_validate(req: WcValidateRequest):
    if not req.match_id and (not req.home_team or not req.away_team):
        raise HTTPException(
            status_code=400,
            detail="Informe match_id ou home_team e away_team",
        )

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc

    home = normalize_national_team(req.home_team) if req.home_team else None
    away = normalize_national_team(req.away_team) if req.away_team else None

    from pipelines.wc_validate import validate_historical_match

    try:
        result = validate_historical_match(
            predictor,
            predictor.fixtures,
            req.season,
            match_id=req.match_id,
            home_team=home,
            away_team=away,
        )
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    breakdown = result["model_breakdown"]
    return WcValidateResponse(
        match=WcValidateMatchInfo(**result["match"]),
        prediction=result["prediction"],
        confidence=round(result["confidence"], 4),
        prob_home=round(result["prob_home"], 4),
        prob_draw=round(result["prob_draw"], 4),
        prob_away=round(result["prob_away"], 4),
        poisson_score=result["poisson_score"],
        expected_goals=result["expected_goals"],
        correct=result["correct"],
        context=result["context"],
        h2h_summary=result["h2h_summary"],
        model_breakdown=_breakdown_to_response(breakdown),
        cutoff_date=result["cutoff_date"],
        cutoff_note=result["cutoff_note"],
    )


@app.get("/worldcup/walkforward")
def worldcup_walkforward():
    report_path = settings.lake_root / "reports" / "wc_walkforward_report.json"
    if not report_path.exists():
        raise HTTPException(
            status_code=404,
            detail="Relatório ausente. Execute: walkforward-wc-models",
        )
    return json.loads(report_path.read_text(encoding="utf-8"))


def _run_wc_retrain_background(*, enable_mlflow: bool = False) -> None:
    global _wc_predictor, _wc_artifact_meta, _wc_models_ready, _wc_train_thread
    from models.wc_artifact import load_or_train_wc_predictor
    from models.wc_train_progress import WcTrainProgressReporter

    reporter = WcTrainProgressReporter(console=False)
    try:
        predictor, manifest = load_or_train_wc_predictor(
            force=True,
            progress=reporter,
            enable_mlflow=enable_mlflow,
        )
        with _wc_train_lock:
            _wc_predictor = predictor
            _wc_artifact_meta = manifest
            _wc_models_ready = True
        _wc_round_cache().invalidate_wc_round_cache()
    except Exception as exc:
        with _wc_train_lock:
            _wc_models_ready = False
        reporter.fail(str(exc))
    finally:
        with _wc_train_lock:
            _wc_train_thread = None


@app.get("/worldcup/train/status")
def worldcup_train_status():
    from models.wc_train_progress import read_train_progress

    state = read_train_progress()
    with _wc_train_lock:
        thread_alive = _wc_train_thread is not None and _wc_train_thread.is_alive()
    if state is None:
        return {
            "status": "running" if thread_alive else "idle",
            "running": thread_alive,
        }
    payload = asdict(state)
    payload["running"] = thread_alive or state.status == "running"
    return payload


@app.post("/worldcup/retrain")
def worldcup_retrain(
    background: bool = Query(False),
    mlflow: bool = Query(False, description="Registra o treino no MLflow"),
):
    global _wc_predictor, _wc_artifact_meta, _wc_models_ready, _wc_train_thread

    if background:
        with _wc_train_lock:
            if _wc_train_thread is not None and _wc_train_thread.is_alive():
                raise HTTPException(status_code=409, detail="Treino WC já em andamento")
            _wc_train_thread = threading.Thread(
                target=_run_wc_retrain_background,
                kwargs={"enable_mlflow": mlflow},
                name="wc-retrain",
                daemon=True,
            )
            _wc_train_thread.start()
        return {"status": "started", "poll": "/worldcup/train/status", "mlflow": mlflow}

    try:
        from models.wc_artifact import load_or_train_wc_predictor
        from models.wc_train_progress import WcTrainProgressReporter

        reporter = WcTrainProgressReporter(console=False)
        _wc_predictor, _wc_artifact_meta = load_or_train_wc_predictor(
            force=True,
            progress=reporter,
            enable_mlflow=mlflow,
        )
        _wc_models_ready = True
        _wc_round_cache().invalidate_wc_round_cache()
    except ValueError as exc:
        _wc_models_ready = False
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    return {
        "status": "ok",
        "artifact": _wc_artifact_meta,
    }


@app.post("/worldcup/value/live", response_model=WcValueResponse)
def worldcup_live_value(req: WcValueRequest):
    schedule_path = Path(req.schedule_file)
    if not schedule_path.exists():
        raise HTTPException(status_code=404, detail=f"Schedule não encontrado: {schedule_path}")

    try:
        schedule = json.loads(schedule_path.read_text(encoding="utf-8"))
    except Exception as exc:
        raise HTTPException(status_code=400, detail=f"Falha ao ler schedule: {exc}") from exc

    try:
        live_odds = fetch_live_h2h_odds(
            sport_key=req.sport_key,
            regions=req.regions,
            preferred_bookmaker=req.bookmaker,
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except Exception as exc:
        raise HTTPException(status_code=502, detail=f"Erro ao consultar Odds API: {exc}") from exc

    merged, matched = merge_schedule_with_odds(schedule, live_odds)
    if req.save_odds_file:
        save_odds_file(merged, Path(req.output_odds_file))

    try:
        predictor = _get_wc_predictor()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail=str(exc)) from exc
    phase_default = merged.get("phase", "group")
    reports: list[WcMatchValueResponse] = []

    for match in merged.get("matches", []):
        phase = match.get("phase", phase_default)
        pred = predictor.predict(match["home_team"], match["away_team"], phase=phase)
        probabilities = {"1": pred.prob_home, "X": pred.prob_draw, "2": pred.prob_away}
        value = evaluate_match(
            home_team=match["home_team"],
            away_team=match["away_team"],
            probabilities=probabilities,
            odds=match["odds"],
            min_edge=req.min_edge,
        )
        reports.append(_match_value_to_response(value))

    return WcValueResponse(
        matched_games=matched,
        total_schedule_games=len(schedule.get("matches", [])),
        source=merged.get("source", "the-odds-api"),
        captured_at=merged.get("captured_at"),
        edges=reports,
    )