File size: 47,453 Bytes
f38e611
bc308f6
 
992fce0
bc308f6
ff54386
 
 
 
 
 
 
 
bc308f6
ff54386
bc308f6
 
 
 
 
 
 
 
 
 
 
 
f38e611
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992fce0
 
 
 
 
 
 
 
fa24328
 
 
 
 
 
 
 
992fce0
fa24328
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
f38e611
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
ff54386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eddf0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
 
 
 
 
 
 
 
 
 
 
7eddf0d
 
 
 
 
 
 
 
 
 
 
ff54386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
fa24328
 
 
 
 
 
 
 
 
546d4ad
 
 
 
 
bc308f6
546d4ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
fa24328
 
 
 
 
 
 
 
 
 
 
 
 
 
992fce0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992fce0
 
 
bc308f6
 
 
 
 
 
 
 
 
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
 
 
 
 
096fb77
 
ff54386
 
096fb77
 
 
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992fce0
bc308f6
992fce0
fa24328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffd2cc6
 
 
 
 
 
fa24328
ffd2cc6
992fce0
 
 
 
 
 
 
 
bc308f6
992fce0
ffd2cc6
992fce0
bc308f6
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
 
bc308f6
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa24328
 
 
 
 
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
096fb77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
992fce0
bc308f6
 
 
 
 
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
992fce0
bc308f6
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
 
ff54386
 
bc308f6
 
ff54386
 
 
 
 
bc308f6
ff54386
 
 
 
 
 
 
 
 
 
 
 
 
 
bc308f6
ff54386
 
 
 
 
bc308f6
 
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
 
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
 
 
 
ff54386
bc308f6
fa24328
bc308f6
 
 
 
 
 
 
 
 
 
f38e611
 
 
bc308f6
f38e611
 
 
bc308f6
 
 
 
ff54386
bc308f6
 
 
 
 
 
 
 
 
fa24328
bc308f6
 
 
 
 
f38e611
 
 
bc308f6
 
 
 
 
 
 
 
 
 
 
f38e611
 
 
bc308f6
 
 
 
ff54386
bc308f6
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
import hashlib
import os
import pickle
import secrets
import numpy as np
import threading
import time
from fastapi import FastAPI, HTTPException, Request, Response, status, Depends
from fastapi.responses import JSONResponse
from logging_config import configure_logging, get_logger, new_request_id, request_id_var

configure_logging()
log = get_logger("api")
from fastapi.security.api_key import APIKeyHeader
from pydantic import BaseModel, Field
from pathlib import Path
from scoring import RiskScoringEngine, MODELS_DIR
from pipeline import run_retraining_pipeline
from database import DB_PATH, init_db

# Initialize FastAPI App
app = FastAPI(
    title="Financial Risk Intelligence API",
    description="Production-grade behavioral and transactional cashflow risk scoring system.",
    version="1.0.0"
)

def hash_api_key(api_key: str) -> str:
    """One-way hash of an API key, for storage.

    Keys were stored verbatim, so anyone with read access to the database held
    every live credential -- a backup, a support query or a leaked dump was
    enough. A key is a bearer secret and should be treated like a password: keep
    the digest, compare against that, and show the key exactly once at creation.

    SHA-256 rather than bcrypt deliberately. These are 160-bit random tokens, not
    user-chosen passwords, so they are not guessable by brute force and the slow
    hash buys nothing -- while costing real latency on EVERY authenticated
    request, which is the opposite of what this endpoint needs.
    """
    return hashlib.sha256(api_key.encode("utf-8")).hexdigest()


# Auto-initialize the database schema.
# NOTE: file existence is only a meaningful check on the SQLite path. When
# DATABASE_URL is set we are on Postgres, where DB_PATH never exists on disk;
# schema creation there is idempotent (CREATE TABLE IF NOT EXISTS).
#
# This must never abort module import: uvicorn imports this module to build the
# app, so an exception here kills the container before /health can ever answer.
# We record the failure instead and surface it as DEGRADED.
# Stateless mode: POST /score needs no database at all, so a deployment that
# only serves scoring should not require one. Setting API_KEYS turns it on --
# auth comes from the environment and no schema is created.
# The database-backed endpoints (/risk-score, /retrain, telemetry) return 503 in
# this mode rather than failing obscurely.
STATIC_API_KEYS = {k.strip() for k in os.environ.get("API_KEYS", "").split(",") if k.strip()}
DATABASE_REQUIRED = not STATIC_API_KEYS or bool(os.environ.get("DATABASE_URL"))

DB_INIT_ERROR = None
if not DATABASE_REQUIRED:
    print(f"Stateless mode: {len(STATIC_API_KEYS)} API key(s) from environment, no database required.")
else:
    try:
        if os.environ.get("DATABASE_URL"):
            print("DATABASE_URL detected. Ensuring PostgreSQL schema exists...")
            init_db()
        elif not os.path.exists(DB_PATH):
            print("Database file not found. Auto-initializing SQLite database...")
            init_db()
    except Exception as _db_init_exc:
        DB_INIT_ERROR = f"{type(_db_init_exc).__name__}: {_db_init_exc}"
        print(f"WARNING: database initialization failed, starting in DEGRADED mode: {DB_INIT_ERROR}")

