File size: 91,258 Bytes
b787014
 
 
 
 
 
 
7619ebb
2f3a344
 
657f05a
9ea78e2
 
 
657f05a
58dfc5d
 
 
 
 
98b17ac
 
 
 
 
 
fd497ef
 
 
 
 
 
 
98b17ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8af9b
98b17ac
 
 
 
 
 
 
 
 
 
 
 
e8c2c65
42b1c21
e8c2c65
 
 
 
 
 
98b17ac
 
e8c2c65
 
 
98b17ac
 
 
 
 
 
e8c2c65
98b17ac
 
 
 
 
7619ebb
 
2f3a344
e2484a8
 
 
 
 
 
 
 
 
 
 
 
 
 
65c566e
 
 
 
65199af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2484a8
e791e9a
 
 
 
 
 
 
 
 
 
 
2f3a344
e2484a8
 
e791e9a
2f3a344
 
 
 
 
 
 
 
 
 
27c2644
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
27c2644
 
 
 
 
8ef4a8d
27c2644
2f3a344
 
9ea78e2
 
 
 
 
e791e9a
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e791e9a
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd7e522
9ea78e2
 
 
 
b83e38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08a3866
 
b83e38d
08a3866
 
 
 
 
 
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b657f
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe8af9b
9ea78e2
 
fe8af9b
 
9ea78e2
fe8af9b
 
9ea78e2
fe8af9b
 
 
 
 
 
 
 
 
 
9ea78e2
98b17ac
 
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5771bd
 
 
 
 
 
 
 
 
 
 
 
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e791e9a
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
e791e9a
9ea78e2
 
 
 
 
 
 
e791e9a
9ea78e2
 
e791e9a
 
 
 
 
 
 
9ea78e2
99df3ef
2f3a344
b787014
 
 
 
 
 
 
2f3a344
b787014
 
 
 
 
 
e51d074
 
e8c3f30
 
 
 
 
 
 
 
 
 
 
 
 
 
b787014
 
 
 
c6b657f
616179f
 
 
 
 
 
 
b787014
 
 
 
 
bb235ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f5314a
 
 
 
 
bb235ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f5314a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb235ca
8f5314a
 
 
 
 
 
bb235ca
 
 
 
 
b787014
2f3a344
 
 
 
 
 
 
 
 
 
 
 
 
 
e2484a8
2f3a344
 
e2484a8
2f3a344
 
 
 
 
b787014
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
 
 
 
 
 
 
 
 
b787014
 
 
bb235ca
 
9ea78e2
 
bdb76da
 
2f3a344
 
27c2644
88ed64a
 
 
 
27c2644
 
 
 
 
88ed64a
27c2644
 
 
88ed64a
 
 
 
 
27c2644
88ed64a
2f3a344
 
 
88ed64a
 
 
 
 
 
 
 
b787014
 
 
 
2f3a344
 
 
 
 
 
 
bd4aec3
 
2f3a344
 
88ed64a
 
 
 
2f3a344
b787014
 
 
 
 
 
 
 
 
ad2a521
 
27c2644
 
946d58b
 
657f05a
 
b787014
 
 
2f3a344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09dab92
 
2f3a344
 
e2484a8
2f3a344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ef4a8d
2f3a344
 
 
 
 
e2484a8
 
2f3a344
 
 
 
 
 
 
 
 
88ed64a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
 
 
 
 
 
 
 
 
 
e2484a8
2f3a344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2484a8
 
2f3a344
27c2644
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
27c2644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
27c2644
 
 
 
 
2f3a344
 
 
946d58b
 
 
 
 
 
 
 
 
 
 
 
657f05a
 
 
 
946d58b
 
 
 
 
657f05a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946d58b
657f05a
 
 
 
 
 
946d58b
657f05a
 
 
 
 
 
 
 
 
 
 
 
 
 
946d58b
657f05a
 
 
 
 
 
 
 
 
 
 
946d58b
 
657f05a
 
 
 
 
 
 
 
 
 
 
 
 
 
946d58b
 
657f05a
946d58b
 
657f05a
946d58b
 
 
657f05a
 
 
946d58b
 
657f05a
 
 
 
 
 
 
 
946d58b
 
 
 
657f05a
946d58b
657f05a
 
946d58b
657f05a
 
 
 
946d58b
 
 
 
 
 
 
 
 
 
657f05a
946d58b
657f05a
946d58b
 
 
 
657f05a
946d58b
 
 
 
 
657f05a
946d58b
 
 
b787014
 
2f3a344
 
 
 
 
9ea78e2
65199af
 
 
 
 
 
 
9ea78e2
65199af
 
27c2644
 
 
 
 
65199af
27c2644
 
 
 
65199af
27c2644
bb235ca
9ea78e2
 
bb235ca
9ea78e2
 
 
 
bb235ca
9ea78e2
 
 
 
 
 
 
bb235ca
9ea78e2
 
b787014
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b787014
9ea78e2
b787014
 
 
 
2f3a344
 
 
 
 
b787014
 
 
 
 
 
 
cd7e522
b787014
 
 
 
 
e2484a8
b787014
 
 
 
 
 
95ef053
 
b787014
95ef053
 
b787014
 
95ef053
 
 
 
 
 
 
 
 
b787014
 
 
 
 
 
 
2f3a344
b787014
 
 
 
 
 
 
 
 
2f3a344
b787014
 
 
 
2f3a344
 
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
 
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
e2484a8
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8c3f30
 
 
 
 
 
 
 
b787014
 
 
 
 
 
 
 
bb235ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b787014
 
 
bb235ca
 
b787014
 
 
 
 
 
 
 
 
 
 
 
2f3a344
b787014
 
 
 
 
 
 
 
 
 
 
 
2f3a344
b787014
 
 
 
 
 
 
 
7619ebb
 
b787014
7619ebb
b787014
 
2f3a344
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
27c2644
 
 
 
 
 
 
 
 
 
 
 
 
 
9ea78e2
 
bb235ca
9ea78e2
 
 
 
b787014
9ea78e2
 
 
 
 
 
 
 
 
b787014
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
27c2644
9ea78e2
 
 
 
b787014
 
9ea78e2
b787014
 
bb235ca
 
 
 
 
 
73c6b6b
bb235ca
 
 
73c6b6b
 
 
 
e8c3f30
 
 
 
 
 
 
 
73c6b6b
bb235ca
 
 
 
c6b657f
bb235ca
73c6b6b
bb235ca
 
 
 
 
 
 
 
9ea78e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdb76da
9ea78e2
 
 
 
 
 
 
 
 
 
 
bdb76da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b787014
 
2f3a344
 
 
 
 
e2484a8
 
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
b787014
 
 
 
 
95ef053
b787014
 
0257786
b787014
95ef053
 
e8c3f30
 
 
 
 
 
 
 
 
 
 
 
95ef053
 
e8c3f30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b787014
 
 
95ef053
 
e8c3f30
b787014
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
 
 
 
 
b787014
 
 
 
 
 
 
 
 
 
 
 
e2484a8
b787014
e2484a8
b787014
 
 
 
 
 
 
 
 
7619ebb
 
 
 
 
b787014
 
 
 
0257786
b787014
 
7619ebb
 
 
 
 
b787014
 
 
 
 
 
 
 
 
 
 
ad2a521
 
2f3a344
 
 
 
 
ad2a521
 
 
 
 
 
 
 
 
 
 
 
e2484a8
ad2a521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
ad2a521
 
 
 
48672d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad2a521
 
 
 
 
48672d3
ad2a521
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f3a344
ad2a521
 
 
 
 
b787014
 
 
 
 
 
 
2f3a344
b787014
99df3ef
b787014
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
import os
import sys
import json
import base64
import tempfile
import shutil
import time
import socket
import sqlite3
import hashlib
import hmac
import queue
import threading
import uuid

# Automatically include local venv site-packages if present
venv_site = os.path.join(os.path.dirname(__file__), '..', 'venv', 'lib', f'python{sys.version_info.major}.{sys.version_info.minor}', 'site-packages')
if os.path.exists(venv_site) and venv_site not in sys.path:
    sys.path.insert(0, os.path.abspath(venv_site))

def sanitize_and_ensure_transparent_subject(img_path, client=None):
    """
    Verifies if an image has a clean transparent background for 3D generation.
    If the image lacks transparency (alpha < 10%), performs an automatic center-weighted
    crop fallback and re-preprocesses it to isolate the central subject.
    """
    try:
        from PIL import Image
        import numpy as np
    except ImportError as ie:
        print(f"[Backend Preprocessing] Pillow or numpy not installed: {ie}. Skipping advanced transparency sanitation.")
        return img_path

    try:
        if not os.path.exists(img_path):
            return img_path

        img = Image.open(img_path).convert('RGBA')
        width, height = img.size
        
        # Calculate alpha coverage
        alpha_channel = np.array(img.split()[3])
        transparent_ratio = np.mean(alpha_channel < 30)
        
        print(f"[Backend Preprocessing] Alpha transparency ratio: {transparent_ratio * 100:.2f}%")
        
        # If image is > 90% solid (less than 10% transparency), remote RMBG failed
        if transparent_ratio < 0.10:
            print("[Backend Preprocessing] Solid image detected (RMBG failed or no transparency). Applying smart center-crop fallback...")
            
            # Crop central 80% to eliminate edge distractions (pillows, beds, frames)
            crop_margin_w = int(width * 0.10)
            crop_margin_h = int(height * 0.10)
            cropped_img = img.crop((crop_margin_w, crop_margin_h, width - crop_margin_w, height - crop_margin_h))
            
            # Save cropped temporary file
            cropped_temp_path = img_path.replace(".png", "_cropped_fallback.png").replace(".jpg", "_cropped_fallback.png")
            cropped_img.save(cropped_temp_path, "PNG")
            
            # Try re-running remote preprocess_image on the cropped subject
            if client:
                try:
                    from gradio_client import handle_file
                    res = client.predict(handle_file(cropped_temp_path), True, api_name="/preprocess_image")
                    path_val = res.get('path') if isinstance(res, dict) else res
                    if path_val and os.path.exists(path_val):
                        img = Image.open(path_val).convert('RGBA')
                        print("[Backend Preprocessing] Re-preprocessing with central focus succeeded!")
                    else:
                        img = cropped_img
                except Exception as e:
                    print(f"[Backend Preprocessing] Re-preprocessing fallback warning: {e}")
                    img = cropped_img
            else:
                img = cropped_img

        # Scale subject down slightly so it occupies ~80% of the canvas with generous margins (prevents border distortions)
        max_dim = max(img.size[0], img.size[1])
        target_size = int(max_dim * 0.82)
        ratio = min(target_size / img.size[0], target_size / img.size[1])
        new_w = max(1, int(img.size[0] * ratio))
        new_h = max(1, int(img.size[1] * ratio))
        img_resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)

        # Pad and center on a square transparent canvas with margin
        square_canvas = Image.new('RGBA', (max_dim, max_dim), (0, 0, 0, 0))
        offset_x = (max_dim - new_w) // 2
        offset_y = (max_dim - new_h) // 2
        square_canvas.paste(img_resized, (offset_x, offset_y), img_resized)
        
        final_1024 = square_canvas.resize((1024, 1024), Image.Resampling.LANCZOS)
        out_path = img_path.replace(".png", "_preprocessed_clean.png").replace(".jpg", "_preprocessed_clean.png")
        if out_path == img_path:
            out_path = img_path + "_clean.png"
        final_1024.save(out_path, "PNG")
        print(f"[Backend Preprocessing] Clean 1024x1024 padded transparent image prepared: {out_path}")
        return out_path
    except Exception as err:
        print(f"[Backend Preprocessing] Exception in sanitize_and_ensure_transparent_subject: {err}")
        return img_path

# Set a generous timeout (5 minutes) to allow sleeping Hugging Face Spaces to wake up
socket.setdefaulttimeout(300)

# Check if persistent volume is mounted on Hugging Face (/data)
PERSISTENT_DIR = '/data' if (os.path.exists('/data') and os.path.isdir('/data')) else None

def get_db_path():
    if PERSISTENT_DIR:
        return os.path.join(PERSISTENT_DIR, 'users.db')
    return os.path.join(os.path.dirname(__file__), 'data', 'users.db')

def get_generated_dir(subfolder, username=None):
    if PERSISTENT_DIR:
        base = os.path.join(PERSISTENT_DIR, 'generated', subfolder)
    else:
        base = os.path.join(os.path.dirname(__file__), 'generated', subfolder)
    
    if username:
        return os.path.join(base, username)
    return base

def calculate_3d_cost(resolution, texture_size):
    cost = 5
    try:
        res_val = int(resolution)
        if res_val >= 1536:
            cost += 2
    except ValueError:
        if str(resolution) == '1536':
            cost += 2

    try:
        tex_val = int(texture_size)
        if tex_val >= 4096:
            cost += 3
    except ValueError:
        pass
    return cost

def get_db_connection():
    """
    Returns a thread-safe SQLite connection configured with WAL (Write-Ahead Logging)
    and a generous timeout to support simultaneous concurrent database access across multiple worker threads.
    """
    db_path = get_db_path()
    conn = sqlite3.connect(db_path, timeout=30.0)
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA synchronous=NORMAL;")
    return conn

def init_db():
    db_path = get_db_path()
    os.makedirs(os.path.dirname(db_path), exist_ok=True)
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS users (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            username TEXT UNIQUE NOT NULL,
            password_hash TEXT NOT NULL,
            salt TEXT NOT NULL,
            created_at REAL NOT NULL
        )
    ''')
    
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS jobs (
            id TEXT PRIMARY KEY,
            username TEXT NOT NULL,
            type TEXT NOT NULL,
            status TEXT NOT NULL,
            progress INTEGER DEFAULT 0,
            message TEXT,
            result TEXT,
            created_at REAL NOT NULL,
            updated_at REAL NOT NULL
        )
    ''')
    
    # Check and add 'credits' column if not exists (database migration)
    cursor.execute("PRAGMA table_info(users)")
    columns = [row[1] for row in cursor.fetchall()]
    if 'credits' not in columns:
        print("[Database] Migrating: Adding 'credits' column to users table.")
        cursor.execute("ALTER TABLE users ADD COLUMN credits INTEGER DEFAULT 20")
        
    conn.commit()
    conn.close()

job_queue = queue.Queue()

def update_job_status(job_id, status, progress=None, message=None, result=None):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        
        now = time.time()
        updates = [("status", status), ("updated_at", now)]
        if progress is not None:
            updates.append(("progress", progress))
        if message is not None:
            updates.append(("message", message))
        if result is not None:
            if isinstance(result, (dict, list)):
                result_str = json.dumps(result)
            else:
                result_str = str(result)
            updates.append(("result", result_str))
            
        set_clause = ", ".join([f"{col} = ?" for col, _ in updates])
        values = [val for _, val in updates]
        values.append(job_id)
        
        cursor.execute(f"UPDATE jobs SET {set_clause} WHERE id = ?", values)
        conn.commit()
        conn.close()
    except Exception as e:
        print(f"[Backend Error updating job status] job={job_id} error={e}")

def refund_credits(username, amount):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET credits = credits + ? WHERE username = ?", (amount, username))
        conn.commit()
        conn.close()
        print(f"[Backend] Successfully refunded {amount} credits to user {username}")
    except Exception as e:
        print(f"[Backend Error refunding credits] user={username} error={e}")

def execute_job_3d(job_id, username, params):
    temp_img_path = None
    client = None
    try:
        update_job_status(job_id, 'processing', progress=10, message="Iniciando generación de malla 3D...")
        
        version = params.get('version', 'v2')
        image_data_b64 = params.get('image') # Base64 encoded image
        hf_token = params.get('token', '')
        seed = float(params.get('seed', 0))
        resolution = params.get('resolution', '1024')
        decimation_target = int(params.get('decimation_target', 300000))
        texture_size = int(params.get('texture_size', 2048))
        ss_guidance = float(params.get('ss_guidance', 7.5))
        ss_steps = int(params.get('ss_steps', 12))
        slat_guidance = float(params.get('slat_guidance', 3.0))
        slat_steps = int(params.get('slat_steps', 12))
        auto_optimize = params.get('auto_optimize', False)
        quad_target_faces = int(params.get('quad_target_faces', 60000))
        prompt = params.get('prompt', '')
        remesh_method = params.get('remeshMethod', 'cleanup')

        if not image_data_b64:
            raise Exception("No image data provided")

        if isinstance(image_data_b64, str) and ('generated_images' in image_data_b64 or 'generated_models' in image_data_b64):
            clean_url = image_data_b64.split('?')[0]
            parts = [p for p in clean_url.split('/') if p]
            
            disk_path = None
            if len(parts) >= 3 and parts[-3] == 'generated_images':
                disk_path = os.path.join(get_generated_dir('images', parts[-2]), parts[-1])
            elif len(parts) >= 3 and parts[-3] == 'generated_models':
                disk_path = os.path.join(get_generated_dir('models', parts[-2]), parts[-1])
            else:
                rel_path = clean_url.lstrip('/')
                if os.path.exists(rel_path):
                    disk_path = rel_path

            if disk_path and os.path.exists(disk_path):
                with open(disk_path, 'rb') as f:
                    image_bytes = f.read()
            else:
                raise Exception(f"No se encontró la imagen en el servidor: {clean_url}")
        elif isinstance(image_data_b64, str) and os.path.exists(image_data_b64):
            with open(image_data_b64, 'rb') as f:
                image_bytes = f.read()
        else:
            if ',' in image_data_b64:
                image_data_b64 = image_data_b64.split(',')[1]
            image_bytes = base64.b64decode(image_data_b64)

        # Save to temporary file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_img:
            temp_img.write(image_bytes)
            temp_img_path = temp_img.name

        # Setup Connection options
        connect_options = {}
        current_token = os.environ.get('HF_TOKEN', '').strip()
        hf_token_clean = str(hf_token).strip() if hf_token else ''
        if hf_token_clean in ('null', 'undefined'):
            hf_token_clean = ''
        
        is_hf_space = 'SPACE_ID' in os.environ
        if is_hf_space:
            token_to_use = hf_token_clean if hf_token_clean else current_token
        else:
            token_to_use = current_token
        if token_to_use == 'PON_TU_TOKEN_AQUI':
            token_to_use = ''
        token_to_use = token_to_use.strip()
        
        if token_to_use:
            connect_options['token'] = token_to_use
        else:
            raise Exception("Falta el Token de Hugging Face. Por favor, asegúrate de que esté configurado.")

        target_space = os.environ.get('HF_SPACE', 'microsoft/TRELLIS.2')
        
        update_job_status(job_id, 'processing', progress=20, message="Verificando estado del servidor de IA...")
        stage = get_space_status(target_space, token_to_use)
        if stage == "PAUSED":
            raise Exception(f"El Space '{target_space}' está PAUSADO.")
        elif stage in ("STOPPED", "ERROR"):
            raise Exception(f"El Space '{target_space}' está APAGADO o tiene un ERROR (Estado: {stage}).")
        elif stage == "SLEEPING":
            update_job_status(job_id, 'processing', progress=25, message="Despertando servidor de IA (esto demora 2-3 minutos)...")
        
        update_job_status(job_id, 'processing', progress=30, message="Conectando al servidor de IA...")
        client = Client(target_space, **connect_options)
        
        try:
            client.predict(api_name="/start_session")
        except Exception as se:
            print(f"[Backend] Remote session initialization warning: {se}")

        # Preprocessing & Background Removal Pipeline
        preprocessed_img_path = temp_img_path
        try:
            update_job_status(job_id, 'processing', progress=40, message="Removiendo fondo de imagen (Pre-procesamiento)...")
            preprocess_result = client.predict(handle_file(temp_img_path), True, api_name="/preprocess_image")
            path_val = preprocess_result.get('path') if isinstance(preprocess_result, dict) else preprocess_result
            if path_val and os.path.exists(str(path_val)):
                preprocessed_img_path = str(path_val)
        except Exception as pe:
            print(f"[Backend] Primary Trellis /preprocess_image failed or missing argument: {pe}. Trying RMBG-1.4 fallback...")
            try:
                rmbg_client = Client("briaai/BRIA-RMBG-1.4", **connect_options)
                rmbg_res = rmbg_client.predict(handle_file(temp_img_path), api_name="/rmbg")
                path_val = rmbg_res.get('path') if isinstance(rmbg_res, dict) else rmbg_res
                if path_val and os.path.exists(str(path_val)):
                    preprocessed_img_path = str(path_val)
                    print("[Backend] RMBG-1.4 dedicated background removal succeeded!")
            except Exception as rmbg_err:
                print(f"[Backend] Dedicated RMBG-1.4 fallback failed: {rmbg_err}")

        # Sanitize and ensure transparent subject padding for 3D reconstruction
        preprocessed_img_path = sanitize_and_ensure_transparent_subject(preprocessed_img_path, client)

        update_job_status(job_id, 'processing', progress=50, message="Construyendo representación 3D (Inferencia de IA)...")
        job = client.submit(
            handle_file(preprocessed_img_path),
            seed,
            resolution,
            ss_guidance,
            0.7,
            ss_steps,
            5.0,
            slat_guidance,
            0.5,
            slat_steps,
            3.0,
            1.0,
            0.0,
            12,
            3.0,
            api_name="/image_to_3d"
        )
        job.result()

        update_job_status(job_id, 'processing', progress=75, message="Extrayendo texturas PBR y generando archivo GLB...")
        extract_job = client.submit(
            decimation_target,
            texture_size,
            api_name="/extract_glb"
        )
        extract_result = extract_job.result()

        if hasattr(extract_result, 'data') and extract_result.data and len(extract_result.data) >= 2:
            gltf_file = extract_result.data[0]
            glb_file = extract_result.data[1]
        elif isinstance(extract_result, (list, tuple)) and len(extract_result) >= 2:
            gltf_file = extract_result[0]
            glb_file = extract_result[1]
        else:
            raise Exception("extract_glb no retornó los archivos esperados.")

        output_dir = get_generated_dir("models", username)
        os.makedirs(output_dir, exist_ok=True)

        gltf_local_path = gltf_file.get('path') if isinstance(gltf_file, dict) else (gltf_file if isinstance(gltf_file, str) else None)
        glb_local_path = glb_file.get('path') if isinstance(glb_file, dict) else (glb_file if isinstance(glb_file, str) else None)

        filename = f"model_{int(time.time())}.glb"
        dest_path = os.path.join(output_dir, filename)

        if glb_local_path and os.path.exists(glb_local_path):
            shutil.copy(glb_local_path, dest_path)
            
            update_job_status(job_id, 'processing', progress=85, message="Generando versión FBX lista para descargas...")
            blender_path = os.environ.get('BLENDER_PATH', '')
            if not blender_path or not os.path.exists(blender_path):
                blender_path = shutil.which("blender") or ""
            if blender_path and os.path.exists(blender_path):
                import subprocess
                script_path = os.path.join(os.path.dirname(__file__), "scripts", "blender", "clean_mesh_blender.py")
                cmd = [blender_path, "--background", "--python", script_path, "--", dest_path, dest_path, str(quad_target_faces), remesh_method]
                print(f"[Backend Background Worker] Generating FBX immediately: {' '.join(cmd)}")
                try:
                    subprocess.run(cmd, capture_output=True, text=True, timeout=90)
                except Exception as be:
                    print(f"[Backend Background Worker] Immediate FBX export note: {be}")

            gltf_url = f"/generated_models/{username}/{filename}"
            glb_url = f"/generated_models/{username}/{filename}"
            fbx_filename = filename.replace(".glb", ".fbx")
            fbx_url = f"/generated_models/{username}/{fbx_filename}" if os.path.exists(os.path.join(output_dir, fbx_filename)) else None
        else:
            gltf_url = gltf_file.get('url') if isinstance(gltf_file, dict) else gltf_local_path
            glb_url = glb_file.get('url') if isinstance(glb_file, dict) else glb_local_path
            fbx_url = None

        update_job_status(job_id, 'processing', progress=95, message="Clasificando especie del modelo...")
        detected_category = classify_species(image_bytes, prompt, token_to_use)

        if glb_local_path and os.path.exists(glb_local_path):
            metadata_path = dest_path.replace(".glb", ".json")
            try:
                with open(metadata_path, "w", encoding="utf-8") as meta_f:
                    json.dump({
                        "detectedCategory": detected_category,
                        "prompt": prompt,
                        "timestamp": time.time()
                    }, meta_f, indent=2)
            except Exception as me:
                print(f"[Backend] Metadata warning: {me}")

        result_payload = {
            "gltfUrl": gltf_url,
            "glbUrl": glb_url,
            "fbxUrl": fbx_url,
            "detectedCategory": detected_category
        }
        
        update_job_status(job_id, 'completed', progress=100, message="Generación 3D completada con éxito.", result=result_payload)
        
    except Exception as ex:
        print(f"[Backend Job Error] job={job_id} error={ex}")
        update_job_status(job_id, 'failed', message=f"Fallo en la generación: {str(ex)}")
        # Refund credits
        refund_credits(username, params.get('cost', 5))
    finally:
        if temp_img_path:
            try:
                os.unlink(temp_img_path)
            except:
                pass
        if client:
            try:
                client.close()
            except:
                pass

def execute_job_2d(job_id, username, params):
    from gradio_client import Client as GradioClient
    try:
        update_job_status(job_id, 'processing', progress=20, message="Conectando al servidor FLUX de imágenes...")
        prompt = params.get('prompt', '')
        hf_token = params.get('token', '')

        current_token = os.environ.get('HF_TOKEN', '').strip()
        hf_token_clean = str(hf_token).strip() if hf_token else ''
        if hf_token_clean in ('null', 'undefined'):
            hf_token_clean = ''
        
        is_hf_space = 'SPACE_ID' in os.environ
        if is_hf_space:
            token_to_use = hf_token_clean if hf_token_clean else current_token
        else:
            token_to_use = current_token
        if token_to_use == 'PON_TU_TOKEN_AQUI':
            token_to_use = ''
        token_to_use = token_to_use.strip()

        connect_options = {}
        if token_to_use:
            connect_options['token'] = token_to_use
        else:
            raise Exception("Falta el Token de Hugging Face.")

        spaces_to_try = [
            "black-forest-labs/FLUX.1-schnell",
            "multimodalart/FLUX.1-schnell"
        ]

        success = False
        response_data = None
        last_error = None

        for space_name in spaces_to_try:
            client = None
            try:
                update_job_status(job_id, 'processing', progress=40, message=f"Generando imagen vía {space_name}...")
                client = GradioClient(space_name, **connect_options)
                result = client.predict(
                    prompt=prompt,
                    seed=0,
                    randomize_seed=True,
                    width=1024,
                    height=1024,
                    num_inference_steps=4,
                    api_name="/infer"
                )

                if isinstance(result, (list, tuple)) and len(result) > 0:
                    img_local_path = result[0]
                elif isinstance(result, dict) and 'path' in result:
                    img_local_path = result['path']
                else:
                    img_local_path = result

                if img_local_path and os.path.exists(img_local_path):
                    with open(img_local_path, "rb") as img_file:
                        img_bytes = img_file.read()
                    
                    images_dir = get_generated_dir("images", username)
                    os.makedirs(images_dir, exist_ok=True)
                    img_filename = f"image_{int(time.time())}.png"
                    img_dest_path = os.path.join(images_dir, img_filename)
                    with open(img_dest_path, "wb") as f:
                        f.write(img_bytes)

                    img_b64 = base64.b64encode(img_bytes).decode('utf-8')
                    response_data = {
                        "image": f"data:image/png;base64,{img_b64}",
                        "imageUrl": f"/generated_images/{username}/{img_filename}",
                        "model_used": space_name
                    }
                    success = True
                    break
                else:
                    raise Exception(f"La ruta devuelta no existe: {img_local_path}")
            except Exception as ex:
                last_error = str(ex)
            finally:
                if client:
                    try:
                        client.close()
                    except:
                        pass

        if success and response_data:
            update_job_status(job_id, 'completed', progress=100, message="Generación de imagen completada.", result=response_data)
        else:
            raise Exception(f"Fallaron todos los Spaces de FLUX. Último error: {last_error}")

    except Exception as ex:
        print(f"[Backend Job Error] job={job_id} error={ex}")
        update_job_status(job_id, 'failed', message=f"Error al generar imagen 2D: {str(ex)}")
        refund_credits(username, params.get('cost', 1))

def background_worker(worker_id):
    print(f"[Backend Background Worker #{worker_id}] Starting worker thread...")
    while True:
        try:
            job = job_queue.get()
            if job is None:
                break
                
            job_id = job["id"]
            username = job["username"]
            job_type = job["type"]
            params = job["params"]
            
            print(f"[Backend Background Worker #{worker_id}] Processing job={job_id} user={username} type={job_type}")
            if job_type == '3d':
                execute_job_3d(job_id, username, params)
            elif job_type == '2d':
                execute_job_2d(job_id, username, params)
                
            job_queue.task_done()
        except Exception as we:
            print(f"[Backend Background Worker #{worker_id} Exception] {we}")
            time.sleep(1)

# Spawn a pool of worker threads for parallel job processing
NUM_WORKER_THREADS = 4
worker_threads = []
for i in range(NUM_WORKER_THREADS):
    t = threading.Thread(target=background_worker, args=(i + 1,), daemon=True)
    t.start()
    worker_threads.append(t)

from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
# pyrefly: ignore [missing-import]
from gradio_client import Client, handle_file

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

# Simple environment loader to avoid external dependencies
def load_dotenv():
    env_path = os.path.join(os.path.dirname(__file__), '.env')
    if os.path.exists(env_path):
        with open(env_path, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, val = line.split('=', 1)
                    key_str = key.strip()
                    val_str = val.strip()
                    
                    is_hf_space = 'SPACE_ID' in os.environ
                    current_val = os.environ.get(key_str, '').strip()
                    
                    # Update/overwrite if:
                    # 1. Variable not already set in environment
                    # 2. Or current value is empty/placeholder
                    # 3. Or we are running locally (not HF Spaces)
                    if (key_str not in os.environ or 
                        current_val in ('', 'PON_TU_TOKEN_AQUI', 'null', 'undefined') or 
                        not is_hf_space):
                        # Avoid overwriting a valid token in the environment with a placeholder from .env
                        if not (val_str == 'PON_TU_TOKEN_AQUI' and current_val.startswith('hf_')):
                            os.environ[key_str] = val_str

# Initialize configuration
load_dotenv()
HF_TOKEN = os.environ.get('HF_TOKEN', '')
HF_SPACE = os.environ.get('HF_SPACE', 'microsoft/TRELLIS.2')

# Hugging Face Spaces always runs on port 7860
if 'SPACE_ID' in os.environ:
    PORT = 7860
    print(f"[Backend] Running inside Hugging Face Space. Forcing PORT to {PORT}")
else:
    PORT = int(os.environ.get('PORT', '8000'))

if not HF_TOKEN or HF_TOKEN == 'PON_TU_TOKEN_AQUI':
    print("\n[⚠️ WARNING] HF_TOKEN is not configured or has default placeholder value in .env file.")
    print("Please open the '.env' file and insert your Hugging Face Token (hf_...) to access your private Space.\n")

def get_space_status(space_id, token=None):
    """
    Checks the current status of a Hugging Face Space.
    Returns the stage string, e.g. 'RUNNING', 'SLEEPING', 'PAUSED', 'STOPPED', 'ERROR', or 'UNKNOWN'.
    """
    import requests
    url = f"https://huggingface.co/api/spaces/{space_id}"
    headers = {}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    try:
        r = requests.get(url, headers=headers, timeout=5)
        if r.status_code == 200:
            data = r.json()
            runtime = data.get("runtime", {})
            stage = runtime.get("stage", "UNKNOWN").upper()
            return stage
        else:
            print(f"[Space Status] Failed to fetch status for {space_id}: HTTP {r.status_code}")
            return "UNKNOWN"
    except Exception as e:
        print(f"[Space Status] Error checking status for {space_id}: {e}")
        return "UNKNOWN"

def classify_species(image_bytes, prompt_text, hf_token):
    p = prompt_text.lower() if prompt_text else ""
    
    # Spider / Insect keywords
    spider_words = ["spider", "araña", "aracnido", "arachnid", "tarantula", "insect", "insecto", "crab", "cangrejo", "scorpion", "escorpion", "bug"]
    if any(w in p for w in spider_words):
        print(f"[Classifier] Detected 'unsupported' category from prompt: '{prompt_text}'")
        return "unsupported"
        
    # Quadruped keywords
    quad_words = ["horse", "caballo", "dog", "perro", "cat", "gato", "wolf", "lobo", "lion", "leon", "tiger", "tigre", "cow", "vaca", "sheep", "oveja", "pig", "cerdo", "fox", "zorro", "deer", "ciervo", "bear", "oso", "quadruped", "cuadrupedo", "animal", "camel", "camello", "elephant", "elefante", "giraffe", "jirafa"]
    if any(w in p for w in quad_words):
        print(f"[Classifier] Detected 'local_quadruped' category from prompt: '{prompt_text}'")
        return "local_quadruped"

    # Humanoid keywords
    humanoid_words = ["human", "humano", "man", "hombre", "woman", "mujer", "boy", "chico", "girl", "chica", "character", "personaje", "soldier", "soldado", "warrior", "guerrero", "wizard", "mago", "hero", "heroe", "knight", "caballero", "robot", "biped", "bipedo", "alien", "cyborg", "golem"]
    if any(w in p for w in humanoid_words):
        print(f"[Classifier] Detected 'ai' category from prompt: '{prompt_text}'")
        return "ai"

    # 2. Image classification fallback via CLIP on HF
    if not hf_token or hf_token in ('null', 'undefined'):
        print("[Classifier] No HF Token for image classification. Defaulting to 'ai'.")
        return "ai"
        
    try:
        import requests
        headers = {"Authorization": f"Bearer {hf_token}"}
        urls_to_try = [
            "https://api-inference.huggingface.co/models/openai/clip-vit-large-patch14",
            "https://router.huggingface.co/hf-inference/models/openai/clip-vit-large-patch14",
            "https://api-inference.hf.co/models/openai/clip-vit-large-patch14"
        ]
        img_b64 = base64.b64encode(image_bytes).decode('utf-8')
        
        payload = {
            "image": img_b64,
            "parameters": {
                "candidate_labels": [
                    "a bipedal humanoid character or person",
                    "a four-legged animal or quadruped",
                    "a spider or multi-legged insect",
                    "an object, prop or static furniture"
                ]
            }
        }
        
        print("[Classifier] Querying CLIP zero-shot classification on Hugging Face...")
        for api_url in urls_to_try:
            try:
                response = requests.post(api_url, headers=headers, json=payload, timeout=8)
                if response.status_code == 200:
                    res_data = response.json()
                    if isinstance(res_data, list) and len(res_data) > 0:
                        best_label = res_data[0].get("label", "")
                        score = res_data[0].get("score", 0.0)
                        print(f"[Classifier] CLIP result: {best_label} (score: {score:.3f})")
                        
                        if "bipedal" in best_label:
                            return "ai"
                        elif "four-legged" in best_label:
                            return "local_quadruped"
                        elif "spider" in best_label:
                            return "unsupported"
                        else:
                            return "unsupported"
                else:
                    err_preview = response.text[:200] if response.text else ""
                    if "<!DOCTYPE" in err_preview or "<html" in err_preview.lower():
                        err_preview = f"HTML error response ({response.status_code})"
                    print(f"[Classifier] API {api_url} returned status {response.status_code}: {err_preview}")
            except Exception as req_err:
                print(f"[Classifier] Request to {api_url} failed: {req_err}")
    except Exception as e:
        print(f"[Classifier] Image classification failed: {e}")
        
    return "ai"

class F23DHTTPRequestHandler(SimpleHTTPRequestHandler):
    def translate_path(self, path):
        import urllib
        path = urllib.parse.unquote(path)
        path = path.split('?', 1)[0]
        path = path.split('#', 1)[0]
        
        if path == '/' or path == '':
            return os.path.join(os.path.dirname(__file__), '..', 'frontend', 'index.html')
            
        parts = [p for p in path.split('/') if p]
        
        if parts:
            if parts[0] == 'generated_images':
                subpath = os.path.join(*parts[1:]) if len(parts) > 1 else ''
                return os.path.join(get_generated_dir('images'), subpath)
            elif parts[0] == 'generated_models':
                subpath = os.path.join(*parts[1:]) if len(parts) > 1 else ''
                return os.path.join(get_generated_dir('models'), subpath)
            elif parts[0] in ('app.js', 'styles.css', 'index.html'):
                return os.path.join(os.path.dirname(__file__), '..', 'frontend', parts[0])
                
        return os.path.join(os.path.dirname(__file__), '..', 'frontend', *parts)

    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
        self.send_header('Pragma', 'no-cache')
        self.send_header('Expires', '0')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200, "OK")
        self.end_headers()

    def get_logged_in_user(self):
        cookie_header = self.headers.get('Cookie', '')
        if cookie_header:
            cookies = {}
            for item in cookie_header.split(';'):
                item = item.strip()
                if '=' in item:
                    k, v = item.split('=', 1)
                    cookies[k.strip()] = v.strip()
            return cookies.get('session_user')
        return None

    def do_GET(self):
        if self.path == '/api/gallery':
            self.handle_get_gallery()
        elif self.path.startswith('/api/space-status'):
            self.handle_space_status()
        elif self.path.startswith('/api/job-status'):
            self.handle_job_status()
        elif self.path == '/api/user-active-job':
            self.handle_user_active_job()
        elif self.path == '/api/me':
            username = self.get_logged_in_user()
            credits = 0
            nick = None
            full_name = None
            avatar = None
            email = None
            if username:
                try:
                    db_path = get_db_path()
                    conn = sqlite3.connect(db_path)
                    cursor = conn.cursor()
                    cursor.execute("SELECT credits, nick, full_name, avatar, email FROM users WHERE username = ?", (username,))
                    row = cursor.fetchone()
                    conn.close()
                    if row:
                        credits = row[0] if row[0] is not None else 0
                        nick = row[1]
                        full_name = row[2]
                        avatar = row[3]
                        email = row[4]
                except Exception as e:
                    print(f"[Backend] Error checking user profile: {e}")
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({
                "username": username,
                "credits": credits,
                "nick": nick or username,
                "full_name": full_name or "",
                "avatar": avatar or "",
                "email": email or ""
            }).encode('utf-8'))
        else:
            super().do_GET()

    def do_POST(self):
        if self.path == '/api/register':
            self.handle_register()
        elif self.path == '/api/login':
            self.handle_login()
        elif self.path == '/api/logout':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Set-Cookie', 'session_user=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; SameSite=Lax')
            self.send_header('Set-Cookie', 'session_user=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; SameSite=None; Secure')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True}).encode('utf-8'))
        elif self.path == '/api/update-profile':
            self.handle_update_profile()
        elif self.path == '/api/update-privacy':
            self.handle_update_privacy()
        elif self.path == '/api/generate-3d':
            self.handle_generate_3d()
        elif self.path == '/api/optimize-3d':
            self.handle_optimize_3d()
        elif self.path == '/api/rig-3d':
            self.handle_rig_3d()
        elif self.path == '/api/generate-2d':
            self.handle_generate_2d()
        elif self.path == '/api/delete-gallery':
            self.handle_delete_gallery()
        elif self.path == '/api/save-weights':
            self.handle_save_weights()
        elif self.path == '/api/topup':
            self.handle_topup()
        elif self.path == '/api/create-checkout-session':
            self.handle_create_checkout_session()
        elif self.path == '/api/lemonsqueezy-webhook':
            self.handle_lemonsqueezy_webhook()
        else:
            self.send_error(404, "Endpoint not found")

    def handle_register(self):
        try:
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))
            
            username = params.get('username', '').strip().lower()
            password = params.get('password', '')
            
            if not username or not password:
                self.send_error_response(400, "Nombre de usuario y contraseña son obligatorios.")
                return
                
            if not username.isalnum() or len(username) < 3:
                self.send_error_response(400, "El nombre de usuario debe ser alfanumérico y de al menos 3 caracteres.")
                return

            if len(password) < 4:
                self.send_error_response(400, "La contraseña debe tener al menos 4 caracteres.")
                return

            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            cursor.execute("SELECT id FROM users WHERE username = ?", (username,))
            if cursor.fetchone():
                conn.close()
                self.send_error_response(400, "El nombre de usuario ya está registrado.")
                return
                
            salt = base64.b64encode(os.urandom(16)).decode('utf-8')
            hasher = hashlib.sha256()
            hasher.update((password + salt).encode('utf-8'))
            password_hash = hasher.hexdigest()
            
            cursor.execute(
                "INSERT INTO users (username, password_hash, salt, created_at, credits) VALUES (?, ?, ?, ?, 20)",
                (username, password_hash, salt, time.time())
            )
            conn.commit()
            conn.close()
            
            os.makedirs(get_generated_dir("images", username), exist_ok=True)
            os.makedirs(get_generated_dir("models", username), exist_ok=True)
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True}).encode('utf-8'))
            
        except Exception as e:
            self.send_error_response(500, str(e))

    def handle_update_profile(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            nick = params.get('nick', '').strip()
            full_name = params.get('full_name', '').strip()
            avatar = params.get('avatar', '').strip()

            if not nick:
                self.send_error_response(400, "El apodo / nick no puede estar vacío.")
                return

            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute(
                "UPDATE users SET nick = ?, full_name = ?, avatar = ? WHERE username = ?",
                (nick, full_name, avatar, username)
            )
            conn.commit()
            conn.close()

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True, "nick": nick, "full_name": full_name, "avatar": avatar}).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error updating profile: {e}")
            self.send_error_response(500, str(e))

    def handle_update_privacy(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            email = params.get('email', '').strip()
            current_password = params.get('current_password', '')
            new_password = params.get('new_password', '')

            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()

            if new_password:
                cursor.execute("SELECT password_hash, salt FROM users WHERE username = ?", (username,))
                user_row = cursor.fetchone()
                if not user_row:
                    conn.close()
                    self.send_error_response(404, "Usuario no encontrado.")
                    return

                stored_hash, salt = user_row[0], user_row[1]
                hasher = hashlib.sha256()
                hasher.update((current_password + salt).encode('utf-8'))
                if hasher.hexdigest() != stored_hash:
                    conn.close()
                    self.send_error_response(400, "La contraseña actual es incorrecta.")
                    return

                new_salt = base64.b64encode(os.urandom(16)).decode('utf-8')
                new_hasher = hashlib.sha256()
                new_hasher.update((new_password + new_salt).encode('utf-8'))
                new_hash = new_hasher.hexdigest()

                cursor.execute(
                    "UPDATE users SET email = ?, password_hash = ?, salt = ? WHERE username = ?",
                    (email, new_hash, new_salt, username)
                )
            else:
                cursor.execute(
                    "UPDATE users SET email = ? WHERE username = ?",
                    (email, username)
                )

            conn.commit()
            conn.close()

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True}).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error updating privacy: {e}")
            self.send_error_response(500, str(e))

    def handle_login(self):
        try:
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))
            
            username = params.get('username', '').strip().lower()
            password = params.get('password', '')
            
            if not username or not password:
                self.send_error_response(400, "Nombre de usuario y contraseña son obligatorios.")
                return

            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            
            cursor.execute("SELECT password_hash, salt FROM users WHERE username = ?", (username,))
            row = cursor.fetchone()
            conn.close()
            
            if not row:
                self.send_error_response(400, "Usuario o contraseña incorrectos.")
                return
                
            db_hash, salt = row
            hasher = hashlib.sha256()
            hasher.update((password + salt).encode('utf-8'))
            login_hash = hasher.hexdigest()
            
            if login_hash != db_hash:
                self.send_error_response(400, "Usuario o contraseña incorrectos.")
                return
                
            os.makedirs(get_generated_dir("images", username), exist_ok=True)
            os.makedirs(get_generated_dir("models", username), exist_ok=True)
            
            # Query credits
            credits = 0
            try:
                db_path = get_db_path()
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
                row = cursor.fetchone()
                conn.close()
                if row:
                    credits = row[0]
            except Exception as e:
                print(f"[Backend] Error checking login credits: {e}")

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.send_header('Set-Cookie', f'session_user={username}; Path=/; Max-Age=2592000; SameSite=Lax')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True, "username": username, "credits": credits}).encode('utf-8'))
            
        except Exception as e:
            self.send_error_response(500, str(e))

    def handle_topup(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))
            amount = int(params.get('amount', 50))

            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute("UPDATE users SET credits = credits + ? WHERE username = ?", (amount, username))
            conn.commit()
            cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
            credits_row = cursor.fetchone()
            conn.close()

            new_credits = credits_row[0] if credits_row else 0
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True, "credits": new_credits}).encode('utf-8'))

        except Exception as e:
            self.send_error_response(500, str(e))

    def handle_create_checkout_session(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))
            pack_type = str(params.get('pack_type', '25'))

            api_key = os.environ.get('LEMON_SQUEEZY_API_KEY', '').strip()
            store_id = os.environ.get('LEMON_SQUEEZY_STORE_ID', '').strip()
            variant_25 = os.environ.get('LEMON_SQUEEZY_VARIANT_25', '').strip()
            variant_100 = os.environ.get('LEMON_SQUEEZY_VARIANT_100', '').strip()

            host = self.headers.get('Host', 'localhost:8000')
            protocol = 'https' if 'hf.space' in host or 'huggingface.co' in host else 'http'
            base_url = f"{protocol}://{host}"

            amount_credits = 100 if pack_type == '100' else 25
            variant_id = variant_100 if pack_type == '100' else variant_25

            if not api_key or not store_id or not variant_id:
                print("[⚠️ Lemon Squeezy] API keys/Variant IDs missing. Simulating checkout url.")
                mock_url = f"{base_url}/?payment=success"
                
                db_path = get_db_path()
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                cursor.execute("UPDATE users SET credits = credits + ? WHERE username = ?", (amount_credits, username))
                conn.commit()
                conn.close()
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"url": mock_url}).encode('utf-8'))
                return

            import urllib.request
            import urllib.error

            url = "https://api.lemonsqueezy.com/v1/checkouts"
            req_data = {
                "data": {
                    "type": "checkouts",
                    "attributes": {
                        "product_options": {
                            "redirect_url": f"{base_url}/?payment=success"
                        },
                        "checkout_data": {
                            "custom": {
                                "username": username,
                                "amount": str(amount_credits)
                            }
                        }
                    },
                    "relationships": {
                        "store": {
                            "data": {
                                "type": "stores",
                                "id": str(store_id)
                            }
                        },
                        "variant": {
                            "data": {
                                "type": "variants",
                                "id": str(variant_id)
                            }
                        }
                    }
                }
            }

            req = urllib.request.Request(
                url,
                data=json.dumps(req_data).encode('utf-8'),
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/vnd.api+json",
                    "Accept": "application/vnd.api+json"
                },
                method="POST"
            )

            try:
                with urllib.request.urlopen(req) as response:
                    res_body = response.read().decode('utf-8')
                    res_json = json.loads(res_body)
                    checkout_url = res_json["data"]["attributes"]["url"]
                    
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({"url": checkout_url}).encode('utf-8'))
            except urllib.error.HTTPError as http_err:
                err_content = http_err.read().decode('utf-8')
                print(f"[Lemon Squeezy API Error] {http_err.code}: {err_content}")
                self.send_error_response(http_err.code, f"Error de Lemon Squeezy: {err_content}")

        except Exception as e:
            print(f"[Lemon Squeezy Checkout Error] {e}")
            self.send_error_response(500, str(e))

    def handle_lemonsqueezy_webhook(self):
        try:
            content_length = int(self.headers.get('Content-Length', 0))
            payload = self.rfile.read(content_length)
            
            sig_header = self.headers.get('X-Signature', '')
            webhook_secret = os.environ.get('LEMON_SQUEEZY_WEBHOOK_SECRET', '').strip()

            if webhook_secret and webhook_secret != 'PON_TU_WEBHOOK_SECRET_AQUI':
                digest = hmac.new(
                    webhook_secret.encode('utf-8'),
                    payload,
                    hashlib.sha256
                ).hexdigest()
                
                if not hmac.compare_digest(digest, sig_header):
                    print("[⚠️ Lemon Squeezy Webhook] Invalid signature verification.")
                    self.send_response(400)
                    self.end_headers()
                    return
            else:
                print("[⚠️ Lemon Squeezy Webhook] Webhook secret not configured. Bypassing signature check (Developer Mode).")

            event = json.loads(payload.decode('utf-8'))
            event_name = event.get('meta', {}).get('event_name')

            if event_name == 'order_created':
                custom_data = event.get('meta', {}).get('custom_data', {})
                username = custom_data.get('username')
                amount = custom_data.get('amount')

                if username and amount:
                    try:
                        amount = int(amount)
                        db_path = get_db_path()
                        conn = sqlite3.connect(db_path)
                        cursor = conn.cursor()
                        cursor.execute("UPDATE users SET credits = credits + ? WHERE username = ?", (amount, username))
                        conn.commit()
                        conn.close()
                        print(f"[Lemon Squeezy Webhook] Successfully credited {amount} credits to user: {username}")
                    except Exception as db_err:
                        print(f"[Lemon Squeezy Webhook Database Error] {db_err}")
                        self.send_response(500)
                        self.end_headers()
                        return
                else:
                    print(f"[Lemon Squeezy Webhook Warning] Webhook custom_data missing username/amount: {custom_data}")

            self.send_response(200)
            self.end_headers()

        except Exception as e:
            print(f"[Lemon Squeezy Webhook Exception] {e}")
            self.send_response(500)
            self.end_headers()

    def handle_generate_3d(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            load_dotenv() # Reload env dynamically
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            resolution = params.get('resolution', '1024')
            texture_size = int(params.get('texture_size', 2048))
            required_credits = calculate_3d_cost(resolution, texture_size)
            params['cost'] = required_credits # store cost in params for potential refund

            # Check credits dynamically
            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
            row = cursor.fetchone()
            if not row or row[0] < required_credits:
                conn.close()
                self.send_response(402)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"error": f"Créditos insuficientes. Esta generación 3D con ajustes seleccionados cuesta {required_credits} créditos."}).encode('utf-8'))
                return
            
            # Deduct credits immediately
            cursor.execute("UPDATE users SET credits = MAX(0, credits - ?) WHERE username = ?", (required_credits, username))
            
            # Query the updated credits
            cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
            credits_row = cursor.fetchone()
            new_credits = credits_row[0] if credits_row else 0
            
            # Create asynchronous job
            job_id = str(uuid.uuid4())
            now = time.time()
            cursor.execute(
                "INSERT INTO jobs (id, username, type, status, progress, message, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (job_id, username, '3d', 'pending', 0, 'En cola de espera...', now, now)
            )
            
            conn.commit()
            conn.close()

            # Push to background worker queue
            job_queue.put({
                "id": job_id,
                "username": username,
                "type": "3d",
                "params": params
            })

            response_data = {
                "success": True,
                "job_id": job_id,
                "status": "pending",
                "credits": new_credits
            }
            
            self.send_response(202) # 202 Accepted
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response_data).encode('utf-8'))
            
        except Exception as e:
            print(f"[Backend] Error initiating 3D generation job: {e}")
            self.send_error_response(500, str(e))

    def handle_optimize_3d(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            load_dotenv()
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            model_url = params.get('modelUrl', '') # e.g. "/generated_models/model_1782268665.glb"
            quad_target_faces = int(params.get('quad_target_faces', 60000))
            remesh_method = params.get('remeshMethod', 'cleanup')
            if not model_url:
                self.send_error_response(400, "No modelUrl provided")
                return

            filename = os.path.basename(model_url)
            output_dir = get_generated_dir("models", username)
            dest_path = os.path.join(output_dir, filename)

            if not os.path.exists(dest_path):
                self.send_error_response(404, f"Model file {filename} not found")
                return

            # Output to a new file (_quad.glb) to keep the original source model intact in gallery
            if "_quad" in filename:
                clean_filename = filename
            else:
                clean_filename = filename.replace(".glb", "_quad.glb")
            
            clean_dest_path = os.path.join(output_dir, clean_filename)
            
            # Copy metadata json if exists so the remeshed model retains species category
            meta_src = dest_path.replace(".glb", ".json")
            meta_dest = clean_dest_path.replace(".glb", ".json")
            if os.path.exists(meta_src) and not os.path.exists(meta_dest):
                try:
                    shutil.copy(meta_src, meta_dest)
                except Exception as me:
                    print(f"[Backend] QuadriFlow metadata copy note: {me}")

            blender_path = os.environ.get('BLENDER_PATH', '')
            if not blender_path or not os.path.exists(blender_path):
                blender_path = shutil.which("blender") or ""
            if blender_path and os.path.exists(blender_path):
                print(f"[Backend] Local optimization requested. Running Blender...")
                import subprocess
                script_path = os.path.join(os.path.dirname(__file__), "scripts", "blender", "clean_mesh_blender.py")
                cmd = [blender_path, "--background", "--python", script_path, "--", dest_path, clean_dest_path, str(quad_target_faces), remesh_method]
                print(f"[Backend] Executing: {' '.join(cmd)}")
                result = subprocess.run(cmd, capture_output=True, text=True)
                
                print(f"[Backend] Blender Output:\n{result.stdout}")
                if result.stderr:
                    print(f"[Backend] Blender Errors:\n{result.stderr}")

                fbx_filename = clean_filename.replace(".glb", ".fbx")
                fbx_url = f"/generated_models/{username}/{fbx_filename}" if os.path.exists(os.path.join(output_dir, fbx_filename)) else None

                if result.returncode == 0 and os.path.exists(clean_dest_path):
                    response_data = {
                        "success": True,
                        "glbUrl": f"/generated_models/{username}/{clean_filename}",
                        "gltfUrl": f"/generated_models/{username}/{clean_filename}",
                        "fbxUrl": fbx_url
                    }
                else:
                    raise Exception(f"Blender failed with exit status {result.returncode}")
            else:
                raise Exception("BLENDER_PATH is not configured or executable not found locally.")

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response_data).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error during 3D optimization: {e}")
            self.send_error_response(500, str(e))

    def handle_rig_3d(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            load_dotenv()
            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            model_url = params.get('modelUrl', '') # e.g. "/generated_models/model_1782268665.glb"
            rig_method = params.get('rigMethod', 'ai')
            hf_token = params.get('token', '')

            if not model_url:
                self.send_error_response(400, "No modelUrl provided")
                return

            filename = os.path.basename(model_url)
            output_dir = get_generated_dir("models", username)
            dest_path = os.path.join(output_dir, filename)

            if not os.path.exists(dest_path):
                self.send_error_response(404, f"Model file {filename} not found")
                return

            # Rigging target paths
            base_name, _ = os.path.splitext(filename)
            rigged_fbx_filename = f"{base_name}_rigged.fbx"
            rigged_fbx_path = os.path.join(output_dir, rigged_fbx_filename)

            if rig_method == 'ai':
                rigged_glb_filename = f"{base_name}_rigged.glb"
                rigged_glb_path = os.path.join(output_dir, rigged_glb_filename)
                
                print(f"[Backend] AI Rigging requested via Hugging Face...")
                # Get the correct token
                current_token = os.environ.get('HF_TOKEN', '')
                # Clean token from spaces/quotes
                hf_token_clean = str(hf_token).strip() if hf_token else ''
                if hf_token_clean in ('null', 'undefined'):
                    hf_token_clean = ''
                
                # If running on HF Spaces, prioritize token sent by the client. If running locally, only use the .env token.
                is_hf_space = 'SPACE_ID' in os.environ
                if is_hf_space:
                    token_to_use = hf_token_clean if hf_token_clean else current_token
                else:
                    token_to_use = current_token
                if token_to_use == 'PON_TU_TOKEN_AQUI':
                    token_to_use = ''
                token_to_use = token_to_use.strip()
                
                print(f"[Backend] Client token length: {len(hf_token_clean)}, Env token length: {len(current_token)}, Token to use length: {len(token_to_use)}")
                
                connect_options = {}
                if token_to_use:
                    connect_options['token'] = token_to_use
                
                # Check Space status before calling Gradio
                unirig_space = "LogicalTrue/Unirig"
                print(f"[Backend] Checking status of Hugging Face Space: '{unirig_space}'...")
                stage = get_space_status(unirig_space, token_to_use)
                print(f"[Backend] Checked Space stage: '{stage}'")
                
                if stage == "PAUSED":
                    self.send_error_response(503, f"El Space de Rigging '{unirig_space}' está PAUSADO. Por favor, reanúdalo en la consola de Hugging Face.")
                    return
                elif stage in ("STOPPED", "ERROR"):
                    self.send_error_response(503, f"El Space de Rigging '{unirig_space}' está APAGADO o tiene un ERROR (Estado actual: {stage}).")
                    return
                elif stage == "SLEEPING":
                    print(f"[Backend] ¡Atención! El Space de Rigging '{unirig_space}' está DORMIDO (SLEEPING). Gradio intentará despertarlo (esto puede demorar de 2 a 3 minutos)...")

                # UniRig API call
                from gradio_client import Client, handle_file
                
                print(f"[Backend] Connecting to '{unirig_space}'...")
                client = Client(unirig_space, **connect_options)
                print(f"[Backend] Submitting {filename} to UniRig...")
                res_path = client.predict(
                    handle_file(dest_path),  # archivo_3d
                    12345,                  # seed
                    api_name="/rig_mesh"
                )
                
                if res_path and os.path.exists(res_path):
                    shutil.copy(res_path, rigged_glb_path)
                    print(f"[Backend] ✓ AI Rigging completed successfully. Saved to: {rigged_glb_path}")
                    response_data = {
                        "success": True,
                        "riggedFbxUrl": f"/generated_models/{username}/{rigged_glb_filename}"
                    }
                else:
                    raise Exception("AI Rigging failed: could not retrieve the generated rigged GLB model from Hugging Face Space.")
            else:
                # Local procedural rigging using Blender
                blender_path = os.environ.get('BLENDER_PATH', '')
                if not blender_path or not os.path.exists(blender_path):
                    blender_path = shutil.which("blender") or ""
                if blender_path and os.path.exists(blender_path):
                    script_name = "rig_quadruped_blender.py" if rig_method == "local_quadruped" else "rig_mesh_blender.py"
                    print(f"[Backend] Local procedural rigging ({rig_method}) requested. Running Blender with {script_name}...")
                    import subprocess
                    script_path = os.path.join(os.path.dirname(__file__), "scripts", "blender", script_name)
                    cmd = [blender_path, "--background", "--python", script_path, "--", dest_path, rigged_fbx_path]
                    print(f"[Backend] Executing: {' '.join(cmd)}")
                    result = subprocess.run(cmd, capture_output=True, text=True)
                    
                    print(f"[Backend] Blender Output:\n{result.stdout}")
                    if result.stderr:
                        print(f"[Backend] Blender Errors:\n{result.stderr}")

                    rigged_glb_filename = f"{base_name}_rigged.glb"
                    rigged_glb_path = os.path.join(output_dir, rigged_glb_filename)
                    if result.returncode == 0 and os.path.exists(rigged_fbx_path):
                        has_glb = os.path.exists(rigged_glb_path)
                        response_data = {
                            "success": True,
                            "riggedFbxUrl": f"/generated_models/{username}/{rigged_glb_filename}" if has_glb else f"/generated_models/{username}/{rigged_fbx_filename}"
                        }
                    else:
                        raise Exception(f"Blender rigging failed with exit status {result.returncode}")
                else:
                    raise Exception("BLENDER_PATH is not configured or executable not found locally.")

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response_data).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error during rigging: {e}")
            self.send_error_response(500, str(e))

    def handle_generate_2d(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            prompt = params.get('prompt', '')
            params['cost'] = 1 # 2D image cost is 1 credit

            if not prompt:
                self.send_error_response(400, "No prompt provided")
                return

            # Check credits (needs 1)
            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
            row = cursor.fetchone()
            if not row or row[0] < 1:
                conn.close()
                self.send_response(402)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"error": "Créditos insuficientes. Generar una imagen cuesta 1 crédito."}).encode('utf-8'))
                return

            # Deduct credits immediately
            cursor.execute("UPDATE users SET credits = MAX(0, credits - 1) WHERE username = ?", (username,))
            
            # Query updated credits
            cursor.execute("SELECT credits FROM users WHERE username = ?", (username,))
            credits_row = cursor.fetchone()
            new_credits = credits_row[0] if credits_row else 0

            # Create async job
            job_id = str(uuid.uuid4())
            now = time.time()
            cursor.execute(
                "INSERT INTO jobs (id, username, type, status, progress, message, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (job_id, username, '2d', 'pending', 0, 'En cola de espera...', now, now)
            )
            conn.commit()
            conn.close()

            # Push to background worker queue
            job_queue.put({
                "id": job_id,
                "username": username,
                "type": "2d",
                "params": params
            })

            response_data = {
                "success": True,
                "job_id": job_id,
                "status": "pending",
                "credits": new_credits
            }

            self.send_response(202) # 202 Accepted
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(response_data).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error during 2D generation initialization: {e}")
            self.send_error_response(500, str(e))

    def handle_space_status(self):
        try:
            from urllib.parse import urlparse, parse_qs
            parsed_path = urlparse(self.path)
            query_params = parse_qs(parsed_path.query)
            space_type = query_params.get('type', ['3d'])[0]
            token = query_params.get('token', [''])[0]
            
            load_dotenv()
            current_token = os.environ.get('HF_TOKEN', '').strip()
            hf_token_clean = token.strip() if token else ''
            if hf_token_clean in ('null', 'undefined'):
                hf_token_clean = ''
                
            # If running on HF Spaces, prioritize token sent by the client. If running locally, only use the .env token.
            is_hf_space = 'SPACE_ID' in os.environ
            if is_hf_space:
                token_to_use = hf_token_clean if hf_token_clean else current_token
            else:
                token_to_use = current_token
            if token_to_use == 'PON_TU_TOKEN_AQUI':
                token_to_use = ''
            token_to_use = token_to_use.strip()
            
            if space_type == 'rig':
                target_space = "LogicalTrue/Unirig"
            else:
                target_space = os.environ.get('HF_SPACE', 'microsoft/TRELLIS.2')
                
            stage = get_space_status(target_space, token_to_use)
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"stage": stage, "space": target_space}).encode('utf-8'))
        except Exception as e:
            self.send_error_response(500, str(e))

    def handle_job_status(self):
        try:
            from urllib.parse import urlparse, parse_qs
            parsed_path = urlparse(self.path)
            query_params = parse_qs(parsed_path.query)
            
            job_id_list = query_params.get('job_id')
            if not job_id_list:
                self.send_error_response(400, "Missing job_id parameter")
                return
                
            job_id = job_id_list[0]
            
            db_path = get_db_path()
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute("SELECT id, username, type, status, progress, message, result FROM jobs WHERE id = ?", (job_id,))
            row = cursor.fetchone()
            conn.close()
            
            if not row:
                self.send_error_response(404, f"Job {job_id} not found")
                return
                
            job_data = {
                "job_id": row[0],
                "username": row[1],
                "type": row[2],
                "status": row[3],
                "progress": row[4],
                "message": row[5],
                "result": json.loads(row[6]) if row[6] and (row[6].startswith('{') or row[6].startswith('[')) else row[6]
            }
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(job_data).encode('utf-8'))
            
        except Exception as e:
            print(f"[Backend Error in handle_job_status] {e}")
            self.send_error_response(500, str(e))

    def handle_user_active_job(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute(
                "SELECT id, username, type, status, progress, message, result FROM jobs WHERE username = ? AND status IN ('pending', 'processing') ORDER BY created_at DESC LIMIT 1",
                (username,)
            )
            row = cursor.fetchone()
            conn.close()

            if not row:
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"has_active": False}).encode('utf-8'))
                return

            job_data = {
                "has_active": True,
                "job_id": row[0],
                "username": row[1],
                "type": row[2],
                "status": row[3],
                "progress": row[4],
                "message": row[5],
                "result": json.loads(row[6]) if row[6] and (row[6].startswith('{') or row[6].startswith('[')) else row[6]
            }

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(job_data).encode('utf-8'))
        except Exception as e:
            self.send_error_response(500, str(e))

    def handle_get_gallery(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            images_dir = get_generated_dir("images", username)
            models_dir = get_generated_dir("models", username)
            
            os.makedirs(images_dir, exist_ok=True)
            os.makedirs(models_dir, exist_ok=True)
            
            items = []
            
            # Read 2D images
            for f in os.listdir(images_dir):
                if f.endswith(('.png', '.jpg', '.jpeg', '.webp')):
                    path = os.path.join(images_dir, f)
                    mtime = os.path.getmtime(path)
                    items.append({
                        "name": f,
                        "type": "image",
                        "url": f"/generated_images/{username}/{f}",
                        "mtime": mtime
                    })
                    
            # Read 3D models
            for f in os.listdir(models_dir):
                if f.endswith('.glb') and not f.endswith('_dirty.glb') and not f.endswith('_temp.glb'):
                    path = os.path.join(models_dir, f)
                    mtime = os.path.getmtime(path)
                    
                    fbx_filename = f.replace('.glb', '.fbx')
                    has_fbx = os.path.exists(os.path.join(models_dir, fbx_filename))
                    
                    # Read metadata if exists
                    meta_path = path.replace(".glb", ".json")
                    detected_category = "unknown"
                    if os.path.exists(meta_path):
                        try:
                            with open(meta_path, "r", encoding="utf-8") as meta_f:
                                meta_data = json.load(meta_f)
                                detected_category = meta_data.get("detectedCategory", "unknown")
                        except Exception as me:
                            print(f"[Gallery] Error reading metadata for {f}: {me}")
                    else:
                        # Extract timestamp/ID from model name (e.g. model_1784353123.glb -> 1784353123)
                        base_clean = f.replace("_quad.glb", "").replace("_clean.glb", "").replace(".glb", "")
                        parts = base_clean.split("_")
                        timestamp = ""
                        for part in parts:
                            if part.isdigit() and len(part) >= 9:
                                timestamp = part
                                break
                        
                        if timestamp:
                            image_name = f"image_{timestamp}.png"
                            image_path = os.path.join(images_dir, image_name)
                            if os.path.exists(image_path):
                                print(f"[Gallery] Backfilling missing metadata for {f} using {image_name}...")
                                try:
                                    with open(image_path, "rb") as img_f:
                                        image_bytes = img_f.read()
                                    # Load token
                                    load_dotenv()
                                    current_token = os.environ.get('HF_TOKEN', '').strip()
                                    detected_category = classify_species(image_bytes, "", current_token)
                                    
                                    # Save metadata JSON file
                                    with open(meta_path, "w", encoding="utf-8") as meta_f:
                                        json.dump({
                                            "detectedCategory": detected_category,
                                            "prompt": "",
                                            "timestamp": mtime
                                        }, meta_f, indent=2)
                                except Exception as c_err:
                                    print(f"[Gallery] Failed backfilling metadata: {c_err}")

                    items.append({
                        "name": f,
                        "type": "model",
                        "url": f"/generated_models/{username}/{f}",
                        "fbxUrl": f"/generated_models/{username}/{fbx_filename}" if has_fbx else None,
                        "detectedCategory": detected_category,
                        "mtime": mtime
                    })
            
            # Sort items by creation time (newest first)
            items.sort(key=lambda x: x["mtime"], reverse=True)
            
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"items": items}).encode('utf-8'))
        except Exception as e:
            print(f"[Backend] Error getting gallery: {e}")
            self.send_error_response(500, str(e))

    def handle_delete_gallery(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))
            
            filename = params.get('name', '')
            item_type = params.get('type', '')
            
            if not filename or not item_type:
                self.send_error_response(400, "Missing name or type")
                return
                
            if item_type == "image":
                target_dir = get_generated_dir("images", username)
            elif item_type == "model":
                target_dir = get_generated_dir("models", username)
            else:
                self.send_error_response(400, "Invalid type")
                return
                
            # Security check: avoid directory traversal
            clean_name = os.path.basename(filename)
            file_path = os.path.join(target_dir, clean_name)
            
            if os.path.exists(file_path):
                try:
                    os.remove(file_path)
                    print(f"[Backend] Deleted file: {file_path}")
                except Exception as file_err:
                    raise Exception(f"El archivo está siendo usado por otro programa (ej: Blender). Detalles: {file_err}")
                
                # If it was a 3D model, clean up associated files (.obj, .mtl, .fbx, _dirty.glb, _texture.png)
                if item_type == "model" and clean_name.endswith(".glb"):
                    prefix = clean_name.replace(".glb", "")
                    for ext in [".obj", ".mtl", ".fbx", "_dirty.glb", "_clean.glb", "_clean.fbx", "_texture.png", "_rigged.fbx", "_rigged.glb", ".json"]:
                        assoc_file = os.path.join(target_dir, prefix + ext)
                        if os.path.exists(assoc_file):
                            try:
                                os.remove(assoc_file)
                                print(f"[Backend] Deleted associated file: {assoc_file}")
                            except Exception as assoc_err:
                                print(f"[Backend] Warning: could not delete associated file {assoc_file}: {assoc_err}")
                            
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"success": True}).encode('utf-8'))
            else:
                self.send_error_response(404, "File not found")
        except Exception as e:
            print(f"[Backend] Error deleting gallery item: {e}")
            self.send_error_response(500, str(e))

    def handle_save_weights(self):
        try:
            username = self.get_logged_in_user()
            if not username:
                self.send_error_response(401, "No has iniciado sesión.")
                return

            content_length = int(self.headers['Content-Length'])
            post_data = self.rfile.read(content_length)
            params = json.loads(post_data.decode('utf-8'))

            model_url = params.get('modelUrl', '')
            glb_base64 = params.get('glbBase64', '')

            if not model_url or not glb_base64:
                self.send_error_response(400, "Missing modelUrl or glbBase64 data")
                return

            filename = os.path.basename(model_url)
            output_dir = get_generated_dir("models", username)
            dest_path = os.path.join(output_dir, filename)

            if not os.path.exists(dest_path):
                self.send_error_response(404, f"Model file {filename} not found")
                return

            # Extract base64 binary
            if ',' in glb_base64:
                glb_base64 = glb_base64.split(',')[1]
            glb_bytes = base64.b64decode(glb_base64)

            # Write updated GLB
            with open(dest_path, "wb") as f:
                f.write(glb_bytes)
            print(f"[Backend] Saved updated GLB weights for: {dest_path}")

            # Check if there is an associated FBX (regenerate it)
            fbx_filename = filename.replace(".glb", ".fbx")
            fbx_dest_path = os.path.join(output_dir, fbx_filename)

            blender_path = os.environ.get('BLENDER_PATH', '')
            if not blender_path or not os.path.exists(blender_path):
                blender_path = shutil.which("blender") or ""
            if blender_path and os.path.exists(blender_path):
                print(f"[Backend] Regenerating FBX from updated GLB weights...")
                import subprocess
                script_path = os.path.join(os.path.dirname(__file__), "scripts", "blender", "glb_to_fbx_weights.py")
                
                with open(script_path, "w", encoding="utf-8") as f_script:
                    f_script.write('''import bpy
import sys
import json

def strip_gltf_extensions(glb_path):
    try:
        with open(glb_path, "rb") as f:
            data = f.read()
        if len(data) < 20 or data[:4] != b'glTF':
            return
        json_len = int.from_bytes(data[12:16], byteorder='little')
        json_bytes = data[20:20+json_len]
        gltf_json = json.loads(json_bytes.decode('utf-8', errors='ignore'))
        
        modified = False
        for key in ['extensionsRequired', 'extensionsUsed']:
            if key in gltf_json and 'EXT_texture_webp' in gltf_json[key]:
                gltf_json[key].remove('EXT_texture_webp')
                modified = True
                
        if modified:
            new_bytes = json.dumps(gltf_json).encode('utf-8')
            if len(new_bytes) <= len(json_bytes):
                new_bytes = new_bytes.ljust(len(json_bytes), b' ')
                new_data = data[:20] + new_bytes + data[20+len(json_bytes):]
                with open(glb_path, "wb") as f:
                    f.write(new_data)
                print(f"[Blender] Stripped EXT_texture_webp extension requirement from GLB.")
    except Exception as e:
        print(f"[Blender] Extension strip note: {e}")

args = sys.argv[sys.argv.index("--") + 1:]
glb_in = args[0]
fbx_out = args[1]

strip_gltf_extensions(glb_in)
bpy.ops.wm.read_factory_settings(use_empty=True)
print(f"Importing GLB: {glb_in}")
bpy.ops.import_scene.gltf(filepath=glb_in)

print(f"Exporting FBX: {fbx_out}")
bpy.ops.export_scene.fbx(
    filepath=fbx_out,
    use_selection=False,
    object_types={'ARMATURE', 'MESH'},
    use_mesh_modifiers=True,
    add_leaf_bones=False,
    bake_anim=False
)
print("FBX conversion completed successfully.")
''')

                cmd = [blender_path, "--background", "--python", script_path, "--", dest_path, fbx_dest_path]
                print(f"[Backend] Executing: {' '.join(cmd)}")
                result = subprocess.run(cmd, capture_output=True, text=True)
                print(f"[Backend] Blender Output:\n{result.stdout}")
                if result.stderr:
                    print(f"[Backend] Blender Errors:\n{result.stderr}")
                
                try:
                    os.remove(script_path)
                except:
                    pass

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True, "fbxUrl": f"/generated_models/{username}/{fbx_filename}" if os.path.exists(fbx_dest_path) else None}).encode('utf-8'))

        except Exception as e:
            print(f"[Backend] Error saving weights: {e}")
            self.send_error_response(500, str(e))

    def send_error_response(self, code, message):
        self.send_response(code)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps({"error": message}).encode('utf-8'))

def run_server():
    init_db()
    server_address = ('', PORT)
    httpd = ThreadingHTTPServer(server_address, F23DHTTPRequestHandler)
    print(f"[Backend] 23DFactory server running at http://localhost:{PORT}")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n[Backend] Server shutting down.")
        httpd.server_close()

if __name__ == '__main__':
    run_server()