File size: 49,603 Bytes
ba25107
ef151e9
19c927e
 
ac0e05a
609d4a4
 
19c927e
609d4a4
 
 
 
19c927e
 
 
ef151e9
 
 
ac0e05a
 
ef151e9
8b8e411
 
ac0e05a
8b8e411
ef151e9
 
 
 
19c927e
609d4a4
ba25107
 
 
 
8b8e411
ef151e9
 
 
 
 
 
 
 
ac0e05a
 
ef151e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b8e411
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef151e9
 
 
 
8b8e411
61cde06
 
 
 
 
8b8e411
61cde06
ef151e9
 
61cde06
 
 
 
 
 
 
 
 
ef151e9
 
61cde06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef151e9
 
 
 
 
 
 
 
 
 
 
 
 
 
61cde06
ef151e9
61cde06
ef151e9
 
 
ac0e05a
ef151e9
ac0e05a
 
ef151e9
 
8b8e411
 
ef151e9
8b8e411
 
61b947c
ef151e9
 
 
 
ac0e05a
ef151e9
 
 
 
 
 
 
 
 
 
 
 
 
ac0e05a
 
 
 
 
 
ef151e9
 
 
 
 
19c927e
609d4a4
19c927e
 
 
 
609d4a4
 
 
 
 
19c927e
 
 
 
 
 
609d4a4
19c927e
 
609d4a4
19c927e
 
 
 
 
 
 
 
609d4a4
 
 
19c927e
609d4a4
 
 
19c927e
 
 
 
 
 
609d4a4
19c927e
 
 
 
 
 
 
 
 
 
 
609d4a4
 
19c927e
 
 
 
609d4a4
19c927e
 
609d4a4
19c927e
 
609d4a4
19c927e
 
 
 
 
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba25107
 
 
 
 
 
 
 
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
ba25107
 
ac0e05a
 
ef151e9
 
 
 
19c927e
82b7cbf
ba25107
 
19c927e
 
 
609d4a4
19c927e
609d4a4
 
 
19c927e
609d4a4
 
 
 
ac0e05a
 
 
 
 
 
 
19c927e
 
 
609d4a4
ef151e9
 
 
ac0e05a
ef151e9
609d4a4
19c927e
ac0e05a
 
19c927e
 
ac0e05a
19c927e
 
ac0e05a
ba25107
ac0e05a
 
 
 
 
 
 
61b947c
ba25107
 
 
 
 
 
 
 
 
 
 
 
 
609d4a4
 
ba25107
 
 
 
 
 
609d4a4
 
 
ba25107
609d4a4
19c927e
609d4a4
ac0e05a
ba25107
ac0e05a
 
 
 
 
 
 
 
 
609d4a4
19c927e
 
 
 
ac0e05a
 
 
 
ba25107
19c927e
 
ba25107
 
 
 
 
19c927e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba25107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7ea88e
 
 
 
19c927e
 
 
 
 
609d4a4
19c927e
 
 
 
609d4a4
19c927e
 
 
 
 
 
 
 
 
ef151e9
19c927e
 
db37ae2
19c927e
 
 
ba25107
19c927e
ba25107
19c927e
ba25107
 
 
 
 
 
 
 
19c927e
ba25107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19c927e
ba25107
 
19c927e
61b947c
ef151e9
ac0e05a
ef151e9
 
19c927e
 
 
 
ba25107
19c927e
 
 
ac0e05a
19c927e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac0e05a
 
 
 
 
 
 
19c927e
ac0e05a
19c927e
 
 
 
 
 
 
 
 
 
8b8e411
 
 
 
 
 
ac0e05a
 
 
 
19c927e
 
 
 
ba25107
ac0e05a
b2b9e82
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
8b8e411
19c927e
 
ba25107
 
19c927e
 
ba25107
 
19c927e
 
 
 
 
8b8e411
19c927e
ac0e05a
 
 
 
 
 
 
 
 
19c927e
8b8e411
 
 
ef151e9
 
8b8e411
ac0e05a
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
24978b8
ba25107
 
24978b8
ba25107
ac0e05a
 
24978b8
19c927e
 
6f99de1
609d4a4
19c927e
ac0e05a
19c927e
 
 
 
609d4a4
ef151e9
ac0e05a
ef151e9
 
19c927e
 
 
 
 
 
 
 
61b947c
19c927e
ac0e05a
b2b9e82
ba25107
ac0e05a
 
61b947c
 
19c927e
 
8b8e411
19c927e
ac0e05a
ba25107
19c927e
ba25107
 
 
 
 
 
 
 
 
 
 
 
19c927e
ac0e05a
 
ba25107
 
 
 
 
 
 
 
19c927e
 
ac0e05a
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
 
 
 
 
 
 
 
ba25107
19c927e
 
 
 
ba25107
 
19c927e
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
ba25107
 
 
ac0e05a
 
 
 
19c927e
 
ba25107
19c927e
 
 
 
 
ac0e05a
ba25107
 
19c927e
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
 
 
 
8b8e411
19c927e
ac0e05a
 
19c927e
 
ba25107
 
 
 
 
 
 
 
 
19c927e
ac0e05a
 
19c927e
ac0e05a
 
 
 
 
 
 
 
 
 
19c927e
 
ba25107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19c927e
ac0e05a
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
 
 
 
 
 
 
 
ba25107
19c927e
 
 
 
ba25107
 
19c927e
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
ba25107
 
 
ac0e05a
 
 
 
19c927e
 
ba25107
19c927e
 
 
 
 
ac0e05a
ba25107
 
19c927e
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
19c927e
 
 
 
 
ac0e05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef151e9
 
 
 
609d4a4
 
ef151e9
ac0e05a
ef151e9
ac0e05a
19c927e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Dict, Any, Tuple, List
import numpy as np
import pandas as pd
import os
import tensorflow as tf
from PIL import Image as PILImage
from PIL import ExifTags
from huggingface_hub import hf_hub_download
import io
import base64
import csv
import sqlite3
import hashlib
import secrets
import time
import uuid
from datetime import datetime
from fastapi.security import APIKeyHeader
from starlette.status import HTTP_401_UNAUTHORIZED
import json