def migrate_api_keys():
    """Adds api_key_hash where missing and converts any plaintext keys to digests.

    Existing keys keep working: each is hashed in place and the plaintext column
    is cleared, so callers are unaffected and the database stops holding usable
    credentials.
    """
    if not DATABASE_REQUIRED:
        return
    try:
        from database import get_db_connection, ensure_columns
        conn = get_db_connection(DB_PATH)
        try:
            ensure_columns(conn, "api_keys", [("api_key_hash", "TEXT")])
            cur = conn.cursor()
            cur.execute("SELECT api_key FROM api_keys "
                        "WHERE api_key IS NOT NULL AND (api_key_hash IS NULL OR api_key_hash = '')")
            plaintext = [r[0] for r in cur.fetchall()]
            for key in plaintext:
                # api_key is NOT NULL on databases created before this change, and
                # SQLite cannot drop that with ALTER TABLE. Writing the digest into
                # both columns satisfies the old constraint, keeps UNIQUE happy, and
                # leaves no plaintext behind -- which is the point.
                cur.execute("UPDATE api_keys SET api_key_hash = ?, api_key = ? WHERE api_key = ?",
                            (hash_api_key(key), hash_api_key(key), key))
            if plaintext:
                conn.commit()
                print(f"Migrated {len(plaintext)} API key(s) from plaintext to hashed storage.")
        finally:
            conn.close()
    except Exception as exc:
        # Loud, because a silently skipped migration leaves plaintext credentials
        # in the database while the code believes they are hashed.
        log.error("API key migration FAILED: %s", exc, exc_info=True)


migrate_api_keys()

# Initialize Risk Scoring Engine
engine = RiskScoringEngine(db_path=DB_PATH)

# --- Request limits ---
# The service runs a single uvicorn worker, so an unbounded body or an
# unthrottled caller stalls every other request. Both limits are enforced before
# any parsing or scoring work happens.
MAX_BODY_BYTES = int(os.environ.get("MAX_BODY_BYTES", 12 * 1024 * 1024))   # 12 MB
RATE_LIMIT_PER_MINUTE = int(os.environ.get("RATE_LIMIT_PER_MINUTE", 120))

# In-process counters. Adequate for a single worker; move to Redis before
# scaling horizontally, or each worker will enforce its own separate allowance.
_rate_buckets: dict[str, list] = {}
_rate_lock = threading.Lock()

def _rate_limit_check(identity: str) -> tuple[bool, int]:
    """Fixed-window counter. Returns (allowed, seconds_until_reset)."""
    now = time.time()
    window = int(now // 60)
    with _rate_lock:
        bucket = _rate_buckets.get(identity)
        if bucket is None or bucket[0] != window:
            # Drop windows we have rolled past so the dict cannot grow unbounded.
            if len(_rate_buckets) > 10000:
                _rate_buckets.clear()
            _rate_buckets[identity] = [window, 1]
            return True, 0
        if bucket[1] >= RATE_LIMIT_PER_MINUTE:
            return False, int((window + 1) * 60 - now)
        bucket[1] += 1
        return True, 0

@app.middleware("http")
async def attach_request_id(request: Request, call_next):
    """Tags every request so its log lines can be found from the response."""
    rid = request.headers.get("x-request-id") or new_request_id()
    token = request_id_var.set(rid)
    started = time.time()
    try:
        response = await call_next(request)
    except Exception:
        log.exception("Unhandled error on %s %s", request.method, request.url.path)
        raise
    finally:
        request_id_var.reset(token)
    duration_ms = int((time.time() - started) * 1000)
    log.info("%s %s -> %s in %dms", request.method, request.url.path,
             response.status_code, duration_ms)
    response.headers["X-Request-ID"] = rid
    return response


# Errors that mean "the datastore is unreachable", not "your request was wrong".
# A caller cannot act on a 500; it has to guess whether to retry. These map to
# 503 with Retry-After so a client can distinguish degraded from bad-request.
_DB_DOWN_MARKERS = (
    "could not connect", "connection to server", "connection refused",
    "operationalerror", "tenant or user not found", "enotfound",
    "no such table", "database is locked", "server closed the connection",
    "could not translate host name", "psycopg2",
)


def looks_like_database_outage(exc) -> bool:
    return any(m in f"{type(exc).__name__}: {exc}".lower() for m in _DB_DOWN_MARKERS)


def fail(status_code, public_message, exc=None):
    """Logs the real cause and returns a caller-safe message plus the request id.

    Interpolating str(exc) into the response body has already leaked a database
    error to a client. The detail belongs in the log; the caller gets an id.
    """
    rid = request_id_var.get()
    if exc is not None:
        log.exception("%s (request %s)", public_message, rid)
    else:
        log.error("%s (request %s)", public_message, rid)

    # Reclassify a datastore outage as 503. It is not the caller's fault and it
    # is retryable, which a 500 cannot express.
    if exc is not None and looks_like_database_outage(exc):
        return HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=("The scoring database is unreachable, so this endpoint is "
                    "temporarily degraded. Retry later, or use POST /score, which "
                    f"requires no database. (request id: {rid})"),
            headers={"Retry-After": "60"})

    return HTTPException(status_code=status_code,
                         detail=f"{public_message} (request id: {rid})")


