File size: 48,598 Bytes
9db4736
 
 
 
 
 
 
 
1034c3a
652ff30
dae4d03
 
 
1034c3a
7672051
dae4d03
 
 
1034c3a
9db4736
 
 
a95a00b
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
a95a00b
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
9db4736
 
 
 
 
 
 
6fb5dda
57785f8
6fb5dda
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dae4d03
 
9db4736
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db4736
 
 
 
 
 
 
 
 
1034c3a
 
 
 
 
 
 
 
 
f0c9842
 
1034c3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c9842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dae4d03
 
57785f8
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
dae4d03
550d9b8
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652ff30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
7672051
1034c3a
7672051
 
 
1034c3a
7672051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
 
 
7672051
1034c3a
 
 
 
 
 
7672051
 
 
550d9b8
 
 
 
 
 
 
7672051
 
 
 
 
1034c3a
 
 
 
 
 
7672051
 
 
 
 
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672051
 
 
 
 
9db4736
888e323
 
 
 
 
 
 
 
 
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
dae4d03
57785f8
dae4d03
550d9b8
 
 
 
 
 
 
 
27aa949
 
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550d9b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dae4d03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db4736
 
07b69d9
 
 
 
9db4736
 
 
57785f8
638586a
795b9df
638586a
795b9df
 
 
 
 
9db4736
 
 
 
 
 
 
 
 
07b69d9
 
 
 
 
 
 
 
 
 
 
 
 
9db4736
 
638586a
 
 
9db4736
 
638586a
9db4736
 
 
07b69d9
 
 
 
 
 
 
 
 
 
 
638586a
 
 
 
 
 
 
 
9db4736
 
 
a95a00b
1034c3a
a95a00b
 
07b69d9
652ff30
1034c3a
a95a00b
 
 
652ff30
 
 
 
 
 
1034c3a
 
 
 
f0c9842
 
 
 
1034c3a
 
 
9db4736
 
 
 
 
1034c3a
 
9db4736
1034c3a
 
 
 
07b69d9
 
 
1034c3a
07b69d9
9db4736
1034c3a
 
888e323
 
 
 
1034c3a
652ff30
1034c3a
9db4736
1034c3a
 
 
888e323
 
1034c3a
dd40bee
 
652ff30
1034c3a
 
 
 
 
652ff30
 
 
 
1034c3a
 
 
 
 
 
 
 
 
 
 
 
652ff30
1034c3a
 
9db4736
1034c3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a95a00b
7672051
 
a95a00b
9db4736
7672051
 
 
9db4736
 
 
 
 
a95a00b
 
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
7672051
 
 
9db4736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888e323
 
 
1034c3a
888e323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
 
 
 
 
 
1b9b8c1
 
1034c3a
 
 
 
 
 
57785f8
1034c3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888e323
 
1034c3a
888e323
 
 
 
 
1034c3a
 
888e323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
888e323
 
1034c3a
 
 
 
 
 
 
 
 
 
1b9b8c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1034c3a
652ff30
 
 
 
 
 
 
 
 
 
 
 
888e323
 
652ff30
888e323
 
 
 
652ff30
 
888e323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652ff30
 
888e323
 
652ff30
 
 
 
 
888e323
652ff30
 
888e323
 
 
652ff30
 
 
 
 
 
 
 
 
 
dd40bee
 
 
 
 
 
 
 
 
 
 
 
888e323
 
dd40bee
888e323
 
dd40bee
 
888e323
 
 
 
 
dd40bee
888e323
dd40bee
888e323
 
 
 
 
 
 
 
 
dd40bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888e323
 
 
dd40bee
888e323
 
dd40bee
 
 
888e323
 
 
 
 
 
 
dd40bee
888e323
 
 
 
 
 
 
 
 
dd40bee
888e323
 
 
 
dd40bee
 
 
 
 
 
 
9db4736
 
0143af6
 
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
import os
import tempfile
import shutil
import subprocess
import logging
import zipfile
import json
import hashlib
import uuid
import requests
import secrets
from datetime import datetime, timedelta
from dotenv import load_dotenv
import boto3
import traceback

# Load local .env if present
load_dotenv()
from botocore.client import Config
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, Response, Request, Depends, Header, Form


# Logging setup
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ----------------------------------------

# FastAPI app
app = FastAPI()

# Configure CORS
default_origins = [
    "http://localhost:8080",
    "https://aimusicapp-a2b65.web.app",
    "https://aimusicapp-a2b65.firebaseapp.com",
    # "https://SplitSonic.ai",
    # "https://www.SplitSonic.ai",
    # "SplitSonic.ai",
    # "www.SplitSonic.ai"
]
allowed_origins_env = os.environ.get('ALLOWED_ORIGINS')
allowed_origins = [o.strip() for o in allowed_origins_env.split(',') if o.strip()] if allowed_origins_env else default_origins

app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["Authorization", "Content-Type", "X-Requested-With"],
    expose_headers=["X-Cache-Key", "X-Video-Title", "Content-Disposition"],
)

@app.options("/upload")
def options_handler(request: Request):
    origin = request.headers.get("origin")
    return Response(status_code=200, headers={
        "Access-Control-Allow-Origin": origin or "*",
        "Access-Control-Allow-Methods": "POST, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization",
    })

@app.get("/")
def health_check():
    return {"status": "healthy", "message": "SplitSonic Backend is running!"}

# --- Utility Functions ---
def find_ffmpeg() -> str:
    common_paths = ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"]
    for path in common_paths:
        if os.path.exists(path) and os.access(path, os.X_OK):
            return path
    
    # Check current directory
    local_binary = os.path.join(os.getcwd(), "ffmpeg")
    if os.path.exists(local_binary):
        return local_binary
    
    return shutil.which("ffmpeg") or "ffmpeg"

FFMPEG_PATH = find_ffmpeg()
FFMPEG_DIR = os.path.dirname(FFMPEG_PATH) if FFMPEG_PATH != "ffmpeg" else None
logger.info(f"Using ffmpeg at: {FFMPEG_PATH}")

def find_demucs() -> list:
    import sys
    path = shutil.which("demucs")
    if path: return [path]
    try:
        import demucs
        return [sys.executable, "-m", "demucs"]
    except ImportError:
        return ["demucs"]

DEMUCS_CMD = find_demucs()
CACHE_DIR = os.path.join(tempfile.gettempdir(), "aimusic_cache")
os.makedirs(CACHE_DIR, exist_ok=True)

# --- Firebase Admin Setup ---
firebase_admin = None
firebase_auth = None
FIREBASE_INITIALIZED = False

try:
    import firebase_admin
    from firebase_admin import credentials, auth as firebase_auth
    if not firebase_admin._apps:
        cred_json = os.environ.get('FIREBASE_CREDENTIALS')
        initialized = False
        
        if cred_json:
            try:
                # Try as JSON string first
                cred_dict = json.loads(cred_json)
                firebase_admin.initialize_app(credentials.Certificate(cred_dict))
                FIREBASE_INITIALIZED = True
                initialized = True
                logger.info("Firebase Admin initialized via environment variable (JSON)")
            except json.JSONDecodeError:
                # Try as file path if NOT valid JSON
                if os.path.exists(cred_json):
                    firebase_admin.initialize_app(credentials.Certificate(cred_json))
                    FIREBASE_INITIALIZED = True
                    initialized = True
                    logger.info(f"Firebase Admin initialized via environment variable (path): {cred_json}")
        
        if not initialized:
            # Fallback: Try to find a JSON file in the project folder
            for f in os.listdir(os.path.dirname(os.path.abspath(__file__))):
                if f.endswith('.json') and 'firebase' in f.lower() and 'admin' in f.lower():
                    firebase_admin.initialize_app(credentials.Certificate(f))
                    FIREBASE_INITIALIZED = True
                    logger.info(f"Firebase Admin initialized via file: {f}")
                    break
except Exception as e:
    logger.warning(f"Firebase Admin setup skipped: {e}")

# --- Cloudflare R2 Setup ---
R2_ENDPOINT = os.environ.get('R2_ENDPOINT')
R2_ACCESS_KEY_ID = os.environ.get('R2_ACCESS_KEY_ID')
R2_SECRET_ACCESS_KEY = os.environ.get('R2_SECRET_ACCESS_KEY')
R2_BUCKET_NAME = os.environ.get('R2_BUCKET_NAME')
R2_ACCOUNT_ID = os.environ.get('R2_ACCOUNT_ID')

s3_client = None
R2_ENABLED = False
# 10 GB limit
MAX_STORAGE_BYTES = 10 * (1000 ** 3)

if all([R2_ENDPOINT, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY, R2_BUCKET_NAME]):
    try:
        s3_client = boto3.client(
            's3',
            endpoint_url=R2_ENDPOINT,
            aws_access_key_id=R2_ACCESS_KEY_ID,
            aws_secret_access_key=R2_SECRET_ACCESS_KEY,
            config=Config(signature_version='s3v4'),
            region_name='auto'  # R2 uses 'auto' for region
        )
        R2_ENABLED = True
        logger.info(f"R2 client initialized for bucket: {R2_BUCKET_NAME}")
    except Exception as e:
        logger.error(f"Failed to initialize R2 client: {e}")
else:
    logger.warning("R2 credentials not found. File storage will use local temp directory.")

def get_r2_usage_bytes() -> int:
    """Calculate the total storage usage of the R2 bucket in bytes."""
    if not R2_ENABLED:
        return 0
    
    total_size = 0
    try:
        paginator = s3_client.get_paginator('list_objects_v2')
        for page in paginator.paginate(Bucket=R2_BUCKET_NAME):
            if 'Contents' in page:
                for obj in page['Contents']:
                    total_size += obj.get('Size', 0)
        return total_size
    except Exception as e:
        logger.error(f"Error calculating R2 usage: {e}")
        return 0

def check_storage_limit():
    """Check if the R2 storage limit has been reached."""
    if not R2_ENABLED:
        return
    
    usage = get_r2_usage_bytes()
    logger.info(f"Current R2 storage usage: {usage / (1024*1024*1024):.2f} GB / {MAX_STORAGE_BYTES / (1024*1024*1024):.2f} GB")
    
    if usage >= MAX_STORAGE_BYTES:
        raise HTTPException(
            status_code=507, 
            detail="Storage limit reached. Please try again tomorrow."
        )

# --- SMTP2GO & Activation Configuration ---
SMTP2GO_API_KEY = os.environ.get('SMTP2GO_API_KEY')
SMTP2GO_SENDER = os.environ.get('SMTP2GO_SENDER', 'contact@niftysoftsol.com')
ACTIVATIONS_FILE = os.path.join(CACHE_DIR, "activations.json")

def load_activations() -> dict:
    try:
        if os.path.exists(ACTIVATIONS_FILE):
            with open(ACTIVATIONS_FILE, 'r', encoding='utf-8') as fh:
                return json.loads(fh.read())
    except Exception:
        logger.exception('Failed to load activations file')
    return {}

def save_activations(data: dict) -> None:
    try:
        with open(ACTIVATIONS_FILE, 'w', encoding='utf-8') as fh:
            fh.write(json.dumps(data, ensure_ascii=False, indent=2))
    except Exception:
        logger.exception('Failed to save activations file')

def send_activation_email(email: str, token: str, origin: str):
    if not SMTP2GO_API_KEY:
        logger.warning("SMTP2GO_API_KEY not found. Skipping email sending.")
        logger.info(f"Activation link for {email}: {origin}/activate?token={token}")
        return
    
    activation_url = f"{origin}/activate?token={token}"
    
    try:
        response = requests.post(
            'https://api.smtp2go.com/v3/email/send',
            json={
                'api_key': SMTP2GO_API_KEY,
                'sender': SMTP2GO_SENDER,
                'to': [email],
                'subject': 'Activate your SplitSonic account',
                'html_body': f"""
                <h1>Welcome to SplitSonic!</h1>
                <p>Please click the link below to activate your account. This link is valid for 15 minutes.</p>
                <a href="{activation_url}" style="display: inline-block; padding: 10px 20px; background-color: #007bff; color: white; text-decoration: none; border-radius: 5px;">Activate Account</a>
                <p>If the button doesn't work, copy and paste this link into your browser:</p>
                <p>{activation_url}</p>
                """
            },
            timeout=10
        )
        result = response.json()
        if response.status_code == 200 and result.get('data', {}).get('succeeded'):
            logger.info(f"Activation email sent to {email}")
        else:
            logger.error(f"Failed to send activation email: {result}")
    except Exception as e:
        logger.error(f"Error sending activation email: {e}")

# --- reCAPTCHA Verification ---
RECAPTCHA_SECRET_KEY = os.environ.get('RECAPTCHA_SECRET_KEY')

def verify_recaptcha(token: str, action: str = 'upload') -> bool:
    """Verify Google reCAPTCHA v3 token"""
    if not RECAPTCHA_SECRET_KEY:
        logger.warning("RECAPTCHA_SECRET_KEY not found. Skipping verification.")
        return True
        
    try:
        response = requests.post(
            'https://www.google.com/recaptcha/api/siteverify',
            data={
                'secret': RECAPTCHA_SECRET_KEY,
                'response': token
            },
            timeout=10
        )
        result = response.json()
        
        if result.get('success') and result.get('action') == action:
            score = result.get('score', 0)
            if score >= 0.5:
                logger.info(f"reCAPTCHA verified for action '{action}' with score {score}")
                return True
            else:
                logger.warning(f"reCAPTCHA score too low: {score} for action '{action}'")
                return False
        
        logger.warning(f"reCAPTCHA verification failed: {result}")
        return False
    except Exception as e:
        logger.error(f"reCAPTCHA verification error: {e}")
        return False

# --- JWT Verification ---
def get_authenticated_user(authorization: str | None) -> dict:
    """
    Core authentication helper to verify Firebase token.
    Returns a dictionary with {'user_id': uid, 'email': email}.
    Includes a development bypass if DEV_ALLOW_PROFILE_NO_AUTH is set.
    """
    # Development bypass
    dev_bypass = os.environ.get('DEV_ALLOW_PROFILE_NO_AUTH', '').lower() in ('1', 'true', 'yes')
    if dev_bypass:
        uid, email = 'dev-user', 'dev@example.com'
        if authorization and authorization.lower().startswith('bearer '):
            token = authorization.split(' ', 1)[1].strip()
            if ':' in token:
                parts = token.split(':', 1)
                uid = parts[0] or uid
                if len(parts) > 1: email = parts[1] or email
        return {'user_id': uid, 'email': email}

    if not authorization or not authorization.lower().startswith('bearer '):
        raise HTTPException(status_code=401, detail='Missing or invalid Authorization header')
    
    if not FIREBASE_INITIALIZED:
        raise HTTPException(status_code=500, detail="Firebase not initialized")
    
    token = authorization.split(' ', 1)[1].strip()
    
    try:
        decoded_token = firebase_auth.verify_id_token(token)
        uid = decoded_token.get('uid')
        if not uid:
            raise HTTPException(status_code=401, detail="Invalid token: missing uid")
        
        # Check for email verification
        user_record = firebase_auth.get_user(uid)
        
        # Check if they have a trusted provider (like Google)
        providers = [p.provider_id for p in user_record.provider_data]
        is_trusted_provider = 'google.com' in providers
        
        if not user_record.email_verified and not is_trusted_provider:
            logger.warning(f"Blocking unverified user: {uid} (Providers: {providers})")
            raise HTTPException(status_code=403, detail='Email not verified. Please check your inbox.')
            
        return {'user_id': uid, 'email': decoded_token.get('email')}
    except HTTPException as he:
        raise he
    except firebase_admin.exceptions.ExpiredIdTokenError:
        raise HTTPException(status_code=401, detail="Token expired")
    except Exception as e:
        logger.error(f"Token verification failed: {e}")
        raise HTTPException(status_code=401, detail="Token verification failed")

def verify_firebase_token(authorization: str | None) -> str:
    """
    Legacy helper that returns only the UID string.
    Used for S3 path construction and general auth checks.
    """
    user = get_authenticated_user(authorization)
    return user['user_id']

PROFILES_FILE = os.path.join(CACHE_DIR, "profiles.json")

class ProfileIn(BaseModel):
    display_name: str | None = None
    profile_picture: str | None = None

class ProfileOut(BaseModel):
    user_id: str
    display_name: str | None = None
    email: str | None = None
    profile_picture: str | None = None
    created_at: str | None = None
    updated_at: str | None = None

def load_profiles() -> dict:
    try:
        if os.path.exists(PROFILES_FILE):
            with open(PROFILES_FILE, 'r', encoding='utf-8') as fh:
                return json.loads(fh.read())
    except Exception:
        logger.exception('Failed to load profiles file')
    return {}

def save_profiles(data: dict) -> None:
    try:
        with open(PROFILES_FILE, 'w', encoding='utf-8') as fh:
            fh.write(json.dumps(data, ensure_ascii=False, indent=2))
    except Exception:
        logger.exception('Failed to save profiles file')

def get_current_user(authorization: str | None = Header(None)):
    """
    Dependency helper for FastAPI routes.
    Returns the full user info dictionary.
    """
    return get_authenticated_user(authorization)

def get_user_storage_prefixes(user: dict) -> list[str]:
    """
    Returns the storage prefix for R2 for a given user.
    Uses the Python str(dict) representation as requested: {'user_id': 'uid', 'email': 'email'}
    """
    uid = user['user_id']
    email = user['email']
    
    # User requested to ONLY use this specific format
    prefix_dict = {"user_id": uid, "email": email}
    return [f"uploads/{str(prefix_dict)}/"]

@app.get("/api/profile", response_model=ProfileOut)
def get_profile(user=Depends(get_current_user)):
    profiles = load_profiles()
    p = profiles.get(user['user_id'], {})
    return {
        "user_id": user['user_id'],
        "email": user['email'],
        "display_name": p.get("display_name"),
        "profile_picture": p.get("profile_picture"),
        "created_at": p.get("created_at"),
        "updated_at": p.get("updated_at")
    }

@app.api_route("/api/profile", methods=["POST", "PUT"], response_model=ProfileOut)
def update_profile(data: ProfileIn, user=Depends(get_current_user)):
    profiles = load_profiles()
    u_id = user['user_id']
    now = datetime.utcnow().isoformat()
    
    if u_id not in profiles:
        profiles[u_id] = {"created_at": now}
    
    p = profiles[u_id]
    if data.display_name is not None: p["display_name"] = data.display_name
    if data.profile_picture is not None: p["profile_picture"] = data.profile_picture
    p["updated_at"] = now
    
    save_profiles(profiles)
    return {**p, "user_id": u_id, "email": user['email']}

@app.delete("/api/profile")
async def delete_profile(authorization: str = Header(...)):
    """
    Delete the authenticated user's profile and all associated files.
    """
    user = get_authenticated_user(authorization)
    uid = user['user_id']
    
    # 1. Delete all R2 files
    if R2_ENABLED:
        try:
            user_prefixes = get_user_storage_prefixes(user)
            deleted_count = 0
            for prefix in user_prefixes:
                while True:
                    response = s3_client.list_objects_v2(
                        Bucket=R2_BUCKET_NAME,
                        Prefix=prefix
                    )
                    
                    if 'Contents' not in response:
                        break
                        
                    delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
                    s3_client.delete_objects(
                        Bucket=R2_BUCKET_NAME,
                        Delete=delete_objects
                    )
                    deleted_count += len(delete_objects['Objects'])
                    
                    if not response.get('IsTruncated'):
                        break
            logger.info(f"Deleted {deleted_count} files for user {uid} during profile deletion")
        except Exception as e:
            logger.error(f"Failed to delete files during profile deletion key={uid}: {e}")
            # Proceed to delete profile even if storage cleanup fails partially
            pass

    # 2. Delete profile data
    profiles = load_profiles()
    if uid in profiles:
        del profiles[uid]
        save_profiles(profiles)
        logger.info(f"Deleted profile data for user {uid}")
        
    return {"message": "Profile and all data deleted successfully"}

# --- Authentication & Activation Endpoints ---

class SignupRequest(BaseModel):
    email: str
    password: str

class ActivateRequest(BaseModel):
    token: str

@app.post("/api/signup")
async def signup(request: SignupRequest, req: Request, background_tasks: BackgroundTasks):
    if not FIREBASE_INITIALIZED:
        raise HTTPException(status_code=500, detail="Firebase not initialized")
    
    origin = req.headers.get('origin')
    if origin not in allowed_origins:
        # Fallback to the first allowed origin if not provided or invalid (for safety)
        origin = allowed_origins[0] if allowed_origins else "http://localhost:8080"

    # Validate password complexity
    import re
    password_regex = r"^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?\":{}|<>]).{8,}$"
    if not re.match(password_regex, request.password):
        raise HTTPException(
            status_code=400, 
            detail="Password must be at least 8 characters long and include an uppercase letter, a number, and a special character."
        )
    
    logger.info(f"Signup request for email {request.email} from origin {origin}")
    try:
        # Create user in Firebase with email_verified=False
        user = firebase_auth.create_user(
            email=request.email,
            password=request.password,
            email_verified=False
        )
        
        # Generate activation token
        token = secrets.token_urlsafe(32)
        expiry = (datetime.utcnow() + timedelta(minutes=15)).isoformat()
        
        activations = load_activations()
        activations[token] = {
            "uid": user.uid,
            "email": request.email,
            "expires_at": expiry
        }
        save_activations(activations)
        
        # Send email in background
        background_tasks.add_task(send_activation_email, request.email, token, origin)
        # Also clean up expired accounts
        background_tasks.add_task(cleanup_unactivated_users)
        
        return {"message": "Signup successful. Please check your email for activation link."}
    except Exception as e:
        logger.error(f"Signup error: {e}")
        raise HTTPException(status_code=400, detail=str(e))

@app.post("/api/activate")
async def activate(request: ActivateRequest):
    if not FIREBASE_INITIALIZED:
        raise HTTPException(status_code=500, detail="Firebase not initialized")
    
    activations = load_activations()
    data = activations.get(request.token)
    
    if not data:
        raise HTTPException(status_code=404, detail="Invalid or expired activation token.")
    
    expiry = datetime.fromisoformat(data['expires_at'])
    if datetime.utcnow() > expiry:
        # Cleanup expired user from Firebase
        try:
            uid = data['uid']
            user = firebase_auth.get_user(uid)
            if not user.email_verified:
                logger.info(f"Cleaning up expired user during activation attempt: {uid}")
                firebase_auth.delete_user(uid)
        except Exception as cleanup_err:
            logger.error(f"Failed to cleanup user during activation attempt: {cleanup_err}")

        # Remove token
        del activations[request.token]
        save_activations(activations)
        raise HTTPException(status_code=400, detail="Activation token has expired. Please sign up again.")
    
    try:
        # Mark user as verified in Firebase
        firebase_auth.update_user(data['uid'], email_verified=True)
        
        # Remove token
        del activations[request.token]
        save_activations(activations)
        
        return {"message": "Account activated successfully. You can now log in."}
    except Exception as e:
        logger.error(f"Activation error: {e}")
        raise HTTPException(status_code=500, detail="Failed to activate account.")

@app.get("/api/check-password-user")
def check_password_user(email: str):
    """
    Check if a user with the given email already has a 'password' provider.
    Used by Google Auth flow to prevent duplicates.
    """
    if not FIREBASE_INITIALIZED:
        raise HTTPException(status_code=500, detail="Firebase not initialized")
    
    try:
        user = firebase_auth.get_user_by_email(email)
        # Check providers on this specific user object
        providers = [p.provider_id for p in user.provider_data]
        logger.info(f"Checking providers for {email}: {providers}")
        
        has_password = 'password' in providers
        return {"has_password": has_password, "providers": providers}
    except firebase_admin.auth.UserNotFoundError:
        return {"has_password": False, "providers": []}
    except Exception as e:
        logger.error(f"Error checking password user: {e}")
        raise HTTPException(status_code=500, detail=str(e))

def cleanup_unactivated_users():
    """Delete expired activation tokens and their associated Firebase users."""
    if not FIREBASE_INITIALIZED:
        return
    
    activations = load_activations()
    now = datetime.utcnow()
    tokens_to_remove = []
    
    for token, data in activations.items():
        expiry = datetime.fromisoformat(data['expires_at'])
        if now > expiry:
            uid = data['uid']
            try:
                # Check if user is already verified (maybe by other means, though unlikely here)
                user = firebase_auth.get_user(uid)
                if not user.email_verified:
                    logger.info(f"Cleaning up unactivated user: {uid} ({data['email']})")
                    firebase_auth.delete_user(uid)
                tokens_to_remove.append(token)
            except Exception as e:
                logger.error(f"Error during cleanup for user {uid}: {e}")
                # Still remove token if user not found
                if "user-not-found" in str(e).lower():
                    tokens_to_remove.append(token)

    if tokens_to_remove:
        for t in tokens_to_remove:
            del activations[t]
        save_activations(activations)
        logger.info(f"Cleaned up {len(tokens_to_remove)} expired activation(s)")

# --- Core Logic ---

def run_demucs_and_extract(input_path: str, tmpdir: str, requested_stems: list = None) -> str:
    if requested_stems is None:
        requested_stems = ["vocals", "drums", "bass", "other", "instrumental"]
    
    output_dir = os.path.join(tmpdir, "stems")
    os.makedirs(output_dir, exist_ok=True)
    
    cmd = DEMUCS_CMD + ["-o", output_dir, input_path]
    # Run demucs (suppress verbose output)
    try:
        subprocess.run(cmd, check=True, capture_output=True, text=True)
    except subprocess.CalledProcessError as e:
        logger.error(f"Demucs failed code={e.returncode}")
        logger.error(f"Demucs stderr: {e.stderr}")
        logger.error(f"Demucs stdout: {e.stdout}")
        raise e
    
    mp3_dir = os.path.join(tmpdir, "stems_mp3")
    os.makedirs(mp3_dir, exist_ok=True)
    
    # Walk to find all .wav files (handles various models like htdemucs)
    wav_count = 0
    for root, dirs, files in os.walk(output_dir):
        for f in files:
            if f.endswith('.wav'):
                basename = f.replace('.wav', '').lower()
                # Map Demucs names to our stem names
                is_requested = False
                if basename in requested_stems:
                    is_requested = True
                elif basename == 'vocal' and 'vocals' in requested_stems:
                    is_requested = True
                elif basename == 'drum' and 'drums' in requested_stems:
                    is_requested = True
                
                if not is_requested:
                    continue

                src = os.path.join(root, f)
                dst = os.path.join(mp3_dir, f.replace('.wav', '.mp3'))
                # Convert WAV to MP3 (suppress ffmpeg output)
                subprocess.run([FFMPEG_PATH, "-y", "-i", src, "-codec:a", "libmp3lame", "-qscale:a", "2", dst], 
                              check=True, capture_output=True, text=True)
                wav_count += 1
    
    logger.info(f"Processed {wav_count} stems")
    if wav_count == 0:
        raise Exception("Demucs produced no output files. Check if the model is installed and the input is valid.")
    
    # Create instrumental mix if requested
    if 'instrumental' in requested_stems:
        stems = [os.path.join(mp3_dir, f) for f in os.listdir(mp3_dir) if 'vocal' not in f.lower() and f.endswith('.mp3')]
        if stems:
            inst_path = os.path.join(mp3_dir, 'instrumental.mp3')
            n = len(stems)
            labels = "".join(f"[{i}:a]" for i in range(n))
            subprocess.run([FFMPEG_PATH, "-y"] + [i for s in stems for i in ("-i", s)] + 
                           ["-filter_complex", f"{labels}amix=inputs={n}:normalize=0", "-c:a", "libmp3lame", "-qscale:a", "2", inst_path], 
                           check=True, capture_output=True, text=True)
            # We don't increment wav_count here since it's an extra file
 
    # Add original audio to the output
    original_mp3 = os.path.join(mp3_dir, 'original.mp3')
    subprocess.run([
        FFMPEG_PATH, "-y", "-i", input_path,
        "-codec:a", "libmp3lame", "-qscale:a", "2",
        original_mp3
    ], check=True, capture_output=True, text=True)
 
    return mp3_dir

@app.post("/upload")
async def process_upload(
    file: UploadFile = File(...), 
    tos_agreed: bool = Form(...),
    stems: str = Form("vocals,drums,bass,other,instrumental"),
    recaptcha_token: str = Form(None),
    authorization: str = Header(None),
    background_tasks: BackgroundTasks = None
):
    if not tos_agreed:
        raise HTTPException(status_code=400, detail="You must agree to the Terms of Service.")
    
    # Verify reCAPTCHA
    if recaptcha_token:
        if not verify_recaptcha(recaptcha_token, 'upload'):
            raise HTTPException(status_code=403, detail="Bot detection failed. Please try again.")
    
    # Verify Firebase token and get UID
    uid = verify_firebase_token(authorization) if authorization else None
    
    # Enforce R2 storage limit only if user is authenticated and R2 is enabled
    if R2_ENABLED and uid:
        check_storage_limit()
    
    # Generate unique song ID
    song_id = str(uuid.uuid4())
    
    tmpdir = tempfile.mkdtemp()
    try:
        input_path = os.path.join(tmpdir, file.filename)
        audio_path = os.path.join(tmpdir, "audio.mp3")
        
        with open(input_path, "wb") as f: 
            f.write(file.file.read())
        
        # Convert to standard format
        subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], 
                      check=True, capture_output=True, text=True)
        
        # Parse stems list
        requested_stems = [s.strip().lower() for s in stems.split(',') if s.strip()]
        
        # Process with Demucs
        extracted_dir = run_demucs_and_extract(audio_path, tmpdir, requested_stems)
        
        # If R2 is enabled and user is authenticated, upload to R2
        if R2_ENABLED and uid:
            user = get_authenticated_user(authorization)
            user_prefix = get_user_storage_prefixes(user)[0] # Get the only prefix we now support
            
            logger.info(f"Uploading stems to R2 for user {uid}, song {song_id} to prefix {user_prefix}")
            
            # Upload each stem to R2 with metadata
            uploaded_files = []
            for root, dirs, files in os.walk(extracted_dir):
                for filename in files:
                    if filename.endswith('.mp3'):
                        file_path = os.path.join(root, filename)
                        # Construct key using the prefix: uploads/{dict_str}/{song_id}/{filename}
                        s3_key = f"{user_prefix}{song_id}/{filename}"
                        
                        # Store original filename as metadata on all files for robustness
                        metadata = {'original-filename': file.filename}
                        
                        with open(file_path, 'rb') as f:
                            s3_client.upload_fileobj(
                                f,
                                R2_BUCKET_NAME,
                                s3_key,
                                ExtraArgs={
                                    'ContentType': 'audio/mpeg',
                                    'Metadata': metadata
                                }
                            )
                        uploaded_files.append(filename)
                        logger.info(f"Uploaded {filename} to R2")
            
            # Clean up temp directory
            if background_tasks:
                background_tasks.add_task(shutil.rmtree, tmpdir, True)
            
            return {
                "song_id": song_id,
                "uid": uid,
                "files": uploaded_files,
                "title": file.filename,
                "message": "Upload successful. Files stored in R2."
            }
        
        else:
            # Fallback to local ZIP storage (backward compatibility)
            logger.info(f"Using local storage for song {song_id}")
            final_zip_path = os.path.join(tmpdir, "extracted_stems.zip")
            with zipfile.ZipFile(final_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for root, dirs, files in os.walk(extracted_dir):
                    for file in files:
                        file_path = os.path.join(root, file)
                        arcname = os.path.relpath(file_path, extracted_dir)
                        zipf.write(file_path, arcname)

            digest = hashlib.sha256(open(final_zip_path, 'rb').read()).hexdigest()
            cache_path = os.path.join(CACHE_DIR, f"{digest}.zip")
            shutil.copyfile(final_zip_path, cache_path)
            
            if background_tasks: 
                background_tasks.add_task(shutil.rmtree, tmpdir, True)
            
            return FileResponse(
                cache_path, 
                filename="extracted_stems.zip", 
                media_type="application/zip", 
                headers={"X-Cache-Key": digest}
            )
            
    except HTTPException as he:
        # Keep tmpdir for debugging instead of clearing it on error
        logger.error(f"HTTPException in process_upload (tmpdir: {tmpdir}): {he.detail}")
        raise he
    except Exception as e:
        # Keep tmpdir for debugging instead of clearing it on error
        error_details = traceback.format_exc()
        logger.error(f"Upload processing error (tmpdir: {tmpdir}):\n{error_details}")
        raise HTTPException(status_code=500, detail=str(e))



@app.post("/upload/extracted")
def process_upload_extracted(file: UploadFile = File(...), tos_agreed: bool = Form(...)):
    if not tos_agreed:
        raise HTTPException(status_code=400, detail="You must agree to the Terms of Service to upload content.")

    tmpdir = tempfile.mkdtemp()
    try:
        input_path = os.path.join(tmpdir, file.filename)
        audio_path = os.path.join(tmpdir, "audio.mp3")
        with open(input_path, "wb") as f: f.write(file.file.read())
        subprocess.run([FFMPEG_PATH, "-y", "-i", input_path, "-ac", "2", "-ar", "44100", audio_path], check=True)
        extracted_dir = run_demucs_and_extract(audio_path, tmpdir)
        
        files = []
        for f in os.listdir(extracted_dir):
            files.append({"filename": f, "path": os.path.join(extracted_dir, f)})
        
        return {"message": "Success", "extracted_files": files, "extracted_directory": extracted_dir}
    except Exception as e:
        # Keep tmpdir for debugging instead of clearing it on error
        error_details = traceback.format_exc()
        logger.error(f"Error in process_upload_extracted (tmpdir: {tmpdir}):\n{error_details}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get('/cache/{key}')
def get_cache(key: str):
    path = os.path.join(CACHE_DIR, f"{key}.zip")
    if not os.path.exists(path): raise HTTPException(status_code=404, detail="Not found")
    return FileResponse(path, filename="extracted_stems.zip", media_type="application/zip")

@app.get('/stems/{key}/{filename:path}')
def get_stem(key: str, filename: str):
    zip_path = os.path.join(CACHE_DIR, f"{key}.zip")
    if not os.path.exists(zip_path):
        raise HTTPException(status_code=404, detail="Cache not found")
    
    try:
        with zipfile.ZipFile(zip_path, 'r') as zf:
            target = filename
            if target not in zf.namelist():
                found = None
                for name in zf.namelist():
                    if os.path.basename(name) == filename:
                        found = name
                        break
                if not found:
                    raise HTTPException(status_code=404, detail="Stem not found in archive")
                target = found
            
            data = zf.read(target)
            return Response(content=data, media_type="audio/mpeg", headers={"Content-Disposition": f"attachment; filename={filename}"})
    except Exception as e:
        logger.error(f"Error extracting stem: {e}")
        raise HTTPException(status_code=500, detail="Failed to extract stem from archive")

# --- R2 Presigned URL Endpoints ---
class PresignedUrlRequest(BaseModel):
    song_id: str
    filename: str

@app.post("/presigned-url")
async def get_presigned_url(
    request: PresignedUrlRequest,
    authorization: str = Header(...)
):
    """
    Generate a presigned URL for accessing a file in R2.
    Requires Firebase authentication.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify token and get user
    user = get_authenticated_user(authorization)
    uid = user['user_id']
    
    # candidate prefixes
    prefixes = get_user_storage_prefixes(user)
    
    found_key = None
    for prefix in prefixes:
        s3_key = f"{prefix}{request.song_id}/{request.filename}"
        try:
            # Check if file exists
            s3_client.head_object(Bucket=R2_BUCKET_NAME, Key=s3_key)
            found_key = s3_key
            break
        except:
            continue
            
    if not found_key:
        raise HTTPException(status_code=404, detail="File not found")
    
    try:
        presigned_url = s3_client.generate_presigned_url(
            'get_object',
            Params={
                'Bucket': R2_BUCKET_NAME,
                'Key': found_key,
                'ResponseContentDisposition': f'attachment; filename="{request.filename}"'
            },
            ExpiresIn=3600  # 1 hour
        )
        
        return {
            "url": presigned_url,
            "expires_in": 3600, # 1 hour
            "filename": request.filename
        }
    except Exception as e:
        logger.error(f"Failed to generate presigned URL: {e}")
        raise HTTPException(status_code=500, detail="Failed to generate presigned URL")


@app.get("/list-stems/{song_id}")
async def list_stems(
    song_id: str,
    authorization: str = Header(...)
):
    """
    List all stem files for a given song ID.
    Requires Firebase authentication.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify token and get user
    user = get_authenticated_user(authorization)
    
    # List objects in R2 with both potential prefixes
    prefixes = get_user_storage_prefixes(user)
    
    files = []
    found_song = False
    
    try:
        for user_prefix in prefixes:
            prefix = f"{user_prefix}{song_id}/"
            response = s3_client.list_objects_v2(
                Bucket=R2_BUCKET_NAME,
                Prefix=prefix
            )
            
            if 'Contents' in response:
                found_song = True
                for obj in response['Contents']:
                    # Extract filename from key
                    filename = obj['Key'].split('/')[-1]
                    if filename:  # Skip directory markers
                        files.append({
                            "filename": filename,
                            "size": obj['Size'],
                            "last_modified": obj['LastModified'].isoformat()
                        })
                # If we found files in any prefix, we stop (avoiding duplicates if it exists in both, which shouldn't happen)
                if files:
                    break
        
        if not found_song and not files:
             raise HTTPException(status_code=404, detail="Song not found")
        
        return {
            "song_id": song_id,
            "files": files,
            "count": len(files)
        }
    except Exception as e:
        logger.error(f"Failed to list stems: {e}")
        raise HTTPException(status_code=500, detail="Failed to list stems")

@app.get("/songs/{song_id}/zip")
async def get_song_zip(
    song_id: str,
    background_tasks: BackgroundTasks,
    authorization: str = Header(...)
):
    """
    Download all stems for a song as a single ZIP archive.
    Stems are fetched from R2 and zipped on the fly.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify auth
    user = get_authenticated_user(authorization)
    
    # 1. Find the stems
    prefixes = get_user_storage_prefixes(user)
    found_keys = []
    for user_prefix in prefixes:
        prefix = f"{user_prefix}{song_id}/"
        try:
            response = s3_client.list_objects_v2(Bucket=R2_BUCKET_NAME, Prefix=prefix)
            if 'Contents' in response:
                for obj in response['Contents']:
                    if obj['Key'].endswith('.mp3'):
                        found_keys.append(obj['Key'])
                if found_keys:
                    break
        except Exception as e:
            logger.error(f"Error listing objects for ZIP: {e}")
            continue
            
    if not found_keys:
        raise HTTPException(status_code=404, detail="No stems found for this song")
        
    # 2. Create ZIP
    temp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
    try:
        with zipfile.ZipFile(temp_zip.name, 'w', zipfile.ZIP_DEFLATED) as zf:
            for key in found_keys:
                filename = os.path.basename(key)
                try:
                    obj = s3_client.get_object(Bucket=R2_BUCKET_NAME, Key=key)
                    zf.writestr(filename, obj['Body'].read())
                except Exception as e:
                    logger.error(f"Failed to add {key} to ZIP: {e}")
                    continue
        
        # Add cleanup task
        background_tasks.add_task(os.remove, temp_zip.name)
        
        return FileResponse(
            temp_zip.name, 
            filename=f"stems_{song_id[:8]}.zip", 
            media_type="application/zip"
        )
    except Exception as e:
        if os.path.exists(temp_zip.name):
            os.remove(temp_zip.name)
        logger.error(f"Failed to create ZIP archive: {e}")
        raise HTTPException(status_code=500, detail="Failed to create ZIP archive")


@app.get("/my-songs")
async def list_my_songs(
    authorization: str = Header(...)
):
    """
    List all songs for the authenticated user.
    Returns song_id and metadata for each song.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify token and get UID
    user = get_authenticated_user(authorization)
    uid = user['user_id']
    
    # List candidate user prefixes
    user_prefixes = get_user_storage_prefixes(user)
    
    songs = []
    
    try:
        for user_prefix in user_prefixes:
            response = s3_client.list_objects_v2(
                Bucket=R2_BUCKET_NAME,
                Prefix=user_prefix,
                Delimiter='/'
            )
            
            # Get unique song_ids from CommonPrefixes (directories)
            if 'CommonPrefixes' in response:
                for prefix_obj in response['CommonPrefixes']:
                    current_song_dir_prefix = prefix_obj['Prefix']
                    # Extract song_id from prefix: uploads/.../{song_id}/
                    parts = current_song_dir_prefix.rstrip('/').split('/')
                    if len(parts) >= 3:
                        song_id = parts[-1] # The last part is the song_id
                        
                        # List files in this specific song directory
                        song_response = s3_client.list_objects_v2(
                            Bucket=R2_BUCKET_NAME,
                            Prefix=current_song_dir_prefix
                        )
                        
                        files = []
                        original_title = None
                        
                        if 'Contents' in song_response:
                            for idx, obj in enumerate(song_response['Contents']):
                                filename = obj['Key'].split('/')[-1]
                                if filename:
                                    files.append({
                                        "filename": filename,
                                        "size": obj['Size'],
                                        "last_modified": obj['LastModified'].isoformat()
                                    })
                                    
                                    # Get metadata from file to retrieve original filename
                                    if not original_title:
                                        try:
                                            head_response = s3_client.head_object(
                                                Bucket=R2_BUCKET_NAME,
                                                Key=obj['Key']
                                            )
                                            # Use case-insensitive check for metadata keys
                                            metadata = head_response.get('Metadata', {})
                                            # Boto3/S3 often normalizes keys to lowercase
                                            original_title = metadata.get('original-filename') or metadata.get('original-filename'.lower())
                                        except Exception as e:
                                            logger.warning(f"Failed to get metadata for {obj['Key']}: {e}")
                    
                    if files:  # Only include songs that have files
                        # Use the latest modification time among all files in the song
                        latest_time = max(f['last_modified'] for f in files)
                        songs.append({
                            "song_id": song_id,
                            "title": original_title or f"Song {song_id[:8]}",
                            "files": files,
                            "file_count": len(files),
                            "created_at": latest_time
                        })
        
        # Sort songs by created_at descending (recency)
        songs.sort(key=lambda x: x.get('created_at') or '', reverse=True)
        
        return {
            "uid": uid,
            "songs": songs,
            "count": len(songs)
        }
    except Exception as e:
        logger.error(f"Failed to list user songs: {e}")
        raise HTTPException(status_code=500, detail="Failed to list songs")


@app.delete("/songs/{song_id}")
async def delete_song(
    song_id: str,
    authorization: str = Header(...)
):
    """
    Delete all files for a given song ID from R2.
    Requires Firebase authentication.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify token and get user
    user = get_authenticated_user(authorization)
    
    # Construct candidate prefixes
    user_prefixes = get_user_storage_prefixes(user)
    
    try:
        deleted_any = False
        for user_prefix in user_prefixes:
            prefix = f"{user_prefix}{song_id}/"
            # Find all objects to delete
            response = s3_client.list_objects_v2(
                Bucket=R2_BUCKET_NAME,
                Prefix=prefix
            )
            
            if 'Contents' in response:
                delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
                s3_client.delete_objects(
                    Bucket=R2_BUCKET_NAME,
                    Delete=delete_objects
                )
                logger.info(f"Deleted {len(delete_objects['Objects'])} objects for song {song_id} in prefix {prefix}")
                deleted_any = True
        
        return {"message": f"Song {song_id} deleted successfully"}
    except Exception as e:
        logger.error(f"Failed to delete song {song_id}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete song")


@app.delete("/songs")
async def delete_all_songs(
    authorization: str = Header(...)
):
    """
    Delete all files for the authenticated user from R2.
    """
    if not R2_ENABLED:
        raise HTTPException(status_code=503, detail="R2 storage not configured")
    
    # Verify token and get user
    user = get_authenticated_user(authorization)
    uid = user['user_id']
    
    # Construct candidate prefixes
    user_prefixes = get_user_storage_prefixes(user)
    
    try:
        deleted_count = 0
        for prefix in user_prefixes:
            # Paginating delete if there are many objects
            while True:
                response = s3_client.list_objects_v2(
                    Bucket=R2_BUCKET_NAME,
                    Prefix=prefix
                )
                
                if 'Contents' not in response:
                    break
                    
                delete_objects = {'Objects': [{'Key': obj['Key']} for obj in response['Contents']]}
                s3_client.delete_objects(
                    Bucket=R2_BUCKET_NAME,
                    Delete=delete_objects
                )
                deleted_count += len(delete_objects['Objects'])
                
                # If there are more objects, they will be picked up in next iteration
                if not response.get('IsTruncated'):
                    break
                    
        logger.info(f"Deleted all {deleted_count} objects for user {uid}")
        return {"message": f"All {deleted_count} objects deleted successfully"}
    except Exception as e:
        logger.error(f"Failed to delete all songs for user {uid}: {e}")
        raise HTTPException(status_code=500, detail="Failed to delete all songs")


if __name__ == "__main__":
    import uvicorn
    # Default to 7860 for Hugging Face Spaces
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))