# =============================================================================
#                               MODEL LOADING
# =============================================================================

# model token
model_key = os.getenv("hf_token")
file_path = hf_hub_download("soranz84/grai4", "04_004.h5", token=model_key)

# PSD classes for the model output (softmax)
PSD_CLASSES = ['Cl', 'fSi', 'mSi', 'cSi', 'fSa', 'mSa', 'cSa', 'fGr', 'mGr', 'cGr', 'Co']

# =============================================================================
#                               AUTH SETUP
# =============================================================================

DB_PATH = os.getenv("API_KEYS_DB_PATH", "auth.db")
API_KEY_HEADER_NAME = "x-api-key"
api_key_header = APIKeyHeader(name=API_KEY_HEADER_NAME, auto_error=False)

def get_db_connection(db_path: str = None):
    conn = sqlite3.connect(db_path or DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_db():
    conn = get_db_connection()
    try:
        conn.execute(
            """
            CREATE TABLE IF NOT EXISTS api_keys (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                key_hash TEXT NOT NULL UNIQUE,
                active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT NOT NULL
            );
            """
        )
        conn.commit()
    finally:
        conn.close()

# =============================================================================
#                           API USAGE TRACKING SETUP
# =============================================================================

# Initialize usage tracking database
USAGE_DB_PATH = os.getenv("USAGE_DB_PATH", "usage_tracking.db")

def get_usage_db_connection():
    """Get connection to the usage tracking database"""
    conn = sqlite3.connect(USAGE_DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def init_usage_db():
    """Initialize the usage tracking database"""
    conn = get_usage_db_connection()
    try:
        conn.execute(
            """
            CREATE TABLE IF NOT EXISTS api_usage (
                id TEXT PRIMARY KEY,
                api_key_hash TEXT NOT NULL,
                endpoint TEXT NOT NULL,
                timestamp REAL NOT NULL,
                user_id TEXT,
                owner TEXT,
                success BOOLEAN NOT NULL,
                response_time REAL,
                request_method TEXT,
                user_agent TEXT,
                client_ip TEXT,
                additional_data TEXT,
                image_dimensions TEXT,
                model_prediction_b REAL,
                model_prediction_c REAL
            );
            """
        )
        
        # Index for better query performance
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_api_key_hash ON api_usage(api_key_hash)"
        )
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_timestamp ON api_usage(timestamp)"
        )
        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_endpoint ON api_usage(endpoint)"
        )
        
        conn.commit()
    finally:
        conn.close()