@app.middleware("http")
async def enforce_request_limits(request: Request, call_next):
    content_length = request.headers.get("content-length")
    if content_length and content_length.isdigit() and int(content_length) > MAX_BODY_BYTES:
        return JSONResponse(
            status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
            content={"detail": f"Request body exceeds {MAX_BODY_BYTES} bytes."})

    if request.url.path not in ("/health", "/score/contract", "/docs", "/openapi.json"):
        identity = request.headers.get(API_KEY_NAME) or (request.client.host if request.client else "anonymous")
        allowed, retry_after = _rate_limit_check(identity)
        if not allowed:
            return JSONResponse(
                status_code=status.HTTP_429_TOO_MANY_REQUESTS,
                content={"detail": f"Rate limit of {RATE_LIMIT_PER_MINUTE} requests/minute exceeded."},
                headers={"Retry-After": str(retry_after)})

    return await call_next(request)

# --- API Key Authentication System ---
API_KEY_NAME = "x-api-key"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)

def verify_api_key(api_key: str = Depends(api_key_header)):
    """Verifies that the provided API key is active in the database."""
    if not api_key:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="API key missing. Please provide it in the 'x-api-key' header."
        )
    # Environment-provided keys are checked first and need no database.
    if STATIC_API_KEYS:
        if any(secrets.compare_digest(api_key, known) for known in STATIC_API_KEYS):
            return api_key
        if not DATABASE_REQUIRED:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Invalid or revoked API key.")

    # Authentication runs as a FastAPI dependency, BEFORE the endpoint body and
    # outside the handler that maps datastore outages to 503. Without catching it
    # here a database outage makes every authenticated endpoint return a bare 500
    # -- including POST /score, which needs no database for scoring and is
    # supposed to be the path that stays up when the database does not.
    from database import get_db_connection
    try:
        conn = get_db_connection(DB_PATH)
        try:
            cursor = conn.cursor()
            # Look the key up by digest. Legacy plaintext rows are still honoured
            # so an existing deployment does not lock itself out on upgrade.
            cursor.execute(
                "SELECT status FROM api_keys WHERE api_key_hash = ? OR api_key = ?",
                (hash_api_key(api_key), api_key))
            row = cursor.fetchone()
        finally:
            conn.close()
    except Exception as auth_exc:
        log.error("Key verification could not reach the key store: %s", auth_exc)
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=("Cannot verify the API key: the key store is unreachable. This is a "
                    "service fault, not a problem with your request. Setting API_KEYS on "
                    "this deployment authenticates without a database."),
            headers={"Retry-After": "60"})
    
    if not row or row["status"] != "ACTIVE":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid or revoked API key."
        )
    return api_key

def require_database():
    """Guards endpoints that cannot work without a database.

    In stateless mode these would otherwise fail deep in a query with an
    unhelpful error; this says plainly that the deployment does not have one.
    """
    if not DATABASE_REQUIRED:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="This endpoint requires a database. This deployment is running in "
                   "stateless mode (API_KEYS set, no DATABASE_URL). Use POST /score, "
                   "or configure DATABASE_URL to enable the full surface.")


# --- Admin Authentication (API key lifecycle) ---
# Key issuance must not be reachable using a key that this endpoint itself hands
# out, so generation and revocation sit behind a separate admin secret supplied
# via the ADMIN_API_KEY environment variable rather than the api_keys table.
ADMIN_KEY_NAME = "x-admin-key"
admin_key_header = APIKeyHeader(name=ADMIN_KEY_NAME, auto_error=False)

def verify_admin_key(admin_key: str = Depends(admin_key_header)):
    """Verifies the caller holds the deployment's admin secret."""
    expected = os.environ.get("ADMIN_API_KEY")
    if not expected:
        # Fail closed: an unconfigured secret disables key management rather
        # than leaving it open to anonymous callers.
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Key management is disabled: ADMIN_API_KEY is not configured on this deployment."
        )
    if not admin_key or not secrets.compare_digest(admin_key, expected):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid or missing admin key."
        )
    return admin_key

# --- Pydantic Schemas ---
class RiskScoreRequest(BaseModel):
    user_id: int

class RiskScoreResponse(BaseModel):
    user_id: int
    risk_score: float
    credit_score: int
    default_probability: float
    financial_stress_probability: float
    liquidity_risk: float
    confidence_score: float
    top_risk_factors: list[str]
    top_positive_factors: list[str]
    model_version: str
    predicted_at: str
    snapshot_date: str
    age: int
    dob: str
    
    # Sequential intelligence fields
    conformal_bounds: dict | None = None
    latent_state: str | None = None
    behavioural_archetype: str | None = None
    survival_trajectories: dict | None = None
    ood_alert: dict | None = None
    resilience_profile: dict | None = None
    
    # Part 16 Governance and Validation fields
    data_quality_index: float | None = None
    data_quality_flags: dict | None = None
    uncertainty_decomposition: dict | None = None
    multi_horizon_forecasting: dict | None = None
    digital_twin_scenarios: dict | None = None
    sequence_explanation: dict | None = None
    human_review_escalation: dict | None = None
    
    # Part 17 Production Consolidation fields
    macro_regime_adjustment: dict | None = None
    thin_file_analysis: dict | None = None
    confidence_underwriting: dict | None = None
    self_reported_scrutiny: dict | None = None

    # Data freshness (how old the scored snapshot is)
    data_freshness: dict | None = None

    # Part 19 Multi-Account Financial Intelligence & Visibility Governance fields
    visibility_score: float | None = None
    account_roles: dict | None = None
    consolidated_liquidity: float | None = None
    omission_risk_score: float | None = None
    transfer_reconciliation_summary: dict | None = None
    multi_account_governance_metadata: dict | None = None


