File size: 42,534 Bytes
a27587f
2fcae50
 
a27587f
 
1455aca
a27587f
 
 
2fcae50
a27587f
 
d06b99c
a27587f
d06b99c
a27587f
2fcae50
ee85faa
a27587f
2fcae50
 
 
a27587f
55932c9
ca371b2
a27587f
 
 
 
 
 
 
 
 
2fcae50
c296d70
2fcae50
a27587f
 
 
 
2fcae50
a27587f
2fcae50
 
 
a27587f
 
 
 
2fcae50
a27587f
 
 
 
 
 
 
 
 
 
 
2fcae50
 
 
a27587f
ca371b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecadd5a
a3d7db1
 
 
 
ca371b2
 
d69ea55
 
ca371b2
d69ea55
 
 
 
 
 
 
 
ca371b2
d69ea55
ca371b2
 
 
 
 
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca371b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
a27587f
3b7a305
a27587f
 
 
7f8f9a6
3b7a305
 
a27587f
3b7a305
a27587f
3b7a305
 
 
 
 
 
a27587f
2fcae50
a27587f
2fcae50
a27587f
 
 
3b7a305
a27587f
 
7f8f9a6
3b7a305
2fcae50
 
 
7f8f9a6
 
3b7a305
2fcae50
 
3b7a305
2fcae50
3b7a305
 
0a6dddb
3b7a305
 
0a6dddb
 
 
 
 
 
3b7a305
 
 
 
 
 
 
2fcae50
3b7a305
 
0a6dddb
3b7a305
 
0a6dddb
 
 
 
 
 
3b7a305
 
 
 
 
 
 
2fcae50
3b7a305
 
0a6dddb
3b7a305
 
0a6dddb
 
 
 
 
 
3b7a305
 
 
 
2fcae50
3b7a305
a27587f
 
 
3b7a305
 
 
7f8f9a6
3b7a305
 
 
 
7f8f9a6
 
3b7a305
 
 
 
 
 
a27587f
 
2fcae50
 
 
 
4b38699
3c631de
2fcae50
3c631de
3f9ec34
3c631de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f9ec34
 
3c631de
 
2fcae50
6f15ebd
a27587f
2fcae50
a27587f
 
 
 
2fcae50
 
 
3c631de
 
 
 
 
a27587f
3c631de
 
2fcae50
3c631de
a27587f
2fcae50
3c631de
 
 
 
 
a27587f
 
 
2fcae50
 
 
 
 
a27587f
 
ca371b2
 
d69ea55
ca371b2
 
 
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca371b2
 
 
 
d69ea55
 
 
 
 
 
 
 
 
 
 
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
ca371b2
 
a3d7db1
ca371b2
 
 
 
 
 
 
 
 
d69ea55
ca371b2
d69ea55
 
ca371b2
 
 
d69ea55
 
 
 
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
ca371b2
d69ea55
 
 
 
 
 
 
 
ca371b2
 
 
 
 
 
 
 
 
 
 
 
2fcae50
3170c04
37426c6
 
 
 
 
 
3170c04
 
 
 
 
 
 
 
ca371b2
 
 
 
 
 
 
 
 
 
 
a27587f
eee83a0
37426c6
ca371b2
a3d7db1
37426c6
ca371b2
37426c6
ca371b2
37426c6
65bbbc0
50e2e6d
 
65bbbc0
a27587f
 
 
 
 
65bbbc0
a27587f
65bbbc0
 
37426c6
50e2e6d
 
37426c6
50e2e6d
 
 
 
 
 
65bbbc0
50e2e6d
c7060a1
eee83a0
ca371b2
 
 
a3d7db1
37426c6
ca371b2
37426c6
ca371b2
2fcae50
f029b18
6395222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f75a344
6395222
 
 
 
 
f75a344
6395222
f75a344
6395222
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f029b18
2fcae50
 
a27587f
 
 
 
 
ca371b2
a27587f
2fcae50
a27587f
 
 
 
 
 
 
 
 
 
2fcae50
a27587f
d06b99c
2fcae50
a26c316
 
 
2fcae50
d06b99c
 
 
 
a27587f
 
2fcae50
a27587f
 
2fcae50
a3d7db1
 
a27587f
a3d7db1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
 
 
ca371b2
 
 
2fcae50
d06b99c
2fcae50
 
 
 
 
 
 
a3d7db1
 
a27587f
 
2fcae50
a27587f
 
 
ca371b2
a27587f
 
d06b99c
2fcae50
 
 
 
 
 
 
 
 
 
 
a27587f
 
 
 
2fcae50
a27587f
 
 
ca371b2
a27587f
 
ca371b2
 
 
 
d06b99c
ca371b2
 
 
 
 
 
d69ea55
 
ca371b2
d69ea55
 
 
 
ca371b2
d69ea55
ca371b2
 
 
 
 
2fcae50
 
 
 
 
 
 
 
 
 
df236f5
d06b99c
2fcae50
 
 
 
 
 
 
a27587f
 
 
 
2fcae50
a27587f
 
 
ca371b2
a27587f
 
