Spaces:
Running

File size: 35,959 Bytes
959e4bb
35bc8f7
dbdd5c5
959e4bb
96f9f5f
dbdd5c5
 
 
96f9f5f
8fe756a
35bc8f7
c924ee5
2aa3ef0
ded8996
c924ee5
8fe756a
dbdd5c5
d5fc8e2
58ca004
d5fc8e2
959e4bb
2aa3ef0
 
959e4bb
 
 
 
 
a15686e
959e4bb
35bc8f7
 
 
 
 
 
ebc8a27
 
 
8fe756a
ebc8a27
 
 
 
 
 
 
40320bc
ebc8a27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959e4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5fc8e2
 
58ca004
8fe756a
959e4bb
d5fc8e2
 
58ca004
 
8fe756a
959e4bb
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
 
 
 
 
 
58ca004
d4ba7c6
 
 
 
 
 
 
 
 
 
 
 
 
 
58ca004
 
 
 
 
 
 
 
 
 
d4ba7c6
 
 
 
267bd68
d4ba7c6
267bd68
58ca004
c924ee5
 
 
 
 
 
 
 
 
8fe756a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ba7c6
 
 
 
 
 
 
 
 
ded8996
d4ba7c6
 
 
 
 
 
 
 
 
 
 
ded8996
d4ba7c6
8fe756a
 
 
 
 
 
 
 
 
 
65caebd
8fe756a
 
 
 
 
 
c924ee5
8fe756a
c924ee5
 
 
 
 
 
8fe756a
 
 
c924ee5
d4ba7c6
 
 
 
 
c924ee5
d9a5fa8
 
8fe756a
 
 
 
d9a5fa8
65caebd
d9a5fa8
c924ee5
58ca004
267bd68
58ca004
267bd68
 
 
 
 
 
 
 
 
 
 
 
 
58ca004
 
 
 
267bd68
58ca004
267bd68
58ca004
 
 
 
 
 
 
 
 
267bd68
58ca004
 
 
 
 
267bd68
 
 
 
 
 
 
 
 
 
58ca004
 
267bd68
 
 
58ca004
267bd68
58ca004
267bd68
58ca004
267bd68
58ca004
 
dbdd5c5
959e4bb
dbdd5c5
96f9f5f
 
 
 
 
 
 
 
 
 
 
d4ba7c6
 
 
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
35bc8f7
 
 
 
959e4bb
 
 
c924ee5
35bc8f7
 
 
 
 
 
 
959e4bb
 
 
 
dbdd5c5
959e4bb
d4ba7c6
 
 
 
 
 
 
 
dbdd5c5
959e4bb
96f9f5f
959e4bb
 
 
 
 
 
 
96f9f5f
959e4bb
 
 
 
 
96f9f5f
959e4bb
d4ba7c6
959e4bb
 
96f9f5f
d4ba7c6
 
959e4bb
 
 
 
 
58ca004
 
 
 
 
 
 
 
 
 
 
959e4bb
dbdd5c5
 
58ca004
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
 
 
959e4bb
 
 
 
 
 
 
 
 
 
 
 
 
3cfc37e
959e4bb
 
 
 
 
 
 
 
dbdd5c5
5153ac4
 
 
959e4bb
96f9f5f
 
 
 
959e4bb
96f9f5f
 
 
 
dbdd5c5
959e4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b340bd0
76119a4
959e4bb
 
3f7c4aa
959e4bb
 
 
96f9f5f
dbdd5c5
959e4bb
 
d4ba7c6
 
 
959e4bb
d4ba7c6
 
959e4bb
 
dbdd5c5
 
ebc8a27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4ba7c6
 
 
ebc8a27
d4ba7c6
 
ebc8a27
 
 
 
4329ef0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b2a304
 
d5fc8e2
 
 
4329ef0
 
 
3b2a304
d5fc8e2
 
 
 
ebc8a27
 
 
 
 
 
 
 
 
 
 
 
 
dbdd5c5
 
 
 
 
 
 
 
c924ee5
dbdd5c5
2aa3ef0
 
 
 
 
dbdd5c5
 
c924ee5
dbdd5c5
 
 
 
c924ee5
dbdd5c5
 
7f85ae5
 
ebc8a27
 
 
 
 
 
 
 
 
 
 
58ca004
ebc8a27
 
58ca004
ebc8a27
 
58ca004
ebc8a27
 
 
4329ef0
 
 
 
58ca004
ebc8a27
 
4329ef0
58ca004
ebc8a27
 
 
58ca004
ebc8a27
 
 
 
 
 
 
 
d5fc8e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35bc8f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, HTTPException, Header, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import ORJSONResponse
from bs4 import BeautifulSoup
import httpx
import asyncio
import time
import re
import hashlib
import hmac
import jwt
import logging
import os
from jwt import PyJWKClient
from starlette.concurrency import run_in_threadpool

import history
import stats

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)