# --- Stateless scoring (payload in, scores out) ---
# Every field is optional by design. Applicants differ in what is known about
# them, so the contract accepts whatever the caller has and reports what it could
# actually use in the `coverage` block of the response rather than rejecting.

class ScoreProfile(BaseModel):
    user_id: int | None = None
    age: int | None = None
    dob: str | None = None
    employment_status: str | None = None   # EMPLOYED|SELF_EMPLOYED|UNEMPLOYED|STUDENT|RETIRED
    housing_type: str | None = None        # RENT|MORTGAGE|OWNED|OTHER
    credit_score: int | None = None
    gross_income: float | None = None
    net_income: float | None = None
    debt_self_report: float | None = None
    impulse_spending: int | None = None          # 1-5 self-report
    tracking_habits: int | None = None           # 1-5 self-report
    income_stability_report: int | None = None   # 1-5 self-report
    savings_habits: int | None = None            # 1-5 self-report

class ScoreAccount(BaseModel):
    account_id: str | None = None
    account_type: str | None = None    # CHECKING|SAVINGS|CREDIT_CARD|LOAN
    balance: float | None = None       # credit balances are negative when owed
    credit_limit: float | None = None
    overdraft_limit: float | None = None

class ScoreTransaction(BaseModel):
    transaction_date: str
    amount: float                      # positive = inflow, negative = outflow
    category: str | None = None
    account_id: str | None = None
    description: str | None = None
    is_failed: bool | None = False

# Caps sized well above a realistic applicant (12 months of open-banking data is
# typically 1-3k transactions) while bounding the work a single request can cause.
MAX_TRANSACTIONS = 10000
MAX_ACCOUNTS = 50

class ScoreRequest(BaseModel):
    profile: ScoreProfile | None = None
    accounts: list[ScoreAccount] = Field(default_factory=list, max_length=MAX_ACCOUNTS)
    transactions: list[ScoreTransaction] = Field(default_factory=list, max_length=MAX_TRANSACTIONS)
    market: str | None = None          # UK|CZECH|INDIA|SME - selects the calibration curve
    as_of: str | None = None           # scoring date; defaults to now
    include_simulations: bool = False
    audit: bool = False                # persist the score only; never the input data

class RetrainResponse(BaseModel):
    status: str
    deployed: bool
    decision_reason: str
    champion_metrics: dict | None
    challenger_metrics: dict | None
    drift_report: dict | None
    timestamp: str

class GenerateKeyRequest(BaseModel):
    client_name: str

class RevokeKeyRequest(BaseModel):
    api_key: str

# --- Endpoints ---
@app.get("/health", status_code=status.HTTP_200_OK)
def health_check(response: Response):
    """Verifies service health and database availability."""
    db_error = None
    if not DATABASE_REQUIRED:
        # Nothing to be degraded about: scoring does not use a database.
        return {
            "status": "HEALTHY",
            "mode": "stateless",
            "database_required": False,
            "database_connected": False,
            "database_error": None,
            "scoring_endpoints": ["/score", "/score/contract"],
            "unavailable_without_database": [
                "/risk-score", "/retrain", "/portfolio-risk", "/continuous-update",
                "/shadow-telemetry", "/shadow-learning-status", "/dashboard-telemetry",
                "/explain-regulatory", "/active-learning/escalate", "/autonomous-cycle",
                "/external-dataset/register", "/api-key/generate", "/api-key/revoke"],
            "loaded_model_type": "xgboost" if len(engine.ml_models) > 0 else "baseline_heuristic",
            "shadow_model_active": engine.shadow_model is not None,
        }

    try:
        from database import get_db_connection
        conn = get_db_connection()
        conn.close()
        db_connected = True
    except Exception as e:
        log.warning("Health check database connection failure: %s", e)
        db_connected = False
        db_error = f"{type(e).__name__}: {e}"

    healthy = db_connected and DB_INIT_ERROR is None
    if not healthy:
        # Report DEGRADED with a non-2xx code so orchestrators and uptime checks
        # actually notice, rather than seeing a 200 with a DEGRADED body.
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE

    return {
        "status": "HEALTHY" if healthy else "DEGRADED",
        "database_connected": db_connected,
        "database_error": db_error or DB_INIT_ERROR,
        "loaded_model_type": "xgboost" if len(engine.ml_models) > 0 else "baseline_heuristic",
        "shadow_model_active": engine.shadow_model is not None
    }

@app.post("/risk-score", response_model=RiskScoreResponse, status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def get_risk_score(request: RiskScoreRequest):
    """Calculates behavioral credit and stress risk score for a user.
    
    Checks database for transactions and features, scores using the calibrated
    XGBoost champion model (falling back to baseline if thin-file/cold-start),
    computes SHAP explanations, and logs output for auditability.
    """
    try:
        score_profile = engine.score_user(request.user_id, save_pred=True)
        return score_profile
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR,
                   "An error occurred during scoring calculation", e)