ca371b2
 
 
2fcae50
d06b99c
2fcae50
 
 
 
 
 
 
d69ea55
 
ca371b2
d69ea55
 
 
 
ca371b2
d69ea55
ca371b2
 
 
 
 
2fcae50
d06b99c
2fcae50
 
 
 
 
 
 
6f15ebd
2fcae50
 
 
 
 
 
 
 
a27587f
 
 
 
2fcae50
a27587f
 
6a5c5e3
 
 
 
ca371b2
a3d7db1
6a5c5e3
a3d7db1
6a5c5e3
 
2fcae50
6a5c5e3
 
 
 
 
 
 
 
 
 
a3d7db1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
 
6a5c5e3
2fcae50
 
6a5c5e3
2fcae50
6a5c5e3
 
2fcae50
6a5c5e3
2fcae50
 
 
 
6a5c5e3
 
a3d7db1
 
6a5c5e3
 
2fcae50
6a5c5e3
 
 
a3d7db1
 
6a5c5e3
 
2fcae50
6a5c5e3
 
a3d7db1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
 
6a5c5e3
2fcae50
 
6a5c5e3
2fcae50
6a5c5e3
 
2fcae50
 
 
 
 
6a5c5e3
 
a3d7db1
 
6a5c5e3
 
2fcae50
6a5c5e3
 
2fcae50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a5c5e3
 
2fcae50
6a5c5e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
 
 
 
 
 
 
 
 
 
 
 
 
 
7f8f9a6
 
 
2fcae50
 
 
 
 
 
 
 
 
55932c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f8f9a6
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f8f9a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df236f5
 
 
 
7f8f9a6
 
df236f5
7f8f9a6
 
 
 
 
 
 
0dbb26a
 
 
 
 
 
 
 
71240dc
 
 
 
 
 
 
 
 
 
0dbb26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fcae50
1455aca
 
2fcae50
 
 
 
 
 
 
 
 
 
a27587f
 
 
 
ef3133a
a27587f
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
"""
TreeTrack FastAPI Application - Supabase Edition
Clean implementation using Supabase Postgres + Storage
"""

import json
import logging
import time
from datetime import datetime
from typing import Any, Optional, List, Dict

import uvicorn
from fastapi import FastAPI, HTTPException, Request, status, File, UploadFile, Form, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, field_validator
import os

# Import our Supabase components
from supabase_database import SupabaseDatabase
from supabase_storage import SupabaseFileStorage
from config import get_settings
from master_tree_database import create_master_tree_database, get_tree_suggestions, get_all_tree_codes
from auth import auth_manager

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.FileHandler("app.log"), logging.StreamHandler()],
)
logger = logging.getLogger(__name__)

# Log startup
build_time = os.environ.get('BUILD_TIME', 'unknown')
logger.info(f"TreeTrack Supabase Edition starting - Build time: {build_time}")

# Get configuration settings
settings = get_settings()

# Initialize FastAPI app
app = FastAPI(
    title="TreeTrack - Supabase Edition",
    description="Tree mapping and tracking with persistent cloud storage",
    version="3.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.security.cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE"],
    allow_headers=["*"],
)

# Serve static files
app.mount("/static", StaticFiles(directory="static"), name="static")

# Initialize Supabase components
db = SupabaseDatabase()
storage = SupabaseFileStorage()

# Authentication models
class LoginRequest(BaseModel):
    username: str
    password: str

class LoginResponse(BaseModel):
    token: str
    user: Dict[str, Any]

class UserInfo(BaseModel):
    username: str
    role: str
    full_name: str
    permissions: List[str]

class DemoLoginResponse(BaseModel):
    token: str
    user: Dict[str, Any]
    is_demo_mode: bool = True

# Helper function for authentication
def get_current_user(request: Request) -> Optional[Dict[str, Any]]:
    """Extract user info from request headers or cookies"""
    # Try Authorization header first (for API calls)
    auth_header = request.headers.get('Authorization')
    if auth_header and auth_header.startswith('Bearer '):
        token = auth_header.split(' ')[1]
        return auth_manager.validate_session(token)
    
    # Try cookie for web page requests
    auth_cookie = request.cookies.get('auth_token')
    if auth_cookie:
        return auth_manager.validate_session(auth_cookie)
    
    return None

def require_auth(request: Request) -> Dict[str, Any]:
    """Dependency that requires authentication"""
    user = get_current_user(request)
    if not user:
        # Server-side auth telemetry for unauthorized access
        try:
            _record_server_telemetry(
                request=request,
                event_type='auth',
                status='unauthorized',
                metadata={
                    'path': str(request.url),
                    'method': request.method,
                    'has_auth_header': bool(request.headers.get('Authorization'))
                },
                user=None
            )
        except Exception:
            pass
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication required",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return user

def require_permission(permission: str):
    """Dependency factory for specific permissions"""
    def check_permission(request: Request) -> Dict[str, Any]:
        user = require_auth(request)
        if permission not in user.get('permissions', []):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Permission '{permission}' required"
            )
        return user
    return check_permission