# ──────────────────────────────────────────────
# Cache + locks anti-thundering-herd
# ──────────────────────────────────────────────
_cache: dict = {}
BCV_TTL = 60 * 60 * 4   # 4 horas (BCV actualiza una vez al dΓ­a)
P2P_TTL = 60 * 2         # 2 minutos

# Throttle del webhook: aunque llegue con token vΓ‘lido, no se re-scrapea el BCV
# mΓ‘s de una vez cada N segundos. Neutraliza un flood con token vΓ‘lido (evita
# martillar a bcv.org.ve y quemar CPU). El cron legΓ­timo (cada 2 min) nunca lo toca.
_last_forced_refresh = 0.0
FORCED_REFRESH_MIN_INTERVAL = 30  # segundos

# ──────────────────────────────────────────────
# v2 β€” Constantes (aislamiento total respecto a v1)
# ──────────────────────────────────────────────
P2P_V2_TTL = 60 * 10
BINANCE_P2P_URL = "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search"
COUNTRY_CODE_PATTERN = re.compile(r"^[A-Z]{2}$")

# ISO 3166-1 alpha-2 β†’ ISO 4217 (fiat para Binance P2P)
SUPPORTED_COUNTRIES: dict[str, str] = {
    "AR": "ARS",   # Argentina
    "BO": "BOB",   # Bolivia
    "BR": "BRL",   # Brasil
    "CL": "CLP",   # Chile
    "CO": "COP",   # Colombia
    "CR": "CRC",   # Costa Rica
    "DO": "DOP",   # RepΓΊblica Dominicana
    "GT": "GTQ",   # Guatemala
    "HN": "HNL",   # Honduras
    "MX": "MXN",   # MΓ©xico
    "NI": "NIO",   # Nicaragua
    "PY": "PYG",   # Paraguay
    "PE": "PEN",   # PerΓΊ
    "UY": "UYU",   # Uruguay
    "VE": "VES",   # Venezuela (caso especial: local = null)
    "ES": "EUR",   # EspaΓ±a
}

# Un Lock por clave: si el cachΓ© vence y llegan 1000 requests simultΓ‘neas,
# solo la primera hace el fetch β€” las demΓ‘s esperan y consumen el cachΓ©.
_locks: dict[str, asyncio.Lock] = {}


def _lock(key: str) -> asyncio.Lock:
    if key not in _locks:
        _locks[key] = asyncio.Lock()
    return _locks[key]


def _cached(key: str, ttl: int):
    entry = _cache.get(key)
    if entry and (time.time() - entry["ts"]) < ttl:
        return entry["data"]
    return None


def _store(key: str, data: dict):
    _cache[key] = {"ts": time.time(), "data": data}


# ──────────────────────────────────────────────
# Clientes HTTP persistentes (reutilizan conexiones TCP/TLS)
# ──────────────────────────────────────────────
_http: httpx.AsyncClient | None = None        # Binance / general
_http_nv: httpx.AsyncClient | None = None     # BCV (verify=False β€” cert roto del BCV)


@asynccontextmanager
async def lifespan(app: FastAPI):
    global _http, _http_nv
    limits = httpx.Limits(max_connections=10, max_keepalive_connections=5)
    _http    = httpx.AsyncClient(timeout=10, limits=limits)
    _http_nv = httpx.AsyncClient(timeout=15, follow_redirects=True, verify=False, limits=limits)
    history.init()
    sampler = asyncio.create_task(_history_sampler()) if history.is_enabled() else None
    stats_task = stats.start(history.get_db)
    appcheck_cleanup_task = asyncio.create_task(_appcheck_cache_cleanup())
    yield
    if sampler:
        sampler.cancel()
    if stats_task:
        stats_task.cancel()
    appcheck_cleanup_task.cancel()
    await _http.aclose()
    await _http_nv.aclose()


app = FastAPI(
    title="Tazas API",
    version="1.0.0",
    lifespan=lifespan,
    default_response_class=ORJSONResponse,   # orjson: serializaciΓ³n JSON en C (5-10x mΓ‘s rΓ‘pido)
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["GET"],
    allow_headers=["*"],
)


_known_paths: set[str] | None = None


def _tracked_path(path: str) -> str:
    """Colapsa cualquier path que no sea una ruta real de la app a 'other'. Sin
    esto, byPath/latencyByPath en stats crecen sin lΓ­mite: un escΓ‘ner probando
    /wp-admin, /.env, etc. crea una entrada nueva en el dict por cada intento,
    hasta reventar el lΓ­mite de 1 MiB por documento de Firestore."""
    global _known_paths
    if _known_paths is None:
        _known_paths = {route.path for route in app.routes if hasattr(route, "path")}
    return path if path in _known_paths else "other"


@app.middleware("http")
async def _stats_middleware(request, call_next):
    # Mide throughput/latencia/errores por endpoint. Si call_next lanza, cuenta 500.
    started = time.perf_counter()
    status = 500
    try:
        response = await call_next(request)
        status = response.status_code
        return response
    finally:
        stats.record(_tracked_path(request.url.path), status, time.perf_counter() - started)
        # DEBUG TEMPORAL: guarda el detalle de los fallos de App Check para diagnosticarlos.
        # verify_app_check ahora devuelve 404 (no 401) en cualquier fallo, asΓ­ que
        # el disparador de esta captura tiene que ser 404, no 401.
        p = request.url.path
        if status == 404 and (p.startswith("/v1") or p.startswith("/v2")):
            await _capture_401(request)

# ──────────────────────────────────────────────
# Firebase App Check
# ──────────────────────────────────────────────
PROJECT_NUMBER = "748155614527"
APP_ID = "1:748155614527:android:c29d203cf594986dda8f8a"
JWKS_URL = "https://firebaseappcheck.googleapis.com/v1/jwks"

_jwks_client = PyJWKClient(JWKS_URL, cache_jwk_set=True, lifespan=3600)

# ──────────────────────────────────────────────
# Cache de validez de App Check
# ──────────────────────────────────────────────
# El token de App Check dura 7 dΓ­as (config del cliente, fuera de este repo).
# Verificar la firma RSA (CPU-bound) en cada request de esos 7 dΓ­as es
# desperdicio: el mismo patrΓ³n _cached/_lock/_store que usa el resto del
# archivo no aplica igual acΓ‘ porque no queremos guardar el token crudo como
# clave, asΓ­ que este cache vive aparte con la clave hasheada.
# Clave: sha256(token) β€” nunca el token crudo. Valor: timestamp valido_hasta.
_appcheck_cache: dict[str, float] = {}
APPCHECK_CACHE_MAX_TTL = 3 * 24 * 3600       # techo: nunca cachear mΓ‘s de 3 dΓ­as
APPCHECK_CACHE_CLEANUP_INTERVAL = 60 * 60    # limpieza cada 1 hora


def invalidate_appcheck_token(token: str) -> None:
    """Borra manualmente un token del cache de App Check (p.ej. si se detecta que
    fue comprometido y no se quiere esperar a que expire su entrada). No falla si
    el token no estaba cacheado."""
    _appcheck_cache.pop(hashlib.sha256(token.encode()).hexdigest(), None)


async def _appcheck_cache_cleanup():
    """Tarea periΓ³dica (cada 1 hora, ciclo independiente del flush de 120s de
    stats.py) que purga del cache las entradas ya vencidas. Sin esto el dict
    crece indefinidamente con tokens que ya no van a volver a usarse."""
    while True:
        await asyncio.sleep(APPCHECK_CACHE_CLEANUP_INTERVAL)
        ahora = time.time()
        vencidos = [k for k, valido_hasta in _appcheck_cache.items() if valido_hasta <= ahora]
        for k in vencidos:
            _appcheck_cache.pop(k, None)


async def verify_app_check(x_firebase_appcheck: str = Header(None)):
    # DISABLE_APP_CHECK tiene tres estados:
    #   "1"      β†’ desactivado del todo (parche histΓ³rico): no valida nada.
    #   "shadow" β†’ valida y clasifica el motivo igual que en modo estricto, pero
    #              NUNCA bloquea. Sirve para medir cuΓ‘nta gente fallarΓ­a antes de
    #              activar el bloqueo real, sin arriesgar usuarios reales (caso
    #              conocido: redes WiFi que bloquean el alcance a Play Integrity).
    #   (nada)   β†’ modo estricto: bloquea con 404.
    mode = os.getenv("DISABLE_APP_CHECK")
    if mode == "1":
        return
    shadow = mode == "shadow"

    # 404 en vez de 401 en modo estricto: a quien golpee sin token vΓ‘lido, el
    # endpoint le parece inexistente. Un 401 delata que hay algo ahΓ­ protegido y
    # digno de atacar; un 404 no invita a insistir.
    def _reject(reason: str):
        stats.record_auth_failure(reason)
        if shadow:
            return
        raise HTTPException(status_code=404, detail="Not Found")

    if not x_firebase_appcheck:
        return _reject("sin_token")

    token_hash = hashlib.sha256(x_firebase_appcheck.encode()).hexdigest()

    # Cache-hit: este token ya se verificΓ³ antes y sigue vigente. No hace falta
    # volver a validar la firma RSA (CPU-bound) ni pasar por el threadpool β€” se
    # resuelve directo en el event loop. Este es el camino que toma la mayorΓ­a
    # de los requests una vez que el cache se calienta.
    valido_hasta = _appcheck_cache.get(token_hash)
    if valido_hasta is not None and valido_hasta > time.time():
        stats.record_accepted_request()
        stats.record_appcheck_hit()
        return

    # Cache-miss: token nuevo o vencido en el cache. La verificaciΓ³n de firma es
    # CPU-bound y cara, asΓ­ que se manda al threadpool para no bloquear el event
    # loop mientras se calcula.
    def _verificar_firma():
        signing_key = _jwks_client.get_signing_key_from_jwt(x_firebase_appcheck)
        return jwt.decode(
            x_firebase_appcheck,
            signing_key.key,
            algorithms=["RS256"],
            audience=f"projects/{PROJECT_NUMBER}",
            issuer=f"https://firebaseappcheck.googleapis.com/{PROJECT_NUMBER}",
        )

    try:
        claims = await run_in_threadpool(_verificar_firma)
        if claims.get("sub") != APP_ID:
            return _reject("sub_no_coincide")
    except jwt.exceptions.PyJWTError as e:
        # Nombre real de la excepciΓ³n de PyJWT (ExpiredSignatureError, DecodeError,
        # InvalidAudienceError, PyJWKClientError...) en vez de adivinar el motivo.
        return _reject(type(e).__name__)

    # Llegar hasta acΓ‘ significa que no pasΓ³ por ningΓΊn _reject(): token presente,
    # firma/audience/issuer vΓ‘lidos y sub coincide con la app. Request aceptada.
    # Se cachea el Γ©xito (nunca los fallos) hasta el mΓ­nimo entre el exp real del
    # token y el techo de 3 dΓ­as β€” nunca le damos al cache mΓ‘s vida que la que el
    # token realmente tiene segΓΊn su propio claim.
    _appcheck_cache[token_hash] = min(claims["exp"], time.time() + APPCHECK_CACHE_MAX_TTL)
    stats.record_accepted_request()
    stats.record_appcheck_miss()


# ──────────────────────────────────────────────
# DEBUG TEMPORAL β€” App Check: por quΓ© fallan los 401
# ──────────────────────────────────────────────
# Ante un 401 en /v1|/v2, guarda el detalle en la colecciΓ³n rodante `appcheck_401`
# (30 slots que se reescriben), con el MOTIVO clasificado para ver el patrΓ³n:
#   sin_token        β†’ la app no consiguiΓ³ token (red bloquea Google / Play Integrity)
#   token_no_jwt     β†’ dummy/error de App Check (no obtuvo token real)
#   token_expirado   β†’ token vencido
#   sub_no_coincide  β†’ token de otra app
#   firma_o_aud_iss  β†’ JWT en forma OK pero rechazado (firma/audience/issuer)
# Throttle 2s para no floodear Firestore. QUITAR cuando se resuelva.
_last_401_capture = 0.0


async def _capture_401(request) -> None:
    global _last_401_capture
    db = history.get_db()
    if db is None:
        return
    now = time.time()
    if now - _last_401_capture < 2:
        return
    _last_401_capture = now

    token = request.headers.get("x-firebase-appcheck")
    info = {
        "ts": int(now),
        "path": request.url.path,
        "userAgent": request.headers.get("user-agent"),
        "hasToken": token is not None,
        "disableAppCheck": os.getenv("DISABLE_APP_CHECK"),
    }
    reason = "sin_token"
    if token:
        info["tokenLen"] = len(token)
        try:
            claims = jwt.decode(token, options={"verify_signature": False})
            info["claims"] = {k: claims.get(k) for k in ("sub", "aud", "iss", "exp", "iat")}
            sub_ok = claims.get("sub") == APP_ID
            exp = claims.get("exp")
            expired = bool(exp and exp < int(now))
            info["subMatches"] = sub_ok
            info["expired"] = expired
            reason = (
                "token_expirado" if expired
                else "sub_no_coincide" if not sub_ok
                else "firma_o_aud_iss"
            )
        except Exception as e:
            info["decodeError"] = f"{type(e).__name__}: {e}"
            info["tokenPreview"] = token[:48]
            reason = "token_no_jwt"
    info["reason"] = reason

    slot = int(now) % 30
    try:
        await db.collection("appcheck_401").document(f"slot_{slot:02d}").set(info)
    except Exception as e:
        logger.error("captura 401 fallΓ³: %s", e)


# ──────────────────────────────────────────────
# Helpers
# ──────────────────────────────────────────────
def _parse_bcv_rate(text: str) -> float | None:
    """Convierte '36,85' o '36.853,12' a float."""
    cleaned = text.strip().replace("Bs.", "").replace("S", "").strip()
    # Formato venezolano: punto como separador de miles, coma como decimal
    cleaned = cleaned.replace(".", "").replace(",", ".")
    try:
        return float(cleaned)
    except ValueError:
        return None


def _classify_fetch_error(e: Exception) -> str:
    """Clasifica el fallo de un fetcher externo (BCV, P2P) en un motivo legible
    para las stats β€” asΓ­ el dashboard distingue timeout de caΓ­da de conexiΓ³n de
    un cambio de formato en la respuesta."""
    if isinstance(e, httpx.TimeoutException):
        return "timeout"
    if isinstance(e, httpx.HTTPStatusError):
        return f"http_error_{e.response.status_code}"
    if isinstance(e, httpx.RequestError):
        return "connection_error"
    return type(e).__name__


# ──────────────────────────────────────────────
# Fetchers
# ──────────────────────────────────────────────
async def fetch_bcv(force: bool = False) -> dict:
    # force=True omite el cachΓ©: lo usa el webhook cuando changedetection.io
    # avisa que la pΓ‘gina del BCV cambiΓ³, para traer la tasa nueva de inmediato.
    if not force:
        cached = _cached("bcv", BCV_TTL)
        if cached:
            return cached

    async with _lock("bcv"):
        # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
        if not force:
            cached = _cached("bcv", BCV_TTL)
            if cached:
                return cached

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Accept-Language": "es-VE,es;q=0.9",
        }

        # verify=False porque bcv.org.ve tiene cadena de certificados incompleta (problema del BCV)
        try:
            response = await _http_nv.get("https://www.bcv.org.ve/", headers=headers)
            response.raise_for_status()
        except (httpx.TimeoutException, httpx.RequestError, httpx.HTTPStatusError) as e:
            reason = _classify_fetch_error(e)
            stats.record_fetch_error("bcv", reason, str(e))
            logger.warning("BCV fetch fallΓ³ (%s): %s", reason, e)
            raise HTTPException(status_code=503, detail="No se pudo contactar al BCV") from e

        soup = BeautifulSoup(response.text, "lxml")

        currency_ids = {
            "Usd": "dolar",
            "Eur": "euro",
            "Cny": "yuan",
            "Try": "lira",
            "Rub": "rublo",
        }

        rates = {}
        for suffix, div_id in currency_ids.items():
            div = soup.find(id=div_id)
            tag = div.find("strong") if div else None
            rates[f"bcv{suffix}"] = _parse_bcv_rate(tag.text) if tag else None

        if all(v is None for v in rates.values()):
            stats.record_fetch_error("bcv", "parse_error", "todas las tasas dieron None")
            logger.error("BCV: all rates are None β€” scraping failed")
            raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")

        stats.record_fetch_success("bcv")

        updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
        updated_at = updated_tag.text.strip() if updated_tag else None

        data = {**rates, "updatedAt": updated_at}
        _store("bcv", data)

        # Mantiene {current, previous} para la "tasa del viernes". Solo corre en un
        # scrape real (no en cache hits) y con fecha valor presente, asΓ­ que el costo
        # en Firestore es raro y no se corrompe el estado si falla leer la fecha.
        if history.is_enabled() and data.get("updatedAt"):
            try:
                previous = await history.update_bcv_state(data)
                _store("bcv_previous", previous or {})
            except Exception as e:
                logger.warning("update_bcv_state fallΓ³: %s", e)

        return data


async def _bcv_previous() -> dict | None:
    """Tasa BCV inmediatamente anterior (la 'del viernes' durante el fin de semana).
    Cacheada en memoria; se relee de Firestore al vencer el TTL del BCV. {} = sin dato."""
    cached = _cached("bcv_previous", BCV_TTL)
    if cached is not None:
        return cached or None
    previous = await history.get_bcv_previous()
    _store("bcv_previous", previous or {})
    return previous


async def fetch_p2p() -> dict:
    cached = _cached("p2p", P2P_TTL)
    if cached:
        return cached

    async with _lock("p2p"):
        # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
        cached = _cached("p2p", P2P_TTL)
        if cached:
            return cached

        headers = {
            "User-Agent": "Mozilla/5.0",
            "Content-Type": "application/json",
        }
        body_base = {
            "fiat": "VES",
            "page": 1,
            "rows": 20,
            "asset": "USDT",
            "countries": [],
            "proMerchantAds": False,
            "shieldMerchantAds": False,
            "publisherType": None,
            "payTypes": [],
            "classifies": ["mass", "profession"],
        }

        # BUY = compradores de USDT (tab "Vender" en Binance, ordenado de mayor a menor)
        # SELL = vendedores de USDT (tab "Comprar" en Binance, ordenado de menor a mayor)
        buy_ads_res, sell_ads_res = await asyncio.gather(
            _http.post(
                "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
                json={**body_base, "tradeType": "BUY"},
                headers=headers,
            ),
            _http.post(
                "https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
                json={**body_base, "tradeType": "SELL"},
                headers=headers,
            ),
        )
        buy_ads_res.raise_for_status()
        sell_ads_res.raise_for_status()

        def first_eligible_price(ads: list) -> float | None:
            """
            1. Salta los primeros 3 anuncios y promedia precios de ads[3..5] como referencia.
            2. fiat_ref = promedio * 20 (~20 USDT en VES).
            3. Devuelve el primer anuncio donde minSingleTransAmount <= fiat_ref <= maxSingleTransAmount.
            Fallback: primer anuncio desde Γ­ndice 3 con min <= fiat_ref (sin chequeo de max).
            """
            if not ads:
                return None

            sample = []
            for item in ads[3:6]:
                try:
                    sample.append(float(item["adv"]["price"]))
                except (KeyError, ValueError, TypeError):
                    pass

            if not sample:
                return None

            return round(sum(sample) / len(sample), 2)

        p2p_buy  = first_eligible_price(sell_ads_res.json().get("data", []))
        p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))

        data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
        _store("p2p", data)
        return data


async def fetch_p2p_safe() -> dict:
    try:
        data = await fetch_p2p()
        stats.record_fetch_success("p2p")
        return data
    except Exception as e:
        reason = _classify_fetch_error(e)
        stats.record_fetch_error("p2p", reason, str(e))
        logger.error("fetch_p2p failed: %s", e, exc_info=True)
        return {"p2pBuyMax": None, "p2pSellMax": None}


# ──────────────────────────────────────────────
# v2 β€” Fetchers aislados (no afectan a /v1)
# ──────────────────────────────────────────────
async def fetch_p2p_v2(fiat: str) -> dict:
    cache_key = f"p2p_v2:{fiat}"
    cached = _cached(cache_key, P2P_V2_TTL)
    if cached:
        return cached

    async with _lock(cache_key):
        cached = _cached(cache_key, P2P_V2_TTL)
        if cached:
            return cached

        headers = {
            "User-Agent": "Mozilla/5.0",
            "Content-Type": "application/json",
        }
        body_base = {
            "fiat": fiat,
            "page": 1,
            "rows": 20,
            "asset": "USDT",
            "countries": [],
            "proMerchantAds": False,
            "shieldMerchantAds": False,
            "publisherType": None,
            "payTypes": [],
            "classifies": ["mass", "profession"],
        }

        logger.info("fetch_p2p_v2 fiat=%s", fiat)

        buy_ads_res, sell_ads_res = await asyncio.gather(
            _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "BUY"},  headers=headers),
            _http.post(BINANCE_P2P_URL, json={**body_base, "tradeType": "SELL"}, headers=headers),
        )
        buy_ads_res.raise_for_status()
        sell_ads_res.raise_for_status()

        def first_eligible_price(ads: list) -> float | None:
            if not ads:
                return None
            sample = []
            for item in ads[3:6]:
                try:
                    sample.append(float(item["adv"]["price"]))
                except (KeyError, ValueError, TypeError):
                    pass
            if not sample:
                return None
            return round(sum(sample) / len(sample), 2)

        p2p_buy  = first_eligible_price(sell_ads_res.json().get("data", []))
        p2p_sell = first_eligible_price(buy_ads_res.json().get("data", []))

        data = {"p2pBuyMax": p2p_buy, "p2pSellMax": p2p_sell}
        _store(cache_key, data)
        return data


async def fetch_p2p_v2_safe(fiat: str) -> dict:
    try:
        data = await fetch_p2p_v2(fiat)
        stats.record_fetch_success("p2p_v2")
        return data
    except Exception as e:
        reason = _classify_fetch_error(e)
        stats.record_fetch_error("p2p_v2", reason, f"fiat={fiat}: {e}")
        logger.error("fetch_p2p_v2(%s) failed: %s", fiat, e, exc_info=True)
        return {"p2pBuyMax": None, "p2pSellMax": None}


# ──────────────────────────────────────────────
# v2 β€” Caso especial BR: Binance P2P no sirve anuncios pΓΊblicos para USDT/BRL
# (confirmado en vivo: `data: []` de forma consistente). En vez de un fallback
# genΓ©rico para todos los paΓ­ses, se usa el ticker spot pΓΊblico de OKX
# (sin autenticaciΓ³n) solo para este paΓ­s, igual que VE tiene su propia rama
# especial mΓ‘s abajo en rates_v2.
# ──────────────────────────────────────────────
OKX_TICKER_URL = "https://www.okx.com/api/v5/market/ticker"


async def fetch_okx_brl() -> dict:
    cache_key = "okx_v2:BRL"
    cached = _cached(cache_key, P2P_V2_TTL)
    if cached:
        return cached

    async with _lock(cache_key):
        # Double-check: mientras esperΓ‘bamos el lock, otro ya pudo haber refrescado
        cached = _cached(cache_key, P2P_V2_TTL)
        if cached:
            return cached

        logger.info("fetch_okx_brl instId=USDT-BRL")

        response = await _http.get(OKX_TICKER_URL, params={"instId": "USDT-BRL"})
        response.raise_for_status()
        payload = response.json()

        if payload.get("code") != "0":
            raise ValueError(f"OKX code={payload.get('code')!r} msg={payload.get('msg')!r}")

        rows = payload.get("data") or []
        if not rows:
            raise ValueError("OKX devolviΓ³ data vacΓ­o para USDT-BRL")

        ticker = rows[0]
        try:
            ask = float(ticker["askPx"])
            bid = float(ticker["bidPx"])
        except (KeyError, ValueError, TypeError) as e:
            raise ValueError(f"OKX ticker con campos invΓ‘lidos: {ticker}") from e

        # askPx = precio al que alguien COMPRA USDT (anΓ‘logo a p2pBuyMax).
        # bidPx = precio al que alguien VENDE USDT (anΓ‘logo a p2pSellMax).
        # Mismo contrato de salida que fetch_p2p_v2 para que rates_v2 no tenga
        # que distinguir el origen del dato al armar la respuesta.
        data = {"p2pBuyMax": round(ask, 4), "p2pSellMax": round(bid, 4)}
        _store(cache_key, data)
        return data


async def fetch_okx_brl_safe() -> dict:
    try:
        data = await fetch_okx_brl()
        stats.record_fetch_success("okx_brl")
        return data
    except Exception as e:
        reason = _classify_fetch_error(e)
        stats.record_fetch_error("okx_brl", reason, str(e))
        logger.error("fetch_okx_brl failed: %s", e, exc_info=True)
        return {"p2pBuyMax": None, "p2pSellMax": None}


# ──────────────────────────────────────────────
# Muestreador de histΓ³rico: cada 15 min registra BCV + USDT de TODAS las fiats,
# sin depender de que un usuario de ese paΓ­s pida tasas. Los fetchers ya hacen
# el registro (con dedupe por valor), asΓ­ que aquΓ­ solo se fuerza el fetch.
#
# Notas de operaciΓ³n:
# - Con --workers 2 el bucle corre en ambos procesos: el jitter inicial los
#   desincroniza y la identidad por bucket de 5 min evita duplicados en la DB.
#   El costo extra son ~4 llamadas/min a Binance en el peor caso β€” irrelevante.
# - Si el Space duerme (sin trΓ‘fico), el muestreo se pausa: quedan huecos en el
#   histΓ³rico, no errores. Con usuarios activos el Space casi nunca duerme.
# ──────────────────────────────────────────────
HISTORY_SAMPLE_INTERVAL = 60 * 15
HISTORY_SAMPLE_SPACING = 2  # segundos entre fiats para no ametrallar a Binance

async def _history_sampler():
    import random
    await asyncio.sleep(random.uniform(5, 120))  # desincronizar los 2 workers
    fiats = sorted(set(SUPPORTED_COUNTRIES.values()))
    while True:
        try:
            bcv = await fetch_bcv()
            history.record_bcv(bcv)  # dedupe por valor: solo graba si la tasa cambiΓ³
        except Exception as e:
            logger.warning("sampler: fetch_bcv fallΓ³: %s", e)
        for fiat in fiats:
            # BR: mismo caso especial que en rates_v2 β€” Binance P2P no tiene
            # anuncios para USDT/BRL, se usa el ticker spot de OKX en su lugar.
            data = await fetch_okx_brl_safe() if fiat == "BRL" else await fetch_p2p_v2_safe(fiat)
            history.record_p2p(fiat, data.get("p2pBuyMax"), data.get("p2pSellMax"))
            await asyncio.sleep(HISTORY_SAMPLE_SPACING)
        await asyncio.sleep(HISTORY_SAMPLE_INTERVAL)


def validate_country(country: str | None) -> str:
    if not country:
        raise HTTPException(status_code=400, detail="Query param 'country' es requerido")
    if not COUNTRY_CODE_PATTERN.match(country):
        raise HTTPException(
            status_code=400,
            detail="CΓ³digo de paΓ­s debe ser ISO 3166-1 alpha-2 (2 letras mayΓΊsculas)",
        )
    if country not in SUPPORTED_COUNTRIES:
        raise HTTPException(status_code=400, detail=f"PaΓ­s '{country}' no estΓ‘ soportado en esta versiΓ³n")
    return country


# ──────────────────────────────────────────────
# Endpoints
# ──────────────────────────────────────────────
@app.get("/")
async def root():
    return {"status": "ok", "service": "Tazas API"}


@app.get("/v1/rates", dependencies=[Depends(verify_app_check)])
async def rates():
    bcv_data, p2p_data = await asyncio.gather(
        fetch_bcv(),
        fetch_p2p_safe(),
    )
    return {**bcv_data, **p2p_data}


@app.get("/v1/bcv", dependencies=[Depends(verify_app_check)])
async def bcv():
    return await fetch_bcv()


@app.get("/v1/p2p", dependencies=[Depends(verify_app_check)])
async def p2p():
    return await fetch_p2p()


# ──────────────────────────────────────────────
# v2 β€” Endpoint multi-paΓ­s (aislado de /v1)
# ──────────────────────────────────────────────
@app.get("/v2/rates", dependencies=[Depends(verify_app_check)])
async def rates_v2(country: str | None = None):
    cc = validate_country(country)
    fiat = SUPPORTED_COUNTRIES[cc]

    logger.info("/v2/rates country=%s fiat=%s", cc, fiat)

    if cc == "VE":
        bcv_data, ve_p2p, prev = await asyncio.gather(
            fetch_bcv(),
            fetch_p2p_v2_safe("VES"),
            _bcv_previous(),
        )
        return {
            "venezuela": {**bcv_data, **ve_p2p, "previous": prev},
            "local": None,
        }

    # BR: Binance P2P no sirve anuncios pΓΊblicos para USDT/BRL (data: [] confirmado
    # en vivo). Caso especial: se consulta el ticker spot de OKX en su lugar.
    local_fetch = fetch_okx_brl_safe() if cc == "BR" else fetch_p2p_v2_safe(fiat)

    bcv_data, ve_p2p, local_p2p, prev = await asyncio.gather(
        fetch_bcv(),
        fetch_p2p_v2_safe("VES"),
        local_fetch,
        _bcv_previous(),
    )

    return {
        "venezuela": {**bcv_data, **ve_p2p, "previous": prev},
        "local": {
            "countryCode": cc,
            "currency": fiat,
            "usdtBuy":  local_p2p.get("p2pBuyMax"),
            "usdtSell": local_p2p.get("p2pSellMax"),
            "updatedAt": None,
        },
    }


# ──────────────────────────────────────────────
# v2 β€” HistΓ³rico (persistido en Firestore)
# ──────────────────────────────────────────────
@app.get("/v2/history", dependencies=[Depends(verify_app_check)])
async def history_v2(country: str | None = None, days: int = 30):
    """
    HistΓ³rico de tasas de los ΓΊltimos `days` dΓ­as (mΓ‘x 35).

    - bcv:   puntos {t, usd, eur, cny, try, rub} β€” el BCV cambia ~1 vez/dΓ­a.
    - p2p:   puntos {t, buy, sell} de USDT/VES β€” fluctΓΊa durante el dΓ­a.
    - local: puntos {t, buy, sell} de USDT/{fiat} β€” null para VE/dolarizados.

    `t` es epoch en segundos (UTC), redondeado a buckets de 5 minutos.
    """
    cc = validate_country(country)
    if not history.is_enabled():
        raise HTTPException(status_code=503, detail="HistΓ³rico no disponible")

    days = max(1, min(days, 35))
    fiat = SUPPORTED_COUNTRIES[cc]
    include_local = cc != "VE"

    tasks = [history.get_history("BCV", days), history.get_history("VES", days)]
    if include_local:
        tasks.append(history.get_history(fiat, days))
    results = await asyncio.gather(*tasks)

    return {
        "days": days,
        "bcv": results[0],
        "p2p": results[1],
        "local": {
            "countryCode": cc,
            "currency": fiat,
            "points": results[2],
        } if include_local else None,
    }


# ──────────────────────────────────────────────
# Webhook β€” refresco inmediato del BCV (disparado por changedetection.io)
# ──────────────────────────────────────────────
# GET + POST para que sirva cualquier pinger externo gratuito (cron-job.org,
# UptimeRobot, GitHub Actions, etc.), incluidos los que solo hacen GET.
@app.api_route("/webhook/bcv-refresh", methods=["GET", "POST"])
async def bcv_refresh_webhook(
    token: str | None = Query(default=None),
    x_webhook_token: str | None = Header(default=None),
):
    """
    Un servicio externo (cron gratuito) golpea este endpoint cada pocos minutos.
    Fuerza un scrape fresco del BCV (ignora el cachΓ© de 4h) y registra el valor
    nuevo en el histΓ³rico de inmediato. record_bcv deduplica por valor: si el
    BCV no cambiΓ³, no escribe nada. De paso, el ping mantiene despierto el Space
    (para que el muestreador interno de USDT tambiΓ©n corra).

    Protegido por secreto compartido (env WEBHOOK_SECRET), vΓ­a query `?token=`
    o header `X-Webhook-Token`. No usa App Check: el llamador es externo.
    """
    secret = os.getenv("WEBHOOK_SECRET")
    if not secret:
        raise HTTPException(status_code=404, detail="Not Found")

    provided = x_webhook_token or token or ""
    # compare_digest: comparaciΓ³n de tiempo constante (no filtra el secreto por timing).
    # 404 en vez de 401: a un escΓ‘ner sin el token, el endpoint le parece inexistente.
    if not hmac.compare_digest(provided, secret):
        raise HTTPException(status_code=404, detail="Not Found")

    # Throttle: con token vΓ‘lido pero llamadas muy seguidas, servir el ΓΊltimo valor
    # sin re-scrapear. Acota el scrape a 1 cada FORCED_REFRESH_MIN_INTERVAL seg.
    global _last_forced_refresh
    now = time.time()
    if now - _last_forced_refresh < FORCED_REFRESH_MIN_INTERVAL:
        cached = _cached("bcv", BCV_TTL) or {}
        return {"status": "throttled", "bcvUsd": cached.get("bcvUsd")}
    _last_forced_refresh = now

    data = await fetch_bcv(force=True)
    history.record_bcv(data)
    return {
        "status": "refreshed",
        "bcvUsd": data.get("bcvUsd"),
        "updatedAt": data.get("updatedAt"),
    }