def track_api_usage(
    api_key_hash: str,
    endpoint: str,
    request: Request,
    start_time: float,
    success: bool,
    response_time: float,
    owner: Optional[str] = None,
    additional_data: Optional[Dict] = None,
    prediction_b: Optional[float] = None,
    prediction_c: Optional[float] = None,
    image_dimensions: Optional[Dict] = None
) -> str:
    """
    Track API usage for monitoring and analytics
    
    Args:
        api_key_hash: Hash of the API key used
        endpoint: API endpoint called
        request: FastAPI request object
        start_time: When the request started (time.time())
        success: Whether the request was successful
        response_time: Time taken to complete the request
        owner: Owner of the API key
        additional_data: Additional data to store
        prediction_b: Model prediction for b factor
        prediction_c: Model prediction for c factor
        image_dimensions: Image dimensions if applicable
    """
    usage_id = str(uuid.uuid4())
    
    conn = get_usage_db_connection()
    try:
        conn.execute(
            """
            INSERT INTO api_usage (
                id, api_key_hash, endpoint, timestamp, user_id, owner, 
                success, response_time, request_method, user_agent, 
                client_ip, additional_data, model_prediction_b, 
                model_prediction_c, image_dimensions
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            (
                usage_id,
                api_key_hash,
                endpoint,
                start_time,
                str(request.state.user_id) if hasattr(request.state, 'user_id') else None,
                owner,
                success,
                response_time,
                request.method if request else None,
                request.headers.get("User-Agent") if request else None,
                request.headers.get("X-Forwarded-For", request.client.host if request and request.client else None) if request else None,
                json.dumps(additional_data or {}),
                prediction_b,
                prediction_c,
                json.dumps(image_dimensions or {})
            )
        )
        conn.commit()
    finally:
        conn.close()
    
    return usage_id

def get_usage_stats(
    api_key_hash: Optional[str] = None,
    owner: Optional[str] = None,
    time_range: Optional[tuple] = None,
    endpoint: Optional[str] = None
) -> Dict[str, Any]:
    """
    Get API usage statistics
    
    Args:
        api_key_hash: Filter by API key hash
        owner: Filter by owner
        time_range: Tuple of (start_time, end_time) timestamps
        endpoint: Filter by endpoint
    """
    conn = get_usage_db_connection()
    try:
        query = "SELECT * FROM api_usage WHERE 1=1"
        params = []
        
        if api_key_hash:
            query += " AND api_key_hash = ?"
            params.append(api_key_hash)
        
        if owner:
            query += " AND owner = ?"
            params.append(owner)
        
        if time_range:
            query += " AND timestamp BETWEEN ? AND ?"
            params.extend(time_range)
        
        if endpoint:
            query += " AND endpoint = ?"
            params.append(endpoint)
        
        query += " ORDER BY timestamp DESC"
        
        cursor = conn.execute(query, params)
        rows = cursor.fetchall()
        
        # Process results
        total_requests = len(rows)
        successful_requests = sum(1 for row in rows if row["success"])
        failed_requests = total_requests - successful_requests
        
        # Calculate statistics
        response_times = [row["response_time"] for row in rows if row["response_time"]]
        avg_response_time = sum(response_times) / len(response_times) if response_times else 0
        
        # Group by endpoint
        endpoint_stats = {}
        for row in rows:
            endpoint = row["endpoint"]
            if endpoint not in endpoint_stats:
                endpoint_stats[endpoint] = {
                    "total": 0,
                    "success": 0,
                    "failed": 0,
                    "response_times": []
                }
            
            endpoint_stats[endpoint]["total"] += 1
            endpoint_stats[endpoint]["response_times"].append(row["response_time"])
            
            if row["success"]:
                endpoint_stats[endpoint]["success"] += 1
            else:
                endpoint_stats[endpoint]["failed"] += 1
        
        # Calculate averages for each endpoint
        for endpoint, stats in endpoint_stats.items():
            response_times = stats["response_times"]
            stats["avg_response_time"] = sum(response_times) / len(response_times) if response_times else 0
            stats["success_rate"] = stats["success"] / stats["total"] if stats["total"] > 0 else 0
            del stats["response_times"]  # Remove from output
        
        # Recent activity (last 24 hours)
        day_ago = time.time() - (24 * 60 * 60)
        recent_requests = sum(1 for row in rows if row["timestamp"] > day_ago)
        
        return {
            "total_requests": total_requests,
            "successful_requests": successful_requests,
            "failed_requests": failed_requests,
            "success_rate": successful_requests / total_requests if total_requests > 0 else 0,
            "average_response_time": avg_response_time,
            "recent_requests_24h": recent_requests,
            "endpoint_statistics": endpoint_stats,
            "time_range": time_range,
            "filters": {
                "api_key_hash": api_key_hash,
                "owner": owner,
                "endpoint": endpoint
            }
        }
    finally:
        conn.close()

def get_owner_from_key_hash(api_key_hash: str) -> Optional[str]:
    """Get owner name from API key hash"""
    conn = get_db_connection()
    try:
        row = conn.execute(
            "SELECT owner FROM api_keys WHERE key_hash = ? LIMIT 1",
            (api_key_hash,)
        ).fetchone()
        return row["owner"] if row else None
    finally:
        conn.close()

# =============================================================================
#                           ENHANCED AUTH FUNCTIONS
# =============================================================================

def sha256_hex(value: str) -> str:
    return hashlib.sha256(value.encode("utf-8")).hexdigest()

def seed_api_keys_from_env():
    """
    Seed API keys from env var API_KEYS_SEED.
    Accepts entries separated by commas, newlines, semicolons, or spaces.
    Each entry must be 'owner:raw_key'. Example:
      alice:MY_SUPER_KEY_1
      bob:ANOTHER_KEY_2
    """
    seed = os.getenv("API_KEYS_SEED", "")
    if not seed:
        return

    normalized = seed.replace("\r", "\n")
    for sep in ["\n", ";", " "]:
        normalized = normalized.replace(sep, ",")

    entries = [e.strip() for e in normalized.split(",") if e.strip()]
    if not entries:
        return

    conn = get_db_connection()
    try:
        conn.execute(
            """
            CREATE TABLE IF NOT EXISTS api_keys (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                key_hash TEXT NOT NULL UNIQUE,
                active INTEGER NOT NULL DEFAULT 1,
                created_at TEXT NOT NULL
            );
            """
        )
        from datetime import datetime
        count = 0
        for entry in entries:
            if ":" not in entry:
                continue
            owner, key = entry.split(":", 1)
            owner = owner.strip()
            key = key.strip()
            if not owner or not key:
                continue
            key_hash = sha256_hex(key)
            conn.execute(
                """
                INSERT OR IGNORE INTO api_keys (owner, key_hash, active, created_at)
                VALUES (?, ?, 1, ?)
                """,
                (owner, key_hash, datetime.utcnow().isoformat(timespec="seconds")),
            )
            count += 1
        conn.commit()
        print(f"Seeded {count} API key entries from API_KEYS_SEED")
    finally:
        conn.close()

async def verify_api_key(request: Request, provided_key: Optional[str] = Depends(api_key_header)) -> str:
    """
    Enhanced dependency: verify the provided API key against the DB and store request context
    Returns the API key hash for tracking purposes
    """
    if not provided_key:
        raise HTTPException(
            status_code=HTTP_401_UNAUTHORIZED,
            detail="Missing API key",
            headers={"WWW-Authenticate": "API key"},
        )

    key_hash = sha256_hex(provided_key)
    conn = get_db_connection()
    try:
        row = conn.execute(
            "SELECT id, key_hash, active, owner FROM api_keys WHERE key_hash = ? LIMIT 1",
            (key_hash,),
        ).fetchone()
    finally:
        conn.close()

    if not row or int(row["active"]) != 1:
        # Use constant-time compare for parity (even though we already filtered by DB)
        if not row or not secrets.compare_digest(row["key_hash"], key_hash):
            raise HTTPException(
                status_code=HTTP_401_UNAUTHORIZED,
                detail="Invalid API key",
                headers={"WWW-Authenticate": "API key"},
            )
    
    # Store user context in request state for tracking
    request.state.user_id = str(row["id"])
    request.state.owner = row["owner"]
    
    return key_hash

# =============================================================================
#                           IMAGE/INFERENCE UTILITIES
# =============================================================================

# clean the camera string
def clean_exif_string(val):
    if val is None:
        return None

    # Decode bytes using a few likely encodings
    if isinstance(val, bytes):
        for enc in ("utf-8", "utf-16", "utf-16le", "latin-1"):
            try:
                val = val.decode(enc)
                break
            except Exception:
                pass
        else:
            val = val.decode("latin-1", errors="ignore")

    # Remove null padding and non-printables
    val = val.replace("\x00", "")
    val = "".join(ch for ch in val if ch.isprintable())
    return val.strip()

# find ppm and phone name 
def find_ppm_and_phone_csv(
    path: str,
    camera: str,
    w: int,
    h: int,
    phone: Optional[str] = None
) -> Tuple[Optional[float], Optional[str]]:
    cam = camera.strip().lower()
    w, h = int(w), int(h)
    phone_norm = phone.strip().lower() if phone else None

    with open(path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            cam_row = (row.get("camera", "")).strip().lower()
            if cam_row != cam:
                continue
            if phone_norm:
                if (row.get("phone", "")).strip().lower() != phone_norm:
                    continue
            try:
                rw = int(str(row.get("width", "")).strip())
                rh = int(str(row.get("height", "")).strip())
                ppm = float(str(row.get("ppm", "")).strip())
            except ValueError:
                continue

            # Orientation-independent comparison
            if (rw == w and rh == h) or (rw == h and rh == w):
                phone_name = (row.get("phone", "")).strip() or None
                return ppm, phone_name

    return None, None

# Define the Mish activation function (essential for the model)
class Mish(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super(Mish, self).__init__(**kwargs)

    def call(self, inputs):
        return inputs * tf.math.tanh(tf.math.softplus(inputs))

# Register the custom object for TensorFlow to recognize it when loading the model
tf.keras.utils.get_custom_objects().update({'Mish': Mish})

# Define a custom loss function
def custom_loss(y_true, y_pred):
    weights = np.array([0.7, 0.3])
    squared_diff = tf.square(y_true - y_pred)
    weighted_squared_diff = squared_diff * weights
    return tf.reduce_mean(weighted_squared_diff, axis=-1)

# Custom functions for TensorFlow version compatibility
def mse_metric(y_true, y_pred):
    """Mean Squared Error metric for older Keras compatibility"""
    return tf.keras.metrics.mean_squared_error(y_true, y_pred)

def mae_metric(y_true, y_pred):
    """Mean Absolute Error metric for older Keras compatibility"""
    return tf.keras.metrics.mean_absolute_error(y_true, y_pred)

# Custom DepthwiseConv2D for compatibility with different TF versions
class CompatibleDepthwiseConv2D(tf.keras.layers.DepthwiseConv2D):
    """Custom DepthwiseConv2D that handles the 'groups' parameter for different TF versions"""
    
    def __init__(self, **kwargs):
        # Remove 'groups' parameter if it exists, as it's not supported in newer TF
        kwargs.pop('groups', None)
        super().__init__(**kwargs)
    
    def call(self, inputs):
        # Call the parent method without the problematic 'groups' parameter
        return super().call(inputs)

# Edge Wasserstein Distance (EWD) loss used by grai4 model
@tf.function
def edge_wasserstein_distance(y_true, y_pred):
    """Edge Wasserstein Distance (1-Wasserstein) for probability distributions."""
    cdf_true = tf.cumsum(y_true, axis=-1)
    cdf_pred = tf.cumsum(y_pred, axis=-1)
    cdf_diff = tf.abs(cdf_true - cdf_pred)
    ewd = tf.reduce_sum(cdf_diff, axis=-1)
    return tf.reduce_mean(ewd)

# Register custom objects for model loading
tf.keras.utils.get_custom_objects().update({
    'Mish': Mish, 
    'custom_loss': custom_loss,
    'DepthwiseConv2D': CompatibleDepthwiseConv2D,
    'mse': mse_metric,
    'mae': mae_metric,
    'mean_squared_error': mse_metric,
    'mean_absolute_error': mae_metric,
    'binary_crossentropy': tf.keras.losses.binary_crossentropy,
    'categorical_crossentropy': tf.keras.losses.categorical_crossentropy,
    'edge_wasserstein_distance': edge_wasserstein_distance
})

# =============================================================================
#                               FASTAPI APP
# =============================================================================

app = FastAPI(
    title="grai Soil Analysis API",
    description="API for soil particle size distribution analysis from images (grai4 model with 11 PSD classes)",
    version="4.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Add request state middleware for tracking
@app.middleware("http")
async def add_request_state_middleware(request: Request, call_next):
    """Add request state for tracking purposes"""
    response = await call_next(request)
    return response

# Load the model once at startup
model = None

@app.on_event("startup")
async def on_startup():
    init_db()
    seed_api_keys_from_env()
    init_usage_db()  # Initialize usage tracking
    # Load ML model
    global model
    try:
        # Load model with comprehensive TensorFlow version compatibility fix
        with tf.keras.utils.custom_object_scope(tf.keras.utils.get_custom_objects()):
            model = tf.keras.models.load_model(file_path)
        print("Model loaded successfully")
        print(f"Usage tracking enabled - database: {USAGE_DB_PATH}")
    except Exception as e:
        print(f"Failed to load model: {e}")
        print("This is likely a TensorFlow version compatibility issue.")
        print("Tried to register: Mish, custom_loss, DepthwiseConv2D, mse, mae, edge_wasserstein_distance")
        print("The API will still work but image analysis will be disabled.")
        # If model loading still fails, set model to None to prevent crashes
        model = None

# =============================================================================
#                           RESPONSE MODELS
# =============================================================================

class PSDClasses(BaseModel):
    """Particle size distribution percentages for each class (softmax output)"""
    Cl: float   # Clay (<0.002 mm)
    fSi: float  # Fine silt (0.002-0.006 mm)
    mSi: float  # Medium silt (0.006-0.020 mm)
    cSi: float  # Coarse silt (0.020-0.063 mm)
    fSa: float  # Fine sand (0.063-0.200 mm)
    mSa: float  # Medium sand (0.200-0.630 mm)
    cSa: float  # Coarse sand (0.630-2.0 mm)
    fGr: float  # Fine gravel (2.0-6.3 mm)
    mGr: float  # Medium gravel (6.3-20 mm)
    cGr: float  # Coarse gravel (20-63 mm)
    Co: float   # Cobbles (>63 mm)

class SoilFractions(BaseModel):
    """Aggregate soil fractions derived from PSD classes"""
    clay: float      # = Cl
    silt: float      # = fSi + mSi + cSi
    sand: float      # = fSa + mSa + cSa
    gravel: float    # = fGr + mGr + cGr
    cobbles: float    # = Co

class AnalysisResponse(BaseModel):
    status: str
    psd: PSDClasses
    fractions: SoilFractions
    supported_device: bool
    image_dimensions: Dict[str, int]
    usage_id: str  # Track which usage record this response corresponds to
    ppm_source: Optional[str] = None  # "auto", "csv:<phone>", or "manual:<value>"

class UsageStatsResponse(BaseModel):
    total_requests: int
    successful_requests: int
    failed_requests: int
    success_rate: float
    average_response_time: float
    recent_requests_24h: int
    endpoint_statistics: Dict[str, Any]

class ErrorResponse(BaseModel):
    error: str
    details: Optional[str] = None

# =============================================================================
#                       IMAGE PROCESSING FUNCTIONS
# =============================================================================

def process_image(image: PILImage.Image, ppm_override: Optional[float] = None) -> tuple:
    """
    Process the image according to device specifications and return predictions
    
    Args:
        image: PIL Image to process
        ppm_override: If provided, use this PPM value directly instead of auto-detection.
                       When None, uses CSV lookup with 70° angle fallback (auto behavior).
    """
    width, height = image.size
    scale = 1
    supported_device = True

    # read metadata
    width, height = image.size

    camera = None

    # Pillow >= 6 supports img.getexif(); older versions use _getexif()
    raw_exif = None
    try:
        raw_exif = image.getexif()
    except Exception:
        raw_exif = getattr(image, "_getexif", lambda: None)()
    
    if raw_exif:
        exif = {}
        for tag_id, value in raw_exif.items():
            tag = ExifTags.TAGS.get(tag_id, tag_id)
            exif[tag] = value
        camera = exif.get("Model")  # camera model (tag 272)
        camera = clean_exif_string(camera)

    # find ppm and phone name:
    ppm, phone_name = (None, None)
    ppm_source = "auto"
    if ppm_override is not None:
        # Use user-provided PPM value directly
        ppm = ppm_override
        phone_name = None
        supported_device = True
        ppm_source = f"manual:{ppm_override}"
    else:
        # Auto mode: check CSV, fall back to 70° angle of view
        if camera is not None:
            ppm, phone_name = find_ppm_and_phone_csv("ppm.csv", camera, width, height)

        # handle unknown phone camera (assume 70° angle of view)
        if ppm is None:    
            ppm = max(width,height)/294.087
            supported_device = False
            ppm_source = "auto:70deg_fallback"
        else:
            ppm_source = f"csv:{phone_name or camera or 'unknown'}"
        
    # resize image to 4.6 PPM
    scale = 4.6 / ppm
    
    # Calculate new dimensions
    new_width = int(width * scale)
    new_height = int(height * scale)

    # Resize the image
    resized_image = image.resize((new_width, new_height), PILImage.Resampling.LANCZOS)

    # Crop to 400x400
    width_crop = 400
    height_crop = 400

    if resized_image.size != (width_crop, height_crop):
        width, height = resized_image.width, resized_image.height
        left = (width - width_crop) // 2
        upper = (height - height_crop) // 2
        right = left + width_crop
        lower = upper + height_crop
        cropped_image = resized_image.crop((left, upper, right, lower))
    else:
        cropped_image = resized_image

    # Split channels
    # Convert to RGB first: RGBA images (PNGs with transparency) split into 4 channels
    # and would crash the unpacking below ('too many values to unpack'). Flattening
    # onto RGB is lossless for the model (it only consumes R/G/B).
    red_channel, green_channel, blue_channel = cropped_image.convert('RGB').split()
    
    # Import channels and normalize
    red_array = np.array(red_channel)
    green_array = np.array(green_channel)
    blue_array = np.array(blue_channel)
    
    # Convert to dataframe
    red_df = pd.DataFrame(red_array)
    green_df = pd.DataFrame(green_array)
    blue_df = pd.DataFrame(blue_array)
    
    # Convert to list
    red_list = red_df.values.tolist()
    green_list = green_df.values.tolist()
    blue_list = blue_df.values.tolist()

    # Create input
    X = []
    X.append([red_list, green_list, blue_list])

    # Scale for mobilenet/efficientnet preprocessing
    X0 = np.array(X)
    X = tf.keras.applications.efficientnet_v2.preprocess_input(X0)
    
    # Transpose data
    X = tf.transpose(X, perm=[0, 2, 3, 1])

    return X, supported_device, ppm_source

def calculate_psd_and_fractions(predictions: np.ndarray) -> Dict[str, Any]:
    """
    Calculate PSD class percentages and aggregate fractions from model predictions.
    
    The model outputs a softmax distribution over PSD_CLASSES:
    ['Cl', 'fSi', 'mSi', 'cSi', 'fSa', 'mSa', 'cSa', 'fGr', 'mGr', 'cGr', 'Co']
    
    Returns a dict with:
      - "psd": dict mapping each class name to its percentage (0-100)
      - "fractions": dict with aggregate fractions (clay, silt, sand, gravel, cobbles)
    """
    # predictions shape: (1, 11) or (11,)
    pred = predictions[0] if predictions.ndim > 1 else predictions
    
    # Build PSD percentages (convert from 0-1 to 0-100)
    psd = {}
    for i, cls in enumerate(PSD_CLASSES):
        psd[cls] = round(float(pred[i]) * 100, 1)
    
    # Compute aggregate fractions
    fractions = {
        "clay":    round(psd["Cl"], 1),
        "silt":    round(psd["fSi"] + psd["mSi"] + psd["cSi"], 1),
        "sand":    round(psd["fSa"] + psd["mSa"] + psd["cSa"], 1),
        "gravel":  round(psd["fGr"] + psd["mGr"] + psd["cGr"], 1),
        "cobbles":  round(psd["Co"], 1)
    }
    
    return {
        "psd": psd,
        "fractions": fractions
    }

# =============================================================================
#                           HTML LANDING PAGE
# =============================================================================

HTML_CONTENT = """
<!DOCTYPE html>
<html>
<head>
    <title>grai Soil Analysis API v4.0</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #2F4F4F;
        }
        .endpoints {
            background-color: #f0f0f0;
            padding: 15px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .endpoint {
            margin: 10px 0;
            padding: 10px;
            background-color: white;
            border-left: 4px solid #297FD5;
        }
        .usage-tracking {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        code {
            background-color: #808080;
            padding: 2px 6px;
            border-radius: 3px;
        }
        a {
            color: #297FD5;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        .note {
            background-color: #fff8e1;
            border-left: 4px solid #f9a825;
            padding: 10px;
            margin-top: 20px;
        }
        .stats-endpoint {
            background-color: #e8f5e8;
            border-left: 4px solid #4caf50;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔵🔵🔵 grai Soil Analysis API - v4.0</h1>
        <p>API for soil particle size distribution analysis from images with usage tracking</p>
        <p>Powered by <strong>grai4</strong> model — outputs 11 PSD classes (softmax) for fine-grained particle size distribution</p>
        <p>Developed by <a href="mailto:enrico@deepsoil.at">Enrico Soranzo</a></p>
        
        <div class="usage-tracking">
            <h3>📊 Usage Tracking Enabled</h3>
            <p>This API now includes comprehensive usage tracking:</p>
            <ul>
                <li>Track API key usage patterns</li>
                <li>Monitor response times and success rates</li>
                <li>Access detailed analytics via <code>/usage-stats</code> endpoint</li>
                <li>Secure storage with API key hash tracking</li>
            </ul>
        </div>
        
        <div class="endpoints">
            <h2>Available Endpoints</h2>
            <div class="endpoint">
                <strong>GET /</strong> - This page (public)
            </div>
            <div class="endpoint">
                <strong>POST /analyze</strong> - Analyze soil image (multipart/form-data) [requires x-api-key]<br>
                &nbsp;&nbsp;&nbsp;Optional form field: <code>ppm</code> — <code>auto</code> (default) or numeric value (e.g. <code>15.0</code>)
            </div>
            <div class="endpoint">
                <strong>POST /analyze_base64</strong> - Analyze base64 encoded image [requires x-api-key]<br>
                &nbsp;&nbsp;&nbsp;Optional data field: <code>ppm</code> — <code>auto</code> (default) or numeric value
            </div>
            <div class="endpoint">
                <strong>GET /docs</strong> - <a href="/docs">Interactive API Documentation</a>
            </div>
            <div class="endpoint">
                <strong>GET /health</strong> - Health check (public)
            </div>
            <div class="endpoint stats-endpoint">
                <strong>GET /usage-stats?api_key=YOUR_KEY</strong> - Get usage statistics for your API key
            </div>
            <div class="endpoint stats-endpoint">
                <strong>GET /owner-stats?owner=username</strong> - Get usage statistics for an owner
            </div>
            <div class="endpoint stats-endpoint">
                <strong>GET /admin/stats</strong> - Admin endpoint to get overall statistics (requires special key)
            </div>
        </div>

        <div class="note">
            <strong>Authentication:</strong> Protected endpoints require the header <code>x-api-key: YOUR_KEY</code>.
            Add API keys to the database or set environment variable <code>API_KEYS_SEED</code> on startup:
            <code>API_KEYS_SEED="alice:KEY1,bob:KEY2"</code>.
        </div>

        <div class="usage-tracking">
            <h3>📈 New Usage Statistics Features</h3>
            <p>Monitor your API usage with these new endpoints:</p>
            <ul>
                <li><code>/usage-stats?api_key=KEY</code> - Your usage statistics</li>
                <li><code>/owner-stats?owner=alice</code> - Statistics by owner (requires admin access)</li>
                <li><code>/admin/stats</code> - Overall system statistics</li>
            </ul>
            <p>All statistics include request counts, success rates, response times, and endpoint breakdowns.</p>
        </div>
        
        <h2>Quick Start</h2>
        <p>Upload an image using cURL:</p>
        <code>curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" https://soranz84-graiAPI.hf.space/analyze</code>

        <h3>Custom PPM (pixel density) override:</h3>
        <code>curl -X POST -H "x-api-key: API_KEY" -F "file=@soil_image.jpeg" -F "ppm=15.0" https://soranz84-graiAPI.hf.space/analyze</code>
        <p>Use <code>ppm=auto</code> (default) for automatic detection from EXIF/CSV with 70° angle fallback, or provide a numeric value to set the pixel density (pixels per mm) directly.</p>

        <h3>Get your usage statistics:</h3>
        <code>curl -H "x-api-key: API_KEY" https://soranz84-graiAPI.hf.space/usage-stats?api_key=API_KEY</code>
        
        <h2>Recommended Devices</h2>
        <p>HUAWEI_p9_Lite_20177, iPad Pro, iPhone 13 mini, iPhone 14, iPhone 14 Pro, iPhone 15 Pro, iPhone 16, iPhone 16 Pro, Motorola Edge, Motorola Edge 60 fusion, Motorola G7+, Motorola G30, Samsung Galaxy A17, Samsung Galaxy A32, Samsung A52, Samsung Galaxy S23, Samsung Galaxy S24, Vivo X60, Xiaomi 15, Xiaomi A2<p>
    
        <h2>Other Devices</h2>
        <p>grai is device-agnostic. An angle of view of 70° is assumed for uncalibrated devices. You can write to <a href="mailto:enrico@deepsoil.at">enrico@deepsoil.at</a> to update the list of calibrated devices.</p>
    </div>
</body>
</html>
"""

# =============================================================================
#                               API ROUTES
# =============================================================================

@app.get("/", response_class=HTMLResponse)
async def root():
    """Landing page with API information"""
    return HTML_CONTENT

@app.get("/health")
async def health():
    """Health check endpoint"""
    return {
        "status": "healthy",
        "model_loaded": model is not None,
        "model_version": "grai-04_004",
        "psd_classes": PSD_CLASSES,
        "usage_tracking": True,
        "usage_db_path": USAGE_DB_PATH
    }

@app.post("/analyze", response_model=AnalysisResponse, responses={
    400: {"model": ErrorResponse, "description": "Bad Request"},
    401: {"model": ErrorResponse, "description": "Unauthorized"},
    500: {"model": ErrorResponse, "description": "Internal Server Error"}
})
async def analyze_soil_image(request: Request, file: UploadFile = File(...), ppm: Optional[str] = Form("auto"), api_key_hash: str = Depends(verify_api_key)):
    """
    Analyze a soil image and return particle size distribution (PSD) for 11 classes.
    
    The model outputs a softmax distribution over these PSD classes:
    Cl, fSi, mSi, cSi, fSa, mSa, cSa, fGr, mGr, cGr, Co
    
    Aggregate fractions (clay, silt, sand, gravel, cobbles) are also returned.
    
    Args:
        file: Image file to analyze
        ppm: Pixel density (pixels per mm). Use "auto" (default) for automatic detection 
             from EXIF/CSV lookup with 70° angle fallback, or provide a numeric value 
             (e.g. "15.0") to use a specific PPM for scaling.
    """
    start_time = time.time()
    
    # Parse ppm parameter
    ppm_override = None
    if ppm is not None and ppm.strip().lower() != "auto":
        try:
            ppm_override = float(ppm.strip())
        except ValueError:
            raise HTTPException(status_code=400, detail=f"Invalid ppm value: '{ppm}'. Must be 'auto' or a numeric value.")
    
    # Validate file type
    if not file.content_type or not file.content_type.startswith("image/"):
        # Track failed request
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze",
            request=request,
            start_time=start_time,
            success=False,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": "Invalid file type", "content_type": file.content_type}
        )
        raise HTTPException(status_code=400, detail="File must be an image")
    
    if model is None:
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze",
            request=request,
            start_time=start_time,
            success=False,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": "Model not loaded"}
        )
        raise HTTPException(status_code=500, detail="Model not loaded")
    
    try:
        # Read image file
        contents = await file.read()
        image = PILImage.open(io.BytesIO(contents))
        
        # Get original dimensions
        original_width, original_height = image.size
        
        # Process image
        X, supported_device, ppm_source = process_image(image, ppm_override=ppm_override)
        
        # Make prediction
        predictions = model.predict(X, verbose=0)
        
        # Calculate PSD classes and aggregate fractions
        results = calculate_psd_and_fractions(predictions)
        
        # Track successful usage
        usage_id = track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze",
            request=request,
            start_time=start_time,
            success=True,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={
                "file_size": len(contents),
                "image_mode": image.mode,
                "file_format": getattr(file, 'filename', 'unknown'),
                "ppm_source": ppm_source,
                "psd": results["psd"]
            },
            image_dimensions={"width": original_width, "height": original_height}
        )
        
        return AnalysisResponse(
            status="success",
            psd=PSDClasses(**results["psd"]),
            fractions=SoilFractions(**results["fractions"]),
            supported_device=supported_device,
            image_dimensions={
                "width": original_width,
                "height": original_height
            },
            usage_id=usage_id,
            ppm_source=ppm_source
        )
        
    except Exception as e:
        response_time = time.time() - start_time
        # Track failed usage
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze",
            request=request,
            start_time=start_time,
            success=False,
            response_time=response_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": str(e), "error_type": type(e).__name__}
        )
        raise HTTPException(
            status_code=500,
            detail=f"Error processing image: {str(e)}"
        )

@app.post("/analyze_base64", response_model=AnalysisResponse, responses={
    400: {"model": ErrorResponse, "description": "Bad Request"},
    401: {"model": ErrorResponse, "description": "Unauthorized"},
    500: {"model": ErrorResponse, "description": "Internal Server Error"}
})
async def analyze_soil_image_base64(request: Request, data: Dict[str, str], api_key_hash: str = Depends(verify_api_key)):
    """
    Analyze a soil image provided as base64 string.
    
    The model outputs a softmax distribution over 11 PSD classes:
    Cl, fSi, mSi, cSi, fSa, mSa, cSa, fGr, mGr, cGr, Co
    
    Aggregate fractions (clay, silt, sand, gravel, cobbles) are also returned.
    
    The data dict can optionally include a 'ppm' field:
    - "auto" (default if omitted): automatic detection from EXIF/CSV with 70° angle fallback
    - A numeric string (e.g. "15.0"): use this PPM value directly for scaling
    """
    start_time = time.time()
    
    if "image" not in data:
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze_base64",
            request=request,
            start_time=start_time,
            success=False,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": "Missing image field"}
        )
        raise HTTPException(status_code=400, detail="Missing 'image' field in request")
    
    # Parse ppm parameter from data dict
    ppm_override = None
    ppm_value = data.get("ppm", "auto")
    if ppm_value is not None and ppm_value.strip().lower() != "auto":
        try:
            ppm_override = float(ppm_value.strip())
        except ValueError:
            track_api_usage(
                api_key_hash=api_key_hash,
                endpoint="/analyze_base64",
                request=request,
                start_time=start_time,
                success=False,
                response_time=time.time() - start_time,
                owner=getattr(request.state, 'owner', None),
                additional_data={"error": "Invalid ppm value"}
            )
            raise HTTPException(status_code=400, detail=f"Invalid ppm value: '{ppm_value}'. Must be 'auto' or a numeric value.")
    
    if model is None:
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze_base64",
            request=request,
            start_time=start_time,
            success=False,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": "Model not loaded"}
        )
        raise HTTPException(status_code=500, detail="Model not loaded")
    
    try:
        # Decode base64 image
        image_data = base64.b64decode(data["image"])
        image = PILImage.open(io.BytesIO(image_data))
        
        # Get original dimensions
        original_width, original_height = image.size
        
        # Process image
        X, supported_device, ppm_source = process_image(image, ppm_override=ppm_override)
        
        # Make prediction
        predictions = model.predict(X, verbose=0)
        
        # Calculate PSD classes and aggregate fractions
        results = calculate_psd_and_fractions(predictions)
        
        # Track successful usage
        usage_id = track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze_base64",
            request=request,
            start_time=start_time,
            success=True,
            response_time=time.time() - start_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={
                "data_size": len(data["image"]),
                "image_mode": image.mode,
                "estimated_file_size": len(image_data),
                "ppm_source": ppm_source,
                "psd": results["psd"]
            },
            image_dimensions={"width": original_width, "height": original_height}
        )
        
        return AnalysisResponse(
            status="success",
            psd=PSDClasses(**results["psd"]),
            fractions=SoilFractions(**results["fractions"]),
            supported_device=supported_device,
            image_dimensions={
                "width": original_width,
                "height": original_height
            },
            usage_id=usage_id,
            ppm_source=ppm_source
        )
        
    except Exception as e:
        response_time = time.time() - start_time
        # Track failed usage
        track_api_usage(
            api_key_hash=api_key_hash,
            endpoint="/analyze_base64",
            request=request,
            start_time=start_time,
            success=False,
            response_time=response_time,
            owner=getattr(request.state, 'owner', None),
            additional_data={"error": str(e), "error_type": type(e).__name__}
        )
        raise HTTPException(
            status_code=500,
            detail=f"Error processing image: {str(e)}"
        )

# =============================================================================
#                           USAGE STATISTICS ENDPOINTS
# =============================================================================

class UsageStatsResponse(BaseModel):
    total_requests: int
    successful_requests: int
    failed_requests: int
    success_rate: float
    average_response_time: float
    recent_requests_24h: int
    endpoint_statistics: Dict[str, Any]

@app.get("/usage-stats", response_model=UsageStatsResponse)
async def get_usage_stats_endpoint(request: Request, api_key: Optional[str] = None, 
                                   hours: Optional[int] = 24, owner: Optional[str] = None):
    """
    Get usage statistics for a specific API key or owner
    
    Args:
        api_key: API key to get statistics for (requires same owner access)
        hours: Number of hours to look back (default: 24)
        owner: Owner name filter (for admin access)
    """
    
    # Get requesting user's API key hash if no specific key provided
    request_header_key = request.headers.get("x-api-key")
    
    request_key_hash = None
    if request_header_key:
        request_key_hash = sha256_hex(request_header_key)
    
    # Calculate time range
    end_time = time.time()
    start_time = end_time - (hours * 60 * 60)
    
    # Security check: ensure proper access
    if api_key:
        # User is requesting stats for a specific API key
        requested_key_hash = sha256_hex(api_key)
        
        # Get owner of requested key
        requested_owner = get_owner_from_key_hash(requested_key_hash)
        requested_api_key_owner = None
        
        if request_key_hash:
            requested_api_key_owner = get_owner_from_key_hash(request_key_hash)
        
        # Check if user owns the requested key or is admin
        if request_key_hash != requested_key_hash and requested_api_key_owner != requested_owner:
            # Not the same key owner - deny access
            pass  # This will cause the stats query to return empty
        
    # Get statistics
    stats = get_usage_stats(
        api_key_hash=sha256_hex(api_key) if api_key else request_key_hash,
        owner=owner,
        time_range=(start_time, end_time)
    )
    
    return UsageStatsResponse(**stats)

@app.get("/owner-stats")
async def get_owner_usage_stats(request: Request, owner: str, hours: Optional[int] = 24):
    """
    Get usage statistics for a specific owner
    Requires the requesting user to have the same owner or be an admin
    """
    request_header_key = request.headers.get("x-api-key")
    if not request_header_key:
        raise HTTPException(status_code=401, detail="API key required")
    
    request_key_hash = sha256_hex(request_header_key)
    request_owner = get_owner_from_key_hash(request_key_hash)
    target_owner = owner
    
    # Check if user has access to this owner's stats
    if request_owner != target_owner and request_owner != "admin":  # Add admin check if needed
        raise HTTPException(status_code=403, detail="Not authorized to view this owner's stats")
    
    # Calculate time range
    end_time = time.time()
    start_time = end_time - (hours * 60 * 60)
    
    stats = get_usage_stats(
        owner=target_owner,
        time_range=(start_time, end_time)
    )
    
    return stats

@app.get("/admin/stats")
async def get_admin_stats(request: Request, hours: Optional[int] = 24):
    """
    Get overall system usage statistics (admin only)
    """
    request_header_key = request.headers.get("x-api-key")
    if not request_header_key:
        raise HTTPException(status_code=401, detail="API key required")
    
    request_key_hash = sha256_hex(request_header_key)
    request_owner = get_owner_from_key_hash(request_key_hash)
    
    # Simple admin check - in production, use proper admin roles
    if request_owner != "admin":
        raise HTTPException(status_code=403, detail="Admin access required")
    
    # Calculate time range
    end_time = time.time()
    start_time = end_time - (hours * 60 * 60)
    
    stats = get_usage_stats(time_range=(start_time, end_time))
    
    # Add additional admin-only information
    conn = get_usage_db_connection()
    try:
        cursor = conn.execute(
            "SELECT COUNT(DISTINCT api_key_hash) as unique_users FROM api_usage WHERE timestamp > ?",
            (start_time,)
        )
        unique_users = cursor.fetchone()["unique_users"]
        
        # Get most active users
        cursor = conn.execute(
            """
            SELECT owner, COUNT(*) as request_count 
            FROM api_usage 
            WHERE timestamp > ? 
            GROUP BY owner 
            ORDER BY request_count DESC 
            LIMIT 5
            """,
            (start_time,)
        )
        most_active = [dict(row) for row in cursor.fetchall()]
        
        stats["admin_data"] = {
            "unique_users_24h": unique_users,
            "most_active_users": most_active
        }
    finally:
        conn.close()
    
    return stats

# =============================================================================
#                               MAIN
# =============================================================================

if __name__ == "__main__":
    import uvicorn
    # Optional seed of API keys (example):
    # export API_KEYS_SEED="alice:KEY1,bob:KEY2,admin:ADMIN_KEY"
    # Keys are stored hashed (SHA-256) in SQLite at auth.db (or API_KEYS_DB_PATH).
    # Usage tracking data is stored in usage_tracking.db (or USAGE_DB_PATH).
    uvicorn.run(app, host="0.0.0.0", port=7860)