# Pydantic models (same as before)
class Tree(BaseModel):
    """Complete tree model with all 12 fields"""
    id: int
    latitude: float
    longitude: float
    location_name: Optional[str] = None
    local_name: Optional[str] = None
    scientific_name: Optional[str] = None
    common_name: Optional[str] = None
    tree_code: Optional[str] = None
    height: Optional[float] = None
    width: Optional[float] = None
    utility: Optional[List[str]] = None
    storytelling_text: Optional[str] = None
    storytelling_audio: Optional[str] = None
    phenology_stages: Optional[List[str]] = None
    photographs: Optional[Dict[str, str]] = None
    notes: Optional[str] = None
    created_at: str
    updated_at: Optional[str] = None
    created_by: str = "system"


class TreeCreate(BaseModel):
    """Model for creating new tree records"""
    latitude: float = Field(..., ge=-90, le=90, description="Latitude in decimal degrees")
    longitude: float = Field(..., ge=-180, le=180, description="Longitude in decimal degrees")
    location_name: Optional[str] = Field(None, max_length=200, description="Human-readable location (e.g., landmark)")
    local_name: Optional[str] = Field(None, max_length=200, description="Local Assamese name")
    scientific_name: Optional[str] = Field(None, max_length=200, description="Scientific name")
    common_name: Optional[str] = Field(None, max_length=200, description="Common name")
    tree_code: Optional[str] = Field(None, max_length=20, description="Tree reference code")
    height: Optional[float] = Field(None, gt=0, le=1000, description="Height in feet (ft)")
    width: Optional[float] = Field(None, gt=0, le=200, description="Girth/DBH in feet (ft)")
    utility: Optional[List[str]] = Field(None, description="Ecological/cultural utilities")
    storytelling_text: Optional[str] = Field(None, max_length=5000, description="Stories and narratives")
    storytelling_audio: Optional[str] = Field(None, description="Audio file path")
    phenology_stages: Optional[List[str]] = Field(None, description="Current development stages")
    photographs: Optional[Dict[str, str]] = Field(None, description="Photo categories and paths")
    notes: Optional[str] = Field(None, max_length=2000, description="Additional observations")

    @field_validator("utility", mode='before')
    @classmethod
    def validate_utility(cls, v):
        if isinstance(v, str):
            try:
                v = json.loads(v)
            except json.JSONDecodeError:
                raise ValueError(f"Invalid JSON string for utility: {v}")
        
        if v is not None:
            valid_utilities = [
                "Religious", "Timber", "Biodiversity", "Hydrological benefit", 
                "Faunal interaction", "Food", "Medicine", "Shelter", "Cultural"
            ]
            for item in v:
                if item not in valid_utilities:
                    raise ValueError(f"Invalid utility: {item}")
        return v

    @field_validator("phenology_stages", mode='before')
    @classmethod
    def validate_phenology(cls, v):
        if isinstance(v, str):
            try:
                v = json.loads(v)
            except json.JSONDecodeError:
                raise ValueError(f"Invalid JSON string for phenology_stages: {v}")
        
        if v is not None:
            valid_stages = [
                "New leaves", "Old leaves", "Open flowers", "Fruiting", 
                "Ripe fruit", "Recent fruit drop", "Other"
            ]
            for stage in v:
                if stage not in valid_stages:
                    raise ValueError(f"Invalid phenology stage: {stage}")
        return v

    @field_validator("photographs", mode='before')
    @classmethod
    def validate_photographs(cls, v):
        if isinstance(v, str):
            try:
                v = json.loads(v)
            except json.JSONDecodeError:
                raise ValueError(f"Invalid JSON string for photographs: {v}")
        
        if v is not None:
            valid_categories = ["Leaf", "Bark", "Fruit", "Seed", "Flower", "Full tree"]
            for category in v.keys():
                if category not in valid_categories:
                    raise ValueError(f"Invalid photo category: {category}")
        return v


class TreeUpdate(BaseModel):
    """Model for updating tree records"""
    latitude: Optional[float] = Field(None, ge=-90, le=90)
    longitude: Optional[float] = Field(None, ge=-180, le=180)
    location_name: Optional[str] = Field(None, max_length=200)
    local_name: Optional[str] = Field(None, max_length=200)
    scientific_name: Optional[str] = Field(None, max_length=200)
    common_name: Optional[str] = Field(None, max_length=200)
    tree_code: Optional[str] = Field(None, max_length=20)
    height: Optional[float] = Field(None, gt=0, le=1000)
    width: Optional[float] = Field(None, gt=0, le=200)
    utility: Optional[List[str]] = None
    storytelling_text: Optional[str] = Field(None, max_length=5000)
    storytelling_audio: Optional[str] = None
    phenology_stages: Optional[List[str]] = None
    photographs: Optional[Dict[str, str]] = None
    notes: Optional[str] = Field(None, max_length=2000)