@app.post("/score", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key)])
def score_from_payload(request: ScoreRequest):
    """Scores an applicant from data supplied in the request body.

    Stateless: nothing is read from or written to the database. Send whatever is
    known about the applicant and the full risk profile comes back.

    Incomplete input is expected and handled rather than rejected. The engine
    falls back through the calibrated model, the thin-file path and the
    cold-start heuristic depending on what is usable, and every response carries:

      coverage  - which signals were present, how much history was supplied, and
                  the resulting sufficiency tier (FULL/PARTIAL/THIN)
      warnings  - anything the caller should correct: unrecognised category
                  labels, an inverted amount sign, a market with no calibrator.
                  These do not fail the request, but they change the score.

    Read `confidence_score` and `coverage.sufficiency` alongside the probability:
    a score built from a profile alone is not the same claim as one built from
    six months of transactions.
    """
    from payload import PayloadError
    if request.audit and not DATABASE_REQUIRED:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="audit=true needs a database to write the prediction record, and this "
                   "deployment is running in stateless mode. Omit audit, or set DATABASE_URL.")
    try:
        return engine.score_payload(
            profile=request.profile.model_dump() if request.profile else None,
            accounts=[a.model_dump() for a in request.accounts],
            transactions=[t.model_dump() for t in request.transactions],
            market=request.market,
            as_of=request.as_of,
            run_simulations=request.include_simulations,
            audit=request.audit,
        )
    except PayloadError as e:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e))
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Scoring failed", e)


@app.get("/score/contract", status_code=status.HTTP_200_OK)
def score_contract():
    """Returns the vocabularies /score accepts, so integrations can be validated.

    Values outside these sets do not fail a request; they are reported as
    warnings and the affected signal is treated as absent.
    """
    import payload as pl
    return {
        "transaction_categories": sorted(pl.TRANSACTION_CATEGORIES),
        "expense_categories": sorted(pl.EXPENSE_CATEGORIES),
        "account_types": sorted(pl.ACCOUNT_TYPES),
        "employment_statuses": sorted(pl.EMPLOYMENT_STATUSES),
        "housing_types": sorted(pl.HOUSING_TYPES),
        "markets": sorted(pl.MARKETS),
        "conventions": {
            "amount_sign": "positive = inflow, negative = outflow",
            "credit_card_balance": "negative when money is owed",
            "feature_window_days": pl.FEATURE_WINDOW_DAYS,
            "trend_window_days": pl.TEMPORAL_WINDOW_DAYS,
            "recommended_history_days": pl.TEMPORAL_WINDOW_DAYS,
        },
        "required": "None. All fields are optional; supply at least one account "
                    "balance, an income figure, or a credit score.",
    }


@app.post("/retrain", response_model=RetrainResponse, status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def trigger_retraining():
    """Triggers the model retraining pipeline.
    
    Regenerates snapshots and labels from the latest database transactions,
    trains a candidate model, compares it against the active model,
    performs drift detection, deploys the superior model, and reloads it in-memory.
    """
    try:
        report = run_retraining_pipeline(engine.db_path)
        
        # Hot-reload models in memory after successful retraining run
        engine.reload_models()
        
        return {
            "status": "SUCCESS",
            "deployed": report["deployed"],
            "decision_reason": report["decision_reason"],
            "champion_metrics": report["champion_metrics"],
            "challenger_metrics": report["challenger_metrics"],
            "drift_report": report["drift_report"],
            "timestamp": report["timestamp"]
        }
    except Exception as e:
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Retraining failed", e)

@app.get("/shadow-telemetry", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def get_shadow_telemetry():
    """Computes comparison telemetry and divergence between active Champion and active Shadow predictions."""
    from database import get_db_connection
    
    shadow_active = engine.shadow_model is not None
    
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    
    try:
        # Join predictions
        cursor.execute("""
            SELECT mp.default_probability AS champ_def, 
                   mp.financial_stress_probability AS champ_stress,
                   smp.default_probability AS shadow_def,
                   smp.financial_stress_probability AS shadow_stress
            FROM shadow_model_predictions smp
            JOIN model_predictions mp ON smp.champion_prediction_id = mp.prediction_id
        """)
        rows = cursor.fetchall()
    except Exception as db_ex:
        conn.close()
        return {
            "shadow_model_active": shadow_active,
            "total_predictions": 0,
            "message": f"Could not retrieve telemetry: {db_ex}"
        }
        
    conn.close()
    
    if not rows:
        return {
            "shadow_model_active": shadow_active,
            "total_predictions": 0,
            "message": "No shadow predictions captured yet."
        }
        
    champ_defs = [r["champ_def"] for r in rows]
    champ_stresses = [r["champ_stress"] for r in rows]
    shadow_defs = [r["shadow_def"] for r in rows]
    shadow_stresses = [r["shadow_stress"] for r in rows]
    
    n_preds = len(rows)
    
    # Compute metrics
    mae_def = float(np.mean(np.abs(np.array(champ_defs) - np.array(shadow_defs))))
    mae_stress = float(np.mean(np.abs(np.array(champ_stresses) - np.array(shadow_stresses))))
    
    # Pearson correlation
    corr_def = 1.0
    corr_stress = 1.0
    if n_preds > 1:
        std_champ_def = np.std(champ_defs)
        std_shadow_def = np.std(shadow_defs)
        if std_champ_def > 0 and std_shadow_def > 0:
            corr_def = float(np.corrcoef(champ_defs, shadow_defs)[0, 1])
        std_champ_stress = np.std(champ_stresses)
        std_shadow_stress = np.std(shadow_stresses)
        if std_champ_stress > 0 and std_shadow_stress > 0:
            corr_stress = float(np.corrcoef(champ_stresses, shadow_stresses)[0, 1])
            
    return {
        "shadow_model_active": shadow_active,
        "shadow_model_version": engine.shadow_model["metadata"].get("timestamp", "v1.0") if shadow_active else None,
        "total_predictions": n_preds,
        "metrics": {
            "mean_absolute_difference_default": round(mae_def, 4),
            "mean_absolute_difference_stress": round(mae_stress, 4),
            "correlation_default": round(corr_def, 4) if not np.isnan(corr_def) else 1.0,
            "correlation_stress": round(corr_stress, 4) if not np.isnan(corr_stress) else 1.0
        }
    }

# --- Part 18 Continuous Learning Schemas & Endpoints ---

class ContinuousUpdateRequest(BaseModel):
    user_id: int
    transactions: list[dict] = []
    accounts: list[dict] | None = None
    outcomes: list[dict] | None = None
    overrides: dict | None = None
    macro_regime: dict | None = None

class RegulatoryExplainRequest(BaseModel):
    user_id: int
    smoothing_alpha: float = 0.40

@app.post("/continuous-update", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def continuous_update(request: ContinuousUpdateRequest):
    """Processes incoming data streams, logs them to database, and triggers continuous adaptation."""
    try:
        from continuous_learning import ContinuousLearningOrchestrator
        import pandas as pd
        
        orchestrator = ContinuousLearningOrchestrator(db_path=DB_PATH)
        df_transactions = pd.DataFrame(request.transactions)
        
        orchestrator.process_streaming_input(
            user_id=request.user_id,
            df_transactions=df_transactions,
            accounts=request.accounts,
            outcomes=request.outcomes,
            overrides=request.overrides,
            macro_regime=request.macro_regime
        )
        return {
            "status": "SUCCESS",
            "message": "Continuous learning and ingestion update completed successfully.",
            "user_id": request.user_id
        }
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Continuous update failed", e)

@app.get("/shadow-learning-status", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def get_shadow_learning_status():
    """Reports on continuous learning safety gate status (FGI/ECE/PSI) and active suppressions."""
    from database import get_db_connection
    from continuous_learning import ContinuousLearningOrchestrator
    import datetime
    
    orchestrator = ContinuousLearningOrchestrator(db_path=DB_PATH)
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    
    # 1. Fetch ECE from calibration_memory
    try:
        cursor.execute("SELECT ece, recalibration_triggered, recalibration_reason FROM calibration_memory ORDER BY log_id DESC LIMIT 1")
        cal_row = cursor.fetchone()
    except Exception:
        cal_row = None
        
    # 2. Fetch PSI from portfolio_telemetry
    try:
        cursor.execute("SELECT population_drift_psi FROM portfolio_telemetry ORDER BY log_id DESC LIMIT 1")
        port_row = cursor.fetchone()
    except Exception:
        port_row = None
        
    conn.close()
    
    model_ver = f"xgb_{engine.metadata.get('timestamp', 'v1.0') if (engine.metadata and isinstance(engine.metadata, dict)) else 'v1.0'}"
    suppressed_feats = orchestrator.trust_engine.load_active_suppressions(model_ver)

    # Only report what has actually been measured. fgi, transfer_auc and both
    # AUCs were previously hardcoded literals presented as live telemetry, and
    # the gate verdict was computed from them. Unmeasured values are now null and
    # the gate is not run rather than being run on invented inputs.
    from adaptive_calibration import fetch_matured_calibration_pairs
    _, _, cal_meta = fetch_matured_calibration_pairs(DB_PATH, model_version=model_ver, target="default")

    ece_val = float(cal_row["ece"]) if cal_row else None
    psi_val = float(port_row["population_drift_psi"]) if port_row else None

    champion_eval = {}
    if engine.metadata and isinstance(engine.metadata, dict):
        champion_eval = engine.metadata.get("evaluation", {}).get("default_90d", {}) or {}

    measured = {
        "ece": ece_val,
        "psi": psi_val,
        "holdout_auc_at_training": champion_eval.get("roc_auc"),
        "matured_outcomes_available": cal_meta["matched_pairs"],
        "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    not_measured = {
        "fgi": "not computed in production; no feature-governance job runs",
        "transfer_auc": "not computed in production; requires a cross-domain holdout",
        "live_auc": "requires matured outcomes joined to predictions; "
                    f"{cal_meta['matched_pairs']} pairs available"
    }

    can_gate = ece_val is not None and psi_val is not None and cal_meta["sufficient"]
    if can_gate:
        gate_res = orchestrator.gatekeeper.validate_shadow_update(
            {"ece": ece_val, "psi": psi_val, "auc": champion_eval.get("roc_auc", 0.0),
             "fgi": 0.0, "transfer_auc": 0.0},
            {"auc": champion_eval.get("roc_auc", 0.0)})
        verdict, approved, reasons = gate_res["verdict"], gate_res["approved"], gate_res["reasons"]
    else:
        verdict, approved = "NOT_ASSESSED", False
        reasons = ["Safety gate not evaluated: " + (
            cal_meta.get("reason") if not cal_meta["sufficient"]
            else "no calibration or drift telemetry recorded yet")]

    return {
        "status": verdict,
        "safety_gate_passed": approved,
        "reasons": reasons,
        "metrics": measured,
        "not_measured": not_measured,
        "recalibration_triggered_status": bool(cal_row["recalibration_triggered"]) if (cal_row and cal_row["recalibration_triggered"]) else False,
        "recalibration_reason": cal_row["recalibration_reason"] if cal_row else None,
        "active_suppressions": list(suppressed_feats.keys())
    }

@app.get("/portfolio-risk", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def get_portfolio_risk():
    """Calculates portfolio expected loss, concentration, and runs macro stress tests."""
    from database import get_db_connection
    import pandas as pd
    from portfolio_risk import PortfolioRiskAggregator
    
    portfolio_agg = PortfolioRiskAggregator(db_path=DB_PATH)
    
    conn = get_db_connection(DB_PATH)
    try:
        df_predictions = pd.read_sql_query("""
            SELECT mp.user_id, mp.default_probability, COALESCE(a.credit_limit, 1000.0) AS suggested_credit_limit
            FROM model_predictions mp
            LEFT JOIN accounts a ON mp.user_id = a.user_id AND a.account_type = 'CHECKING'
            WHERE mp.predicted_at = (
                SELECT MAX(mp2.predicted_at) FROM model_predictions mp2
                WHERE mp2.user_id = mp.user_id
            )
        """, conn)
    except Exception as e:
        conn.close()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to query model predictions", e)
    conn.close()
    
    if df_predictions.empty:
        return {
            "portfolio_size": 0,
            "expected_loss": 0.0,
            "stress_concentration_ratio": 0.0,
            "population_drift_psi": 0.0,
            "stress_test_simulation": {
                "baseline_loss": 0.0,
                "stressed_loss": 0.0,
                "increase_ratio": 0.0
            }
        }
        
    psi = 0.04
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT population_drift_psi FROM portfolio_telemetry ORDER BY log_id DESC LIMIT 1")
        row = cursor.fetchone()
        if row:
            psi = float(row[0])
    except Exception:
        pass
    conn.close()
    
    eval_report = portfolio_agg.evaluate_portfolio(df_predictions, psi=psi)
    return eval_report

@app.post("/explain-regulatory", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def explain_regulatory(request: RegulatoryExplainRequest):
    """Returns stable, causally filtered, and temporally smoothed explanations for regulatory audits."""
    from database import get_db_connection
    import json
    
    user_id = request.user_id
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    try:
        cursor.execute("""
            SELECT shap_explanations FROM model_predictions
            WHERE user_id = ?
            ORDER BY predicted_at DESC
            LIMIT 10
        """, (user_id,))
        rows = cursor.fetchall()
    except Exception as e:
        conn.close()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Database query failed", e)
    conn.close()
    
    if not rows:
        # Score the user first to populate the DB
        try:
            profile = engine.score_user(user_id, save_pred=True)
            conn = get_db_connection(DB_PATH)
            cursor = conn.cursor()
            cursor.execute("""
                SELECT shap_explanations FROM model_predictions
                WHERE user_id = ?
                ORDER BY predicted_at DESC
                LIMIT 10
            """, (user_id,))
            rows = cursor.fetchall()
            conn.close()
        except Exception as e:
            raise fail(status.HTTP_404_NOT_FOUND,
                       f"No prediction history found for user {user_id} and scoring failed", e)
            
    if not rows:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"No SHAP explanations available for User {user_id}"
        )
        
    shap_vectors = []
    for r in rows:
        try:
            if r["shap_explanations"]:
                shap_vectors.append(json.loads(r["shap_explanations"]))
        except Exception:
            pass
            
    if not shap_vectors:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Could not parse SHAP explanations for User {user_id}"
        )
        
    current_shap = shap_vectors[0]
    historical_shap_list = shap_vectors[1:]
    
    # Load latest FTS scores from db
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    fts_scores = {}
    try:
        cursor.execute("""
            SELECT feature_name, trust_score FROM feature_trust_logs ft1
            WHERE log_id = (
                SELECT MAX(log_id) FROM feature_trust_logs ft2 
                WHERE ft2.feature_name = ft1.feature_name
            )
        """)
        fts_rows = cursor.fetchall()
        fts_scores = {r["feature_name"]: r["trust_score"] for r in fts_rows}
    except Exception:
        pass
    conn.close()
    
    # Fetch visibility governance from the latest prediction or re-run multi-account aggregator
    visibility_gov = None
    try:
        from multi_account_intelligence import MultiAccountAggregator
        ma_aggregator = MultiAccountAggregator(DB_PATH)
        ma_profile = ma_aggregator.aggregate_entity_profile(user_id)
        visibility_gov = ma_profile.get("visibility_governance")
    except Exception as ex_ma_exp:
        print(f"Failed to fetch multi-account profile for explainability report: {ex_ma_exp}")

    from regulatory_explainability import RegulatoryExplainer
    reg_explainer = RegulatoryExplainer()
    explanation_report = reg_explainer.generate_compliance_explanation(
        current_shap=current_shap,
        historical_shap_list=historical_shap_list,
        fts_scores=fts_scores,
        visibility_governance=visibility_gov
    )
    
    return explanation_report

# --- Part 19 Autonomous & Safety Extensions ---

class IngestDatasetRequest(BaseModel):
    dataset_name: str
    data: list[dict]
    trust_tier: int = 3

class ActiveLearningRequest(BaseModel):
    user_id: int
    ensemble_variance: float = 0.0

class AutonomousCycleRequest(BaseModel):
    cycle_type: str = "hourly"

@app.post("/external-dataset/register", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def register_external_dataset(request: IngestDatasetRequest):
    """Profiles and registers a new external dataset (e.g., Kaggle, FRED) against reference data."""
    try:
        from external_dataset_registry import ExternalDatasetRegistry
        from database import get_db_connection
        import pandas as pd
        
        registry = ExternalDatasetRegistry()
        df_new = pd.DataFrame(request.data)
        
        # Load reference snapshot data
        conn = get_db_connection(DB_PATH)
        df_reference = pd.read_sql_query("SELECT * FROM feature_snapshots LIMIT 100", conn)
        conn.close()
        
        # Determine numerical features matching reference columns
        with open(MODELS_DIR / "model_metadata.pkl", "rb") as f:
            meta = pickle.load(f)
        feat_names = meta["feature_names"]
        
        report = registry.profile_and_register_dataset(
            name=request.dataset_name,
            df_new=df_new,
            df_reference=df_reference,
            feature_cols=feat_names,
            trust_tier=request.trust_tier
        )
        return report
    except Exception as e:
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Dataset profiling failed", e)

@app.post("/active-learning/escalate", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def evaluate_active_learning(request: ActiveLearningRequest):
    """Evaluates active learning priority and analyst reliability rating for a user profile."""
    try:
        from active_learning import ActiveLearningEngine
        
        engine_al = ActiveLearningEngine(db_path=DB_PATH)
        
        # Score the user first to get current risk profile
        profile = engine.score_user(request.user_id, save_pred=False, run_simulations=False)
        dqi_score = profile.get("data_quality_index", 0.85)
        
        escalation_report = engine_al.evaluate_escalation_priority(
            user_profile=profile,
            dqi_score=dqi_score,
            ensemble_variance=request.ensemble_variance
        )
        
        # Get reliability score for a sample underwriter
        reliability_report = engine_al.compute_reviewer_reliability("ANALYST_01")
        
        return {
            "escalation": escalation_report,
            "analyst_audit": reliability_report
        }
    except Exception as e:
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Active learning evaluation failed", e)

@app.get("/dashboard-telemetry", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def get_dashboard_telemetry():
    """Returns a consolidated summary of production telemetry dashboard data."""
    try:
        from production_dashboard import ProductionTelemetryDashboard
        dash = ProductionTelemetryDashboard(db_path=DB_PATH)
        return dash.generate_dashboard_report()
    except Exception as e:
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Dashboard aggregation failed", e)

@app.post("/autonomous-cycle", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_api_key), Depends(require_database)])
def trigger_autonomous_cycle(request: AutonomousCycleRequest):
    """Triggers orchestrator cycles (hourly micro-updates, daily recalibrations, weekly retraining, monthly gates)."""
    try:
        from autonomous_learning_engine import AutonomousLearningEngine
        auton_engine = AutonomousLearningEngine(db_path=DB_PATH)
        auton_engine.run_scheduler_update(cycle_type=request.cycle_type)
        return {
            "status": "SUCCESS",
            "message": f"Autonomous learning [{request.cycle_type.upper()}] cycle executed successfully."
        }
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Autonomous cycle failed", e)

@app.post("/api-key/generate", status_code=status.HTTP_201_CREATED, dependencies=[Depends(verify_admin_key), Depends(require_database)])
def generate_api_key(request: GenerateKeyRequest):
    """Generates a secure random API key, logs it to database, and returns it."""
    from database import get_db_connection
    
    # Generate a prefix like fr_live_ for identification
    key = f"fr_live_{secrets.token_hex(20)}"
    
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    try:
        # Written to both columns for the same reason as the migration above:
        # pre-existing tables declare api_key NOT NULL.
        digest = hash_api_key(key)
        cursor.execute("""
            INSERT INTO api_keys (api_key_hash, api_key, client_name, status)
            VALUES (?, ?, ?, 'ACTIVE')
        """, (digest, digest, request.client_name))
        conn.commit()
    except Exception as e:
        conn.rollback()
        conn.close()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to generate API key", e)
    conn.close()
    
    return {
        "client_name": request.client_name,
        "api_key": key,
        "status": "ACTIVE",
        "message": "Store this key securely. It will not be shown again."
    }

@app.post("/api-key/revoke", status_code=status.HTTP_200_OK, dependencies=[Depends(verify_admin_key), Depends(require_database)])
def revoke_api_key(request: RevokeKeyRequest):
    """Revokes an existing active API key."""
    from database import get_db_connection
    conn = get_db_connection(DB_PATH)
    cursor = conn.cursor()
    cursor.execute(
        "SELECT status FROM api_keys WHERE api_key_hash = ? OR api_key = ?",
        (hash_api_key(request.api_key), request.api_key))
    row = cursor.fetchone()
    
    if not row:
        conn.close()
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="API key not found."
        )
        
    try:
        cursor.execute("""
            UPDATE api_keys SET status = 'REVOKED'
            WHERE api_key_hash = ? OR api_key = ?
        """, (hash_api_key(request.api_key), request.api_key))
        conn.commit()
    except Exception as e:
        conn.rollback()
        conn.close()
        raise fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "Failed to revoke API key", e)
    conn.close()
    
    return {
        "status": "SUCCESS",
        "message": "API key successfully revoked."
    }

if __name__ == "__main__":
    import uvicorn
    # Automatically start server when script runs directly
    uvicorn.run(app, host="127.0.0.1", port=8000)