File size: 29,672 Bytes
1c3d615
 
 
121e50f
98e22db
 
671dd1e
1c3d615
 
 
98e22db
1c3d615
 
98e22db
1c3d615
 
 
 
 
 
671dd1e
1c3d615
 
 
 
671dd1e
1c3d615
 
 
98e22db
1c3d615
671dd1e
1c3d615
 
671dd1e
1c3d615
 
 
 
 
671dd1e
1c3d615
 
 
 
 
 
 
661788f
1c3d615
661788f
1c3d615
 
121e50f
f0c04e9
1c3d615
 
 
 
 
 
 
 
 
 
 
 
 
 
98e22db
1c3d615
121e50f
 
 
1c3d615
671dd1e
1c3d615
 
 
121e50f
 
1c3d615
121e50f
 
1c3d615
 
661788f
 
 
 
 
1c3d615
661788f
1c3d615
 
 
 
 
 
 
 
 
 
671dd1e
 
 
 
 
 
 
1c3d615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671dd1e
 
 
1c3d615
671dd1e
 
 
1c3d615
 
671dd1e
1c3d615
 
 
661788f
1c3d615
661788f
 
1c3d615
 
671dd1e
1c3d615
 
661788f
671dd1e
661788f
1c3d615
 
 
 
661788f
1c3d615
121e50f
 
 
1c3d615
 
 
 
 
 
 
 
 
 
 
661788f
1c3d615
 
98e22db
 
 
 
 
 
 
 
 
 
 
671dd1e
98e22db
 
671dd1e
98e22db
 
 
 
 
 
 
 
05717bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98e22db
 
 
05717bc
 
 
 
 
98e22db
 
 
671dd1e
05717bc
 
 
98e22db
 
05717bc
98e22db
 
 
 
 
671dd1e
05717bc
 
671dd1e
 
05717bc
98e22db
05717bc
671dd1e
98e22db
 
05717bc
98e22db
05717bc
671dd1e
98e22db
 
05717bc
98e22db
 
 
05717bc
98e22db
 
671dd1e
05717bc
671dd1e
05717bc
98e22db
 
05717bc
671dd1e
98e22db
 
05717bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98e22db
 
05717bc
98e22db
05717bc
98e22db
05717bc
98e22db
05717bc
98e22db
 
671dd1e
05717bc
671dd1e
05717bc
98e22db
 
671dd1e
98e22db
 
05717bc
671dd1e
 
05717bc
671dd1e
98e22db
 
 
05717bc
 
 
98e22db
 
 
 
 
 
1c3d615
98e22db
671dd1e
1c3d615
 
 
671dd1e
 
1c3d615
 
 
671dd1e
1c3d615
671dd1e
 
 
 
1c3d615
 
671dd1e
1c3d615
 
 
 
671dd1e
 
 
 
 
121e50f
 
671dd1e
 
 
121e50f
1c3d615
 
 
 
671dd1e
1c3d615
 
 
671dd1e
 
1c3d615
121e50f
1c3d615
 
 
671dd1e
 
1c3d615
 
 
671dd1e
 
1c3d615
671dd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c3d615
661788f
1c3d615
671dd1e
 
 
 
1c3d615
 
671dd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661788f
98e22db
 
671dd1e
 
98e22db
671dd1e
 
 
 
 
 
 
 
 
 
 
 
 
 
661788f
1c3d615
98e22db
 
 
 
1c3d615
671dd1e
98e22db
 
 
671dd1e
121e50f
 
98e22db
671dd1e
121e50f
671dd1e
 
 
 
 
98e22db
671dd1e
 
98e22db
671dd1e
98e22db
671dd1e
121e50f
98e22db
 
 
 
 
 
 
 
 
671dd1e
 
98e22db
 
 
 
 
 
 
671dd1e
98e22db
 
671dd1e
98e22db
 
 
121e50f
98e22db
 
 
671dd1e
98e22db
121e50f
671dd1e
1c3d615
621dc30
1c3d615
 
671dd1e
 
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
import os
import json
import uuid
import secrets
import zipfile
import io
import httpx
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any

from fastapi import FastAPI, Depends, HTTPException, status, UploadFile, File, Query, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse, FileResponse, RedirectResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel, Field

# --- Configuration ---
# In a real production app, use Hugging Face Space Secrets to set this!
JWT_SECRET_KEY = os.environ.get("JWT_SECRET_KEY", secrets.token_hex(32))
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7  # 7 days

# --- Persistent Data Paths (Hugging Face Spaces use /data for persistent storage) ---
DATA_DIR = "data"
USERS_DB_FILE = os.path.join(DATA_DIR, "users.json")
UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")
STATIC_DIR = "static"

# Create persistent directories if they don't exist
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(STATIC_DIR, exist_ok=True)

# --- Security & Hashing ---
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# --- Pydantic Models (Data Schemas) ---
class Token(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    username: Optional[str] = None

class WatchHistoryEntry(BaseModel):
    show_id: str
    show_title: str
    season_number: int
    episode_number: int
    watch_timestamp: datetime

class UserBase(BaseModel):
    username: str

class UserCreate(UserBase):
    password: str

class UserInDB(UserBase):
    hashed_password: str
    profile_picture_url: Optional[str] = None
    watch_history: List[Dict[str, Any]] = Field(default_factory=list)

class UserPublic(UserBase):
    profile_picture_url: Optional[str] = None
    watch_history_detailed: Dict[str, Any] = Field(default_factory=dict)
    email: Optional[str] = None

class PasswordChange(BaseModel):
    current_password: str
    new_password: str

# --- Database Helper Functions (using JSON file) ---
def load_users() -> Dict[str, Dict]:
    if not os.path.exists(USERS_DB_FILE):
        return {}
    try:
        with open(USERS_DB_FILE, "r") as f:
            return json.load(f)
    except (json.JSONDecodeError, FileNotFoundError):
        return {}

def save_users(users_db: Dict[str, Dict]):
    def json_serializer(obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        raise TypeError(f"Type {type(obj)} not serializable")

    with open(USERS_DB_FILE, "w") as f:
        json.dump(users_db, f, indent=4, default=json_serializer)

# --- Password & Token Functions ---
def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt

# --- Dependency to get current user ---
async def get_current_user(token: str = Depends(oauth2_scheme)) -> UserInDB:
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except JWTError:
        raise credentials_exception

    users_db = load_users()
    user_data = users_db.get(token_data.username)
    if user_data is None:
        raise credentials_exception

    return UserInDB(**user_data)


# --- FastAPI App Initialization ---
app = FastAPI(title="Media Auth API")

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

# --- Helper function to structure watch history ---
def structure_watch_history(history_list: List[Dict]) -> Dict:
    structured = {}
    sorted_history = sorted(history_list, key=lambda x: x.get("watch_timestamp", ""), reverse=True)
    
    for item in sorted_history:
        show_id = item.get("show_id")
        show_title = item.get("show_title", "Unknown Show")
        season_num = item.get("season_number")
        episode_num = item.get("episode_number")
        timestamp = item.get("watch_timestamp")

        if not all([show_id, season_num is not None, episode_num is not None, timestamp]):
            continue

        if show_id not in structured:
            structured[show_id] = {
                "show_id": show_id,
                "title": show_title,
                "seasons": {}
            }
        if season_num not in structured[show_id]["seasons"]:
            structured[show_id]["seasons"][season_num] = {
                "season_number": season_num,
                "episodes": {}
            }
        structured[show_id]["seasons"][season_num]["episodes"][episode_num] = timestamp
    return structured

async def get_anime_poster_url(anime_title: str) -> Optional[str]:
    """Fetches the top anime poster URL from Jikan API."""
    try:
        async with httpx.AsyncClient() as client:
            response = await client.get(f"https://api.jikan.moe/v4/anime?q={anime_title}&limit=1")
            response.raise_for_status()
            data = response.json()
            if data.get("data"):
                return data["data"][0]["images"]["jpg"]["large_image_url"]
    except Exception as e:
        print(f"Error fetching poster for '{anime_title}': {e}")
        return None
    return None

# --- HTML Content for Download UI ---
DOWNLOAD_UI_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Anime Series</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        :root {
            --primary-color: #FF9500;
            --primary-dark: #E68600;
            --primary-light: #FFB84D;
            --bg-dark: #0F0F0F;
            --bg-secondary: #1A1A1A;
            --bg-tertiary: #252525;
            --text-primary: #FFFFFF;
            --text-secondary: #B3B3B3;
            --text-muted: #808080;
            --border-color: #333333;
            --border-light: #404040;
            --success-color: #10B981;
            --error-color: #FF9500;
            --glass-bg: rgba(255, 255, 255, 0.05);
            --glass-border: rgba(255, 255, 255, 0.1);
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: linear-gradient(135deg, #0F0F0F 0%, #1A1A1A 100%);
            color: var(--text-primary);
            margin: 0;
            padding: 2rem;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--glass-border);
            padding: 2.5rem;
            border-radius: 24px;
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
            width: 100%;
            max-width: 650px;
            position: relative;
            overflow: hidden;
        }
        
        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, var(--primary-color), transparent);
        }
        
        h1 {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            text-align: center;
            margin-bottom: 2rem;
            font-weight: 700;
            font-size: 2rem;
            letter-spacing: -0.02em;
        }
        
        .series-list {
            list-style: none;
            padding: 0;
            max-height: 45vh;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 16px;
            background: var(--bg-secondary);
            position: relative;
        }
        
        .series-list::-webkit-scrollbar {
            width: 8px;
        }
        
        .series-list::-webkit-scrollbar-track {
            background: var(--bg-tertiary);
            border-radius: 8px;
        }
        
        .series-list::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 8px;
            border: 2px solid var(--bg-tertiary);
        }
        
        .series-list::-webkit-scrollbar-thumb:hover {
            background: var(--primary-light);
        }
        
        .series-item {
            display: flex;
            align-items: center;
            padding: 1.25rem;
            border-bottom: 1px solid var(--border-color);
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
        }
        
        .series-item:last-child {
            border-bottom: none;
        }
        
        
        .series-item.selected {
            background: linear-gradient(135deg, rgba(255, 149, 0, 0.15), rgba(255, 149, 0, 0.08));
            border-left: 3px solid var(--primary-color);
        }
        
        /* Custom Checkbox */
        .custom-checkbox {
            position: relative;
            display: inline-block;
            width: 24px;
            height: 24px;
            margin-right: 1rem;
            cursor: pointer;
        }
        
        .custom-checkbox input[type="checkbox"] {
            opacity: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            cursor: pointer;
        }
        
        .checkbox-visual {
            position: absolute;
            top: 0;
            left: 0;
            width: 24px;
            height: 24px;
            border: 2px solid var(--border-light);
            border-radius: 8px;
            background: var(--bg-tertiary);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .checkbox-visual::after {
            content: '';
            width: 8px;
            height: 8px;
            border: 2px solid var(--text-primary);
            border-top: none;
            border-right: none;
            transform: rotate(-45deg) scale(0);
            transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .custom-checkbox input[type="checkbox"]:checked + .checkbox-visual {
            background: var(--primary-color);
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(255, 149, 0, 0.2);
        }
        
        .custom-checkbox input[type="checkbox"]:checked + .checkbox-visual::after {
            transform: rotate(-45deg) scale(1);
            border-color: var(--text-primary);
        }
        
        .custom-checkbox:hover .checkbox-visual {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(255, 149, 0, 0.1);
        }
        
        .series-item label {
            flex-grow: 1;
            font-size: 1.1rem;
            font-weight: 500;
            color: var(--text-primary);
            cursor: pointer;
            transition: color 0.2s ease;
            line-height: 1.4;
        }
        
        .series-item:hover label {
            color: var(--primary-light);
        }
        
        .button-container {
            text-align: center;
            margin-top: 2rem;
        }
        
        .btn {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: var(--text-primary);
            border: none;
            padding: 1rem 2.5rem;
            font-size: 1.1rem;
            font-weight: 600;
            border-radius: 16px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 8px 25px rgba(255, 149, 0, 0.3);
            position: relative;
            overflow: hidden;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 35px rgba(255, 149, 0, 0.4);
        }
        
        .btn:hover::before {
            left: 100%;
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn:disabled {
            background: linear-gradient(135deg, var(--text-muted), #666);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .btn:disabled::before {
            display: none;
        }
        
        #loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.9);
            backdrop-filter: blur(10px);
            display: none;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .loader {
            width: 80px;
            height: 80px;
            border: 4px solid var(--border-color);
            border-top: 4px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            box-shadow: 0 0 20px rgba(255, 149, 0, 0.3);
        }
        
        #loading-text {
            color: var(--text-primary);
            margin-top: 24px;
            font-size: 1.2rem;
            font-weight: 500;
            text-align: center;
            opacity: 0.9;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .error-message {
            color: var(--error-color);
            text-align: center;
            font-weight: 500;
        }
        
        .empty-state {
            text-align: center;
            color: var(--text-secondary);
            font-style: italic;
        }
        
        @media (max-width: 768px) {
            body {
                padding: 1rem;
            }
            
            .container {
                padding: 1.5rem;
                border-radius: 16px;
            }
            
            h1 {
                font-size: 1.75rem;
            }
            
            .series-list {
                max-height: 35vh;
            }
            
            .series-item {
                padding: 1rem;
            }
            
            .btn {
                padding: 0.875rem 2rem;
                font-size: 1rem;
            }
        }
    </style>
</head>
<body>
    <div id="loading-overlay">
        <div class="loader"></div>
        <p id="loading-text">Generating your files...</p>
    </div>
    
    <div class="container">
        <h1>Select Anime to Download</h1>
        <form id="downloadForm">
            <ul id="seriesList" class="series-list"></ul>
            <div class="button-container">
                <button type="submit" class="btn" id="generateBtn" disabled>Generate Zip</button>
            </div>
        </form>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            const seriesList = document.getElementById('seriesList');
            const generateBtn = document.getElementById('generateBtn');
            const loadingOverlay = document.getElementById('loading-overlay');
            const apiBaseUrl = ''; // API is at the same origin
            
            // Get the token from the URL parameters
            const urlParams = new URLSearchParams(window.location.search);
            const token = urlParams.get('token');
            
            if (!token) {
                seriesList.innerHTML = '<li class="series-item" style="justify-content: center;"><span class="error-message">Authentication token not found in URL.</span></li>';
                generateBtn.disabled = true;
                return;
            }
            
            try {
                // Use the token from the URL for the Bearer authentication header
                const response = await fetch(`${apiBaseUrl}/users/me`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                
                if (!response.ok) {
                    throw new Error('Failed to fetch user data. Your session may have expired.');
                }
                
                const userData = await response.json();
                const history = userData.watch_history_detailed;
                const uniqueSeries = [...new Set(Object.values(history).map(show => show.title))].sort();
                
                if (uniqueSeries.length === 0) {
                    seriesList.innerHTML = '<li class="series-item" style="justify-content: center;"><span class="empty-state">No watched series found.</span></li>';
                    return;
                }
                
                uniqueSeries.forEach(title => {
                    const listItem = document.createElement('li');
                    listItem.className = 'series-item';
                    listItem.innerHTML = `
                        <div class="custom-checkbox">
                            <input type="checkbox" id="${title}" name="series" value="${title}">
                            <div class="checkbox-visual"></div>
                        </div>
                        <label for="${title}">${title}</label>
                    `;
                    
                    // Add click handler for the entire item
                    listItem.addEventListener('click', (e) => {
                        if (e.target.tagName !== 'INPUT') {
                            const checkbox = listItem.querySelector('input[type="checkbox"]');
                            checkbox.checked = !checkbox.checked;
                            checkbox.dispatchEvent(new Event('change'));
                        }
                    });
                    
                    // Add change handler for checkbox
                    const checkbox = listItem.querySelector('input[type="checkbox"]');
                    checkbox.addEventListener('change', () => {
                        if (checkbox.checked) {
                            listItem.classList.add('selected');
                        } else {
                            listItem.classList.remove('selected');
                        }
                    });
                    
                    seriesList.appendChild(listItem);
                });
                
                generateBtn.disabled = false;
                
            } catch (error) {
                seriesList.innerHTML = `<li class="series-item" style="justify-content: center;"><span class="error-message">${error.message}</span></li>`;
            }
            
            document.getElementById('downloadForm').addEventListener('submit', (e) => {
                e.preventDefault();
                loadingOverlay.style.display = 'flex';
                
                const selectedSeries = Array.from(document.querySelectorAll('input[name="series"]:checked')).map(cb => cb.value);
                
                if (selectedSeries.length === 0) {
                    alert('Please select at least one series.');
                    loadingOverlay.style.display = 'none';
                    return;
                }
                
                const queryString = new URLSearchParams({ series_titles: selectedSeries.join(',') }).toString();
                
                // Construct the download URL, passing the token as a query parameter
                const downloadUrl = `${apiBaseUrl}/generate-zip?${queryString}&token=${token}`;
                
                window.open(downloadUrl, '_blank');
                
                setTimeout(() => { 
                    loadingOverlay.style.display = 'none'; 
                }, 3000);
            });
        });
    </script>
</body>
</html>
"""

# --- API Endpoints ---

@app.post("/token", response_model=Token, tags=["Authentication"])
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    users_db = load_users()
    user_data = users_db.get(form_data.username)
    if not user_data or not verify_password(form_data.password, user_data.get("hashed_password")):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user_data["username"]}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@app.post("/signup", status_code=status.HTTP_201_CREATED, tags=["Authentication"])
async def signup_user(user: UserCreate):
    users_db = load_users()
    if user.username in users_db:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Username already registered",
        )
    hashed_password = get_password_hash(user.password)
    new_user = UserInDB(
        username=user.username,
        hashed_password=hashed_password,
        profile_picture_url=None,
        watch_history=[]
    )
    users_db[user.username] = new_user.dict()
    save_users(users_db)
    return {"message": "User created successfully. Please login."}


@app.get("/users/me", response_model=UserPublic, tags=["User"])
async def read_users_me(current_user: UserInDB = Depends(get_current_user)):
    detailed_history = structure_watch_history(current_user.watch_history)
    
    user_public_data = UserPublic(
        username=current_user.username,
        email=current_user.username,
        profile_picture_url=current_user.profile_picture_url,
        watch_history_detailed=detailed_history
    )
    return user_public_data


@app.post("/users/me/profile-picture", response_model=UserPublic, tags=["User"])
async def upload_profile_picture(
    file: UploadFile = File(...),
    current_user: UserInDB = Depends(get_current_user)
):
    file_extension = os.path.splitext(file.filename)[1].lower()
    if file_extension not in ['.png', '.jpg', '.jpeg', '.gif', '.webp']:
        raise HTTPException(status_code=400, detail="Invalid file type.")
        
    unique_filename = f"{uuid.uuid4()}{file_extension}"
    file_path = os.path.join(UPLOAD_DIR, unique_filename)

    with open(file_path, "wb") as buffer:
        buffer.write(await file.read())

    profile_picture_url = f"/uploads/{unique_filename}"
    users_db = load_users()
    users_db[current_user.username]["profile_picture_url"] = profile_picture_url
    save_users(users_db)

    current_user.profile_picture_url = profile_picture_url
    detailed_history = structure_watch_history(current_user.watch_history)
    return UserPublic(
        username=current_user.username,
        email=current_user.username,
        profile_picture_url=current_user.profile_picture_url,
        watch_history_detailed=detailed_history
    )


@app.get("/users/me/watch-history", status_code=status.HTTP_200_OK, tags=["User"])
async def update_watch_history(
    show_id: str = Query(...),
    show_title: str = Query(...),
    season_number: int = Query(..., ge=0),
    episode_number: int = Query(..., ge=1),
    current_user: UserInDB = Depends(get_current_user)
):
    users_db = load_users()
    user_data = users_db[current_user.username]
    episode_id = f"{show_id}_{season_number}_{episode_number}"

    is_already_watched = any(
        (f"{item.get('show_id')}_{item.get('season_number')}_{item.get('episode_number')}" == episode_id)
        for item in user_data.get("watch_history", [])
    )

    if not is_already_watched:
        new_entry = WatchHistoryEntry(
            show_id=show_id,
            show_title=show_title,
            season_number=season_number,
            episode_number=episode_number,
            watch_timestamp=datetime.utcnow()
        )
        user_data.setdefault("watch_history", []).append(new_entry.dict())
        save_users(users_db)
        return {"message": "Watch history updated."}

    return {"message": "Episode already in watch history."}


@app.post("/users/me/password", status_code=status.HTTP_200_OK, tags=["User"])
async def change_user_password(
    password_data: PasswordChange,
    current_user: UserInDB = Depends(get_current_user)
):
    users_db = load_users()
    user_data = users_db[current_user.username]
    
    if not verify_password(password_data.current_password, user_data["hashed_password"]):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Incorrect current password",
        )
    
    new_hashed_password = get_password_hash(password_data.new_password)
    user_data["hashed_password"] = new_hashed_password
    save_users(users_db)
    
    return {"message": "Password updated successfully"}


@app.get("/download-ui", response_class=HTMLResponse, tags=["Download"])
async def get_download_ui(request: Request):
    """Serves the modern HTML interface for selecting downloads."""
    return HTMLResponse(content=DOWNLOAD_UI_HTML)


@app.get("/generate-zip", tags=["Download"])
async def generate_zip_file(
    series_titles: str = Query(..., description="Comma-separated list of anime titles"),
    token: str = Query(..., description="User's auth token from URL param")
):
    """
    Generates a zip file containing folders for selected anime series,
    each with a poster.png inside. It authenticates using the token from the URL.
    """
    # Create a temporary dependency to validate the token from the query parameter
    async def get_user_from_query_token(token_str: str = token) -> UserInDB:
        # This re-uses the logic from get_current_user but works on a raw token string
        return await get_current_user(token=token_str)

    try:
        # Validate the token by calling our temporary dependency
        await get_user_from_query_token()
    except HTTPException:
        raise HTTPException(status_code=401, detail="Authentication failed from URL token")

    titles = [title.strip() for title in series_titles.split(',') if title.strip()]
    
    zip_buffer = io.BytesIO()

    async with httpx.AsyncClient() as client:
        with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for title in titles:
                # Sanitize title for folder name
                safe_folder_name = "".join(c for c in title if c.isalnum() or c in " .-_").rstrip()
                folder_path = f"Anime/{safe_folder_name}/"
                
                poster_url = await get_anime_poster_url(title)
                
                if poster_url:
                    try:
                        response = await client.get(poster_url)
                        response.raise_for_status()
                        zipf.writestr(f"{folder_path}poster.png", response.content)
                    except Exception as e:
                        print(f"Failed to download or write poster for '{title}': {e}")
                        # Create an empty file to ensure folder creation
                        zipf.writestr(f"{folder_path}.placeholder", "")
                else:
                    # If no poster is found, still create the folder via a placeholder
                    zipf.writestr(f"{folder_path}.placeholder", "")

    zip_buffer.seek(0)
    
    return StreamingResponse(
        zip_buffer,
        media_type="application/zip",
        headers={"Content-Disposition": "attachment; filename=anime_series_folders.zip"}
    )

# --- Static File Serving & Root Redirect ---
app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
app.mount("/login", StaticFiles(directory=STATIC_DIR), name="static") 

@app.get("/", include_in_schema=False)
def root():
    return RedirectResponse(url="/docs")