# Application startup
@app.on_event("startup")
async def startup_event():
    """Initialize application"""
    try:
        # Initialize master tree database (always works - local SQLite)
        create_master_tree_database()
        logger.info("Master tree database initialized with 146 species")
        
        # Test Supabase connection (non-blocking)
        try:
            if db.test_connection():
                # Initialize database schema if connection works
                db.initialize_database()
                
                # Log success
                tree_count = db.get_tree_count()
                logger.info(f"TreeTrack Supabase Edition initialized - {tree_count} trees in database")
            else:
                logger.warning("Supabase connection failed - running in limited mode")
                logger.warning("Database operations will fail until Supabase is configured")
        except Exception as db_error:
            logger.error(f"Supabase connection error: {db_error}")
            logger.warning("App starting in limited mode - only master tree database available")
        
        logger.info("TreeTrack application startup complete")
        
    except Exception as e:
        logger.error(f"Critical application startup failed: {e}")
        # Only fail if master database fails (shouldn't happen)
        raise


# Health check
@app.get("/health", tags=["Health"])
async def health_check():
    """Health check endpoint"""
    try:
        connection_ok = db.test_connection()
        tree_count = db.get_tree_count() if connection_ok else 0
        
        # Include environment debug info
        import os
        supabase_url = os.getenv("SUPABASE_URL", "NOT_SET")
        supabase_anon_key = os.getenv("SUPABASE_ANON_KEY", "NOT_SET")
        
        return {
            "status": "healthy" if connection_ok else "limited",
            "database": "connected" if connection_ok else "disconnected", 
            "trees": tree_count,
            "master_database": "available",
            "timestamp": datetime.now().isoformat(),
            "version": "3.0.0",
            "environment": {
                "supabase_url": supabase_url[:50] + "..." if len(supabase_url) > 50 else supabase_url,
                "supabase_anon_key": "SET" if supabase_anon_key != "NOT_SET" else "NOT_SET",
                "port": os.getenv("PORT", "7860")
            }
        }
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        return {
            "status": "unhealthy",
            "error": str(e),
            "timestamp": datetime.now().isoformat(),
        }


# Authentication routes
@app.post("/api/auth/login", response_model=LoginResponse, tags=["Authentication"])
async def login(login_data: LoginRequest, response: Response):
    """Authenticate user and create session"""
    result = auth_manager.authenticate(login_data.username, login_data.password)
    if not result:
        # Telemetry: login failure
        try:
            # Construct a minimal request-like object for _record_server_telemetry if needed
            from fastapi import Request as _Req
        except Exception:
            pass
        # We have the real request inside FastAPI dependency; emulate via middleware not needed here
        # Instead, log via logger for this path
        # Note: We cannot access Request here directly, so we skip client context
        # Use file-based fallback
        _write_telemetry({
            'event_type': 'auth',
            'status': 'login_failed',
            'metadata': {'username': login_data.username},
            'timestamp': datetime.now().isoformat()
        })
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username or password"
        )
    
    # Set authentication cookie for web page requests
    response.set_cookie(
        key="auth_token",
        value=result["token"],
        max_age=8*60*60,  # 8 hours (same as session timeout)
        httponly=True,    # Prevent JavaScript access for security
        secure=True,      # HTTPS required for HuggingFace Spaces
        samesite="lax"    # CSRF protection
    )
    
    # Telemetry: login success (server-side)
    try:
        # We cannot access Request here directly; emit without client metadata
        _write_telemetry({
            'event_type': 'auth',
            'status': 'login_success',
            'metadata': {'username': login_data.username},
            'timestamp': datetime.now().isoformat(),
            'user': {'username': result['user']['username'], 'role': result['user']['role']}
        })
    except Exception:
        pass
    return result


@app.get("/api/auth/validate", tags=["Authentication"])
async def validate_session(user: Dict[str, Any] = Depends(require_auth)):
    """Validate current session"""
    return {
        "valid": True,
        "user": user
    }

@app.post("/api/auth/logout", tags=["Authentication"])
async def logout(request: Request, response: Response):
    """Logout user and invalidate session"""
    # Get token from header or cookie
    token = None
    auth_header = request.headers.get('Authorization')
    if auth_header and auth_header.startswith('Bearer '):
        token = auth_header.split(' ')[1]
    else:
        token = request.cookies.get('auth_token')
    
    if token:
        # Telemetry: logout server-side
        try:
            session = auth_manager.validate_session(token)
            _record_server_telemetry(
                request=request,
                event_type='auth',
                status='logout',
                metadata={'path': str(request.url)},
                user=session or None
            )
        except Exception:
            pass
        auth_manager.logout(token)
    
    # Clear the authentication cookie (must match creation parameters)
    response.delete_cookie(
        key="auth_token",
        secure=True,
        samesite="lax"
    )
    
    return {"message": "Logged out successfully"}

@app.get("/api/auth/user", response_model=UserInfo, tags=["Authentication"])
async def get_user_info(user: Dict[str, Any] = Depends(require_auth)):
    """Get current user information"""
    return UserInfo(
        username=user["username"],
        role=user["role"],
        full_name=user["full_name"],
        permissions=user["permissions"]
    )

# Frontend routes
@app.get("/welcome", response_class=HTMLResponse, tags=["Frontend"])
async def serve_welcome(request: Request):
    """Serve the demo welcome screen for authenticated users"""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
        
    try:
        with open("static/welcome.html", encoding="utf-8") as f:
            content = f.read()
        return HTMLResponse(content=content)
    except FileNotFoundError:
        logger.error("welcome.html not found")
        raise HTTPException(status_code=404, detail="Welcome page not found")

@app.get("/login", response_class=HTMLResponse, tags=["Frontend"])
async def serve_login():
    """Serve the login page"""
    try:
        with open("static/login.html", encoding="utf-8") as f:
            content = f.read()
        return HTMLResponse(content=content)
    except FileNotFoundError:
        logger.error("login.html not found")
        raise HTTPException(status_code=404, detail="Login page not found")

@app.get("/", response_class=HTMLResponse, tags=["Frontend"])
async def read_root(request: Request):
    """Serve main app or redirect based on user type"""
    user = get_current_user(request)
    
    # No user? Redirect to login
    if not user:
        return RedirectResponse(url="/login")
    
    # Demo users see welcome screen after login
    if user.get('role') == 'demo_user':
        return RedirectResponse(url="/welcome")
    
    # Regular authenticated users get the app directly
    try:
        with open("static/index.html", encoding="utf-8") as f:
            content = f.read()
        return HTMLResponse(content=content)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="App not found")

@app.get("/form", response_class=HTMLResponse, tags=["Frontend"])
async def serve_form(request: Request):
    """Direct access to form for demo users"""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    
    try:
        with open("static/index.html", encoding="utf-8") as f:
            content = f.read()
        return HTMLResponse(content=content)
    except FileNotFoundError:
        raise HTTPException(status_code=404, detail="Form not found")

@app.get("/map", response_class=HTMLResponse, tags=["Frontend"])
async def serve_map(request: Request):
    """Serve the map page with auth check"""
    # Check if user is authenticated
    user = get_current_user(request)
    
    # Redirect to login if not authenticated
    if not user:
        return RedirectResponse(url="/login")
    
    return RedirectResponse(url="/static/map.html")

@app.get("/contributors", response_class=HTMLResponse, tags=["Frontend"])
async def serve_contributors(request: Request):
    """Serve the contributors page with auth check"""
    user = get_current_user(request)
    if not user:
        return RedirectResponse(url="/login")
    
    try:
        with open("static/contributors.html", encoding="utf-8") as f:
            content = f.read()
        return HTMLResponse(content=content)
    except FileNotFoundError:
        logger.error("contributors.html not found")
        raise HTTPException(status_code=404, detail="Contributors page not found")

@app.get("/api/dashboard/stats", tags=["Dashboard"])
async def get_dashboard_stats(user: Dict[str, Any] = Depends(require_auth)):
    """Get dashboard statistics"""
    try:
        # Get basic tree statistics
        total_trees = db.get_tree_count()  # Remove await - method is not async
        
        # Get unique species count
        trees = await db.get_trees(limit=10000, offset=0)  # Get all for counting
        unique_species = set()
        for tree in trees:
            if hasattr(tree, 'scientific_name') and tree.scientific_name:
                unique_species.add(tree.scientific_name)
            elif hasattr(tree, 'common_name') and tree.common_name:
                unique_species.add(tree.common_name)
        
        # Get last update time
        last_updated = None
        if trees:
            last_updated = max(tree.updated_at or tree.created_at for tree in trees)
        
        return {
            "totalTrees": total_trees,
            "totalSpecies": len(unique_species),
            "totalUsers": 4,  # Static count for now
            "lastUpdated": last_updated
        }
    except Exception as e:
        logger.error(f"Error getting dashboard stats: {e}")
        # Return basic fallback stats
        return {
            "totalTrees": 0,
            "totalSpecies": 0,
            "totalUsers": 4,
            "lastUpdated": None
        }


# Tree CRUD Operations
@app.get("/api/trees", response_model=List[Tree], tags=["Trees"])
async def get_trees(
    limit: int = 100,
    offset: int = 0,
    species: str = None,
    health_status: str = None,
    user: Dict[str, Any] = Depends(require_auth)
):
    """Get trees with pagination and filters"""
    if limit < 1 or limit > settings.server.max_trees_per_request:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Limit must be between 1 and {settings.server.max_trees_per_request}",
        )
    if offset < 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Offset must be non-negative",
        )
    
    try:
        trees = await db.get_trees(limit=limit, offset=offset, species=species, health_status=health_status)
        
        # For map performance: Skip image processing for bulk tree requests
        # Images are not needed for map markers and clustering
        return trees
        
    except RuntimeError as e:
        if "Database not connected" in str(e):
            raise HTTPException(status_code=503, detail="Database not configured")
        raise HTTPException(status_code=500, detail="Database error")
    except Exception as e:
        logger.error(f"Error retrieving trees: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve trees")


@app.post("/api/trees", response_model=Tree, status_code=status.HTTP_201_CREATED, tags=["Trees"])
async def create_tree(tree: TreeCreate, user: Dict[str, Any] = Depends(require_auth)):
    """Create a new tree record (demo mode aware)"""
    try:
        # Check if user is in demo mode (conference participant)
        is_demo_user = "demo_interact" in user.get("permissions", [])
        
        if is_demo_user:
            # Demo mode: Return mock success response without saving
            tree_data = tree.model_dump(exclude_unset=True)
            tree_data['created_by'] = user['username']
            
            # Create a mock tree response
            mock_tree = {
                "id": 9999,  # Mock ID
                "created_at": datetime.now().isoformat(),
                "updated_at": datetime.now().isoformat(),
                **tree_data
            }
            
            logger.info(f"Demo mode: Mock tree creation for conference participant")
            return mock_tree
        
        # Check write permission for regular users
        if "write" not in user.get("permissions", []):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Insufficient permissions to create trees"
            )
        
        # Convert to dict for database insertion
        tree_data = tree.model_dump(exclude_unset=True)
        
        # Add created_by field
        tree_data['created_by'] = user['username']
        
        # Create tree in database
        created_tree = await db.create_tree(tree_data)
        
        # Process files and return with URLs
        processed_tree = storage.process_tree_files(created_tree)
        
        logger.info(f"Created tree with ID: {created_tree.get('id')}")
        return processed_tree
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error creating tree: {e}")
        raise HTTPException(status_code=500, detail="Failed to create tree")


@app.get("/api/trees/{tree_id}", response_model=Tree, tags=["Trees"])
async def get_tree(tree_id: int, user: Dict[str, Any] = Depends(require_auth)):
    """Get a specific tree by ID"""
    try:
        tree = await db.get_tree(tree_id)
        
        if tree is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Tree with ID {tree_id} not found",
            )
        
        # Process files and return with URLs
        processed_tree = storage.process_tree_files(tree)
        return processed_tree
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving tree {tree_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve tree")


@app.put("/api/trees/{tree_id}", response_model=Tree, tags=["Trees"])
async def update_tree(tree_id: int, tree_update: TreeUpdate, request: Request):
    """Update a tree record"""
    try:
        # Get current user
        user = require_auth(request)
        
        # Get existing tree to check permissions
        existing_tree = await db.get_tree(tree_id)
        if not existing_tree:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Tree with ID {tree_id} not found",
            )
        
        # Get token from header or cookie for permission checking
        token = None
        auth_header = request.headers.get('Authorization', '')
        if auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
        else:
            token = request.cookies.get('auth_token')
        
        if not token or not auth_manager.can_edit_tree(token, existing_tree.get('created_by', '')):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You don't have permission to edit this tree",
            )
        
        # Convert to dict for database update
        update_data = tree_update.model_dump(exclude_unset=True)
        
        if not update_data:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No update data provided",
            )
        
        # Update tree in database
        logger.info(f"Updating tree {tree_id} with fields: {list(update_data.keys())}")
        updated_tree = await db.update_tree(tree_id, update_data)
        
        # Process files and return with URLs
        processed_tree = storage.process_tree_files(updated_tree)
        
        logger.info(f"Updated tree with ID: {tree_id}")
        return processed_tree
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating tree {tree_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to update tree")


@app.delete("/api/trees/{tree_id}", tags=["Trees"])
async def delete_tree(tree_id: int, request: Request):
    """Delete a tree record"""
    try:
        # Get current user
        user = require_auth(request)
        
        # Get tree data first to clean up files
        tree = await db.get_tree(tree_id)
        
        if tree is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Tree with ID {tree_id} not found",
            )
        
        # Get token from header or cookie for permission checking
        token = None
        auth_header = request.headers.get('Authorization', '')
        if auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
        else:
            token = request.cookies.get('auth_token')
        
        if not token or not auth_manager.can_delete_tree(token, tree.get('created_by', '')):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You don't have permission to delete this tree",
            )
        
        # Delete tree from database
        await db.delete_tree(tree_id)
        
        # Clean up associated files
        try:
            if tree.get('photographs'):
                for file_path in tree['photographs'].values():
                    if file_path:
                        storage.delete_image(file_path)
            
            if tree.get('storytelling_audio'):
                storage.delete_audio(tree['storytelling_audio'])
        except Exception as e:
            logger.warning(f"Failed to clean up files for tree {tree_id}: {e}")
        
        logger.info(f"Deleted tree with ID: {tree_id}")
        return {"message": f"Tree {tree_id} deleted successfully"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting tree {tree_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete tree")


# File Upload Endpoints
@app.post("/api/upload/image", tags=["Files"])
async def upload_image(
    file: UploadFile = File(...),
    category: str = Form(...),
    user: Dict[str, Any] = Depends(require_auth)
):
    """Upload an image file with cloud persistence (demo mode aware)"""
    # Validate file type
    if not file.content_type or not file.content_type.startswith('image/'):
        raise HTTPException(status_code=400, detail="File must be an image")
    
    # Validate category
    valid_categories = ["Leaf", "Bark", "Fruit", "Seed", "Flower", "Full tree"]
    if category not in valid_categories:
        raise HTTPException(
            status_code=400,
            detail=f"Category must be one of: {valid_categories}"
        )
    
    try:
        # Check if user is in demo mode
        is_demo_user = "demo_interact" in user.get("permissions", [])
        
        if is_demo_user:
            # Demo mode: Return mock success without uploading
            await file.read()  # Consume the file to prevent issues
            
            logger.info(f"Demo mode: Mock image upload for conference participant")
            
            return {
                "filename": f"demo_{file.filename}",
                "category": category,
                "size": 0,
                "content_type": file.content_type,
                "bucket": "demo-bucket",
                "success": True
            }
        
        # Check write permission for regular users
        if "write" not in user.get("permissions", []):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Insufficient permissions to upload files"
            )
        
        # Read file content
        content = await file.read()
        
        # Upload to Supabase Storage
        result = storage.upload_image(content, file.filename, category)
        
        logger.info(f"Image uploaded successfully: {result['filename']}")
        
        return {
            "filename": result['filename'],
            "category": category,
            "size": result['size'],
            "content_type": file.content_type,
            "bucket": result['bucket'],
            "success": True
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error uploading image: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/upload/audio", tags=["Files"])
async def upload_audio(file: UploadFile = File(...), user: Dict[str, Any] = Depends(require_auth)):
    """Upload an audio file with cloud persistence (demo mode aware)"""
    # Validate file type
    if not file.content_type or not file.content_type.startswith('audio/'):
        raise HTTPException(status_code=400, detail="File must be an audio file")
    
    try:
        # Check if user is in demo mode
        is_demo_user = "demo_interact" in user.get("permissions", [])
        
        if is_demo_user:
            # Demo mode: Return mock success without uploading
            await file.read()  # Consume the file to prevent issues
            
            logger.info(f"Demo mode: Mock audio upload for conference participant")
            
            return {
                "filename": f"demo_{file.filename}",
                "size": 0,
                "content_type": file.content_type,
                "bucket": "demo-bucket",
                "success": True
            }
        
        # Check write permission for regular users
        if "write" not in user.get("permissions", []):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Insufficient permissions to upload files"
            )
        
        # Read file content
        content = await file.read()
        
        # Upload to Supabase Storage
        result = storage.upload_audio(content, file.filename)
        
        logger.info(f"Audio uploaded successfully: {result['filename']}")
        
        return {
            "filename": result['filename'],
            "size": result['size'],
            "content_type": file.content_type,
            "bucket": result['bucket'],
            "success": True
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error uploading audio: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# File serving - generate signed URLs on demand
@app.get("/api/files/image/{file_path:path}", tags=["Files"])
async def get_image(file_path: str):
    """Get signed URL for image file"""
    try:
        signed_url = storage.get_image_url(file_path, expires_in=3600)  # 1 hour
        return RedirectResponse(url=signed_url)
    except Exception as e:
        logger.error(f"Error getting image URL: {e}")
        raise HTTPException(status_code=404, detail="Image not found")


@app.get("/api/files/audio/{file_path:path}", tags=["Files"])
async def get_audio(file_path: str):
    """Get signed URL for audio file"""
    try:
        signed_url = storage.get_audio_url(file_path, expires_in=3600)  # 1 hour
        return RedirectResponse(url=signed_url)
    except Exception as e:
        logger.error(f"Error getting audio URL: {e}")
        raise HTTPException(status_code=404, detail="Audio not found")


# Utility endpoints
@app.get("/api/utilities", tags=["Data"])
async def get_utilities():
    """Get list of valid utility options"""
    return {
        "utilities": [
            "Religious", "Timber", "Biodiversity", "Hydrological benefit", 
            "Faunal interaction", "Food", "Medicine", "Shelter", "Cultural"
        ]
    }


@app.get("/api/phenology-stages", tags=["Data"])
async def get_phenology_stages():
    """Get list of valid phenology stages"""
    return {
        "stages": [
            "New leaves", "Old leaves", "Open flowers", "Fruiting", 
            "Ripe fruit", "Recent fruit drop", "Other"
        ]
    }


@app.get("/api/photo-categories", tags=["Data"])
async def get_photo_categories():
    """Get list of valid photo categories"""
    return {
        "categories": ["Leaf", "Bark", "Fruit", "Seed", "Flower", "Full tree"]
    }


# Statistics
@app.get("/api/stats", tags=["Statistics"])
async def get_stats():
    """Get comprehensive tree statistics"""
    try:
        total_trees = db.get_tree_count()
        species_distribution = db.get_species_distribution(limit=20)
        health_distribution = db.get_health_distribution()  # Will be empty for now
        measurements = db.get_average_measurements()
        
        return {
            "total_trees": total_trees,
            "species_distribution": species_distribution,
            "health_distribution": health_distribution,
            "average_height_ft": measurements["average_height"],
            "average_girth_ft": measurements["average_diameter"],
            "units": {"height": "ft", "girth": "ft"},
            "last_updated": datetime.now().isoformat(),
        }
        
    except Exception as e:
        logger.error(f"Error retrieving statistics: {e}")
        raise HTTPException(status_code=500, detail="Failed to retrieve statistics")


# Master tree database suggestions
@app.get("/api/tree-suggestions", tags=["Data"])
async def get_tree_suggestions_api(query: str = "", limit: int = 10):
    """Get auto-suggestions for tree names from master database"""
    if not query or len(query.strip()) == 0:
        return {"suggestions": []}
    
    try:
        create_master_tree_database()
        suggestions = get_tree_suggestions(query.strip(), limit)
        
        return {
            "query": query,
            "suggestions": suggestions,
            "count": len(suggestions)
        }
        
    except Exception as e:
        logger.error(f"Error getting tree suggestions: {e}")
        return {"suggestions": [], "error": str(e)}


@app.get("/api/tree-codes", tags=["Data"])
async def get_tree_codes_api():
    """Get all available tree codes from master database"""
    try:
        create_master_tree_database()
        tree_codes = get_all_tree_codes()
        
        return {
            "tree_codes": tree_codes,
            "count": len(tree_codes)
        }
        
    except Exception as e:
        logger.error(f"Error getting tree codes: {e}")
        return {"tree_codes": [], "error": str(e)}


# Telemetry logging
# Internal helper to record server-side telemetry without requiring client call

def _record_server_telemetry(request: Request, event_type: str, status: str = None, metadata: Dict[str, Any] = None, user: Dict[str, Any] = None):
    evt = {
        'event_type': event_type,
        'status': status,
        'metadata': metadata or {},
        'timestamp': datetime.now().isoformat(),
        'user': None,
        'client': {
            'ip': request.client.host if request.client else None,
            'user_agent': request.headers.get('user-agent')
        }
    }
    if user:
        evt['user'] = { 'username': user.get('username'), 'role': user.get('role') }
    if getattr(db, 'connected', False):
        if not db.log_telemetry(evt):
            _write_telemetry(evt)
    else:
        _write_telemetry(evt)

class TelemetryEvent(BaseModel):
    event_type: str = Field(..., description="Type of event, e.g., 'upload', 'ui', 'error'")
    status: Optional[str] = Field(None, description="Status such as success/error")
    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
    timestamp: Optional[str] = Field(default=None)


def _write_telemetry(event: Dict[str, Any]):
    try:
        # Ensure timestamp
        if 'timestamp' not in event or not event['timestamp']:
            event['timestamp'] = datetime.now().isoformat()
        # Append as JSON line
        with open("telemetry.log", "a", encoding="utf-8") as f:
            f.write(json.dumps(event) + "\n")
    except Exception as e:
        logger.warning(f"Failed to write telemetry: {e}")


@app.post("/api/telemetry", tags=["System"])
async def telemetry(event: TelemetryEvent, request: Request, user: Dict[str, Any] = Depends(require_auth)):
    """Accept telemetry/observability events from the client for troubleshooting."""
    try:
        evt = event.model_dump()
        # Enrich with user and request context
        evt['user'] = {
            "username": user.get("username"),
            "role": user.get("role")
        }
        evt['client'] = {
            "ip": request.client.host if request.client else None,
            "user_agent": request.headers.get('user-agent')
        }
        # Prefer Supabase persistent storage; fallback to file if not configured
        if getattr(db, 'connected', False):
            ok = db.log_telemetry(evt)
            if ok:
                logger.info(f"Telemetry stored: {evt.get('event_type')} status={evt.get('status')}")
            else:
                logger.warning("Telemetry DB insert failed, writing to file")
                _write_telemetry(evt)
        else:
            logger.info("DB not connected, writing telemetry to file")
            _write_telemetry(evt)
        return {"ok": True}
    except Exception as e:
        logger.error(f"Telemetry error: {e}")
        raise HTTPException(status_code=500, detail="Failed to record telemetry")


# Telemetry query (admin-only)
@app.get("/api/telemetry", tags=["System"])
async def get_telemetry(limit: int = 100, user: Dict[str, Any] = Depends(require_permission("admin"))):
    """Return recent telemetry events. Uses Supabase if connected, else reads telemetry.log."""
    limit = max(1, min(1000, limit))
    try:
        if getattr(db, 'connected', False):
            events = db.get_recent_telemetry(limit)
            # Normalize shape to always include evt.user = {username, role}
            norm_events: List[Dict[str, Any]] = []
            for e in (events or []):
                if 'user' not in e or not e.get('user'):
                    username = e.get('username')
                    role = e.get('role')
                    if username or role:
                        e = {**e, 'user': {'username': username, 'role': role}}
                norm_events.append(e)
            return {"events": norm_events, "source": "supabase", "count": len(norm_events)}
        # Fallback to file
        events: List[Dict[str, Any]] = []
        try:
            with open("telemetry.log", "r", encoding="utf-8") as f:
                lines = f.readlines()
                for line in lines[-limit:]:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        events.append(json.loads(line))
                    except Exception:
                        continue
        except FileNotFoundError:
            events = []
        return {"events": events, "source": "file", "count": len(events)}
    except Exception as e:
        logger.error(f"Get telemetry failed: {e}")
        raise HTTPException(status_code=500, detail="Failed to fetch telemetry")

# Version info
@app.get("/api/version", tags=["System"])
async def get_version():
    """Get current application version"""
    return {
        "version": "3.0.0",
        "backend": "supabase",
        "database": "postgres",
        "storage": "supabase-storage",
        "timestamp": int(time.time()),
        "build": build_time,
        "server_time": datetime.now().isoformat()
    }


if __name__ == "__main__":
    uvicorn.run(
        "app:app", host="127.0.0.1", port=8000, reload=True, log_level="info"
    )