a
File size: 23,917 Bytes
3ed56e3
0fcb5c2
1ad3b12
0fcb5c2
 
 
 
 
 
 
 
1ad3b12
0fcb5c2
 
 
76b8a0b
 
 
1ad3b12
76b8a0b
 
 
 
 
0fcb5c2
 
1ad3b12
0fcb5c2
 
 
fbc8659
0fcb5c2
 
4612e64
76b8a0b
0fcb5c2
 
76b8a0b
a8a0f13
 
 
76b8a0b
 
 
 
a8a0f13
 
 
0fcb5c2
 
 
 
 
 
 
 
 
84c880b
 
 
 
 
 
 
 
0fcb5c2
 
 
 
 
 
 
 
76b8a0b
 
 
 
 
 
 
 
 
 
0fcb5c2
 
 
 
 
 
4612e64
 
8bc2ea7
 
0fcb5c2
 
 
 
 
 
54e4063
1ad3b12
0fcb5c2
54e4063
 
 
 
 
 
 
 
1ad3b12
 
54e4063
 
1ad3b12
54e4063
 
 
1ad3b12
 
 
 
 
 
 
 
54e4063
1ad3b12
54e4063
 
62f0fc0
0fcb5c2
 
 
8663c78
 
 
 
 
0fcb5c2
 
 
 
76b8a0b
 
 
 
 
8bc2ea7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76b8a0b
8bc2ea7
 
0fcb5c2
8bc2ea7
0fcb5c2
 
 
fbc8659
0fcb5c2
 
4612e64
76b8a0b
0fcb5c2
 
bc0c819
0fcb5c2
 
 
76b8a0b
 
 
 
 
0fcb5c2
 
 
 
 
 
76b8a0b
0fcb5c2
 
 
 
 
 
 
4612e64
 
0fcb5c2
 
 
 
 
 
fbc8659
0fcb5c2
 
 
 
 
76b8a0b
0fcb5c2
 
 
9f5255d
 
 
0fcb5c2
 
9f5255d
 
fbc8659
 
0fcb5c2
4612e64
 
 
76b8a0b
4612e64
 
0fcb5c2
 
 
fbc8659
0fcb5c2
 
4612e64
76b8a0b
 
 
 
 
 
 
8663c78
 
 
 
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f5255d
 
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fcb5c2
 
 
8663c78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c8ae4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8a0f13
 
 
76b8a0b
a8a0f13
 
 
 
76b8a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8a0f13
8663c78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c8ae4e
 
0fcb5c2
8663c78
 
 
 
 
fbc8659
0fcb5c2
 
 
3ed56e3
 
 
 
 
 
 
0fcb5c2
 
 
 
 
 
4612e64
0fcb5c2
 
 
 
 
 
 
 
 
 
 
 
 
 
9f5255d
 
0fcb5c2
fbc8659
0fcb5c2
 
4612e64
76b8a0b
0fcb5c2
 
 
 
 
 
 
4612e64
0fcb5c2
 
 
 
 
9f5255d
0fcb5c2
fbc8659
0fcb5c2
 
4612e64
76b8a0b
0fcb5c2
 
3ed56e3
 
 
 
bc0c819
0fcb5c2
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
use crate::error::AppError;
use crate::services::tmdb::TmdbClient;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdType {
    Imdb,
    Tmdb,
    Tvdb,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MediaType {
    Movie,
    Tv,
    Episode,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpisodeInfo {
    pub show_tmdb_id: u64,
    pub season_number: u32,
    pub episode_number: u32,
    pub still_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedId {
    pub imdb_id: Option<String>,
    pub tmdb_id: u64,
    pub tvdb_id: Option<u64>,
    pub media_type: MediaType,
    pub poster_path: Option<String>,
    pub release_date: Option<String>,
    pub episode: Option<EpisodeInfo>,
}

pub fn format_tmdb_id_value(tmdb_id: u64, media_type: &MediaType, episode: Option<&EpisodeInfo>) -> String {
    match media_type {
        MediaType::Movie => format!("movie-{tmdb_id}"),
        MediaType::Tv => format!("series-{tmdb_id}"),
        MediaType::Episode => match episode {
            Some(ep) => format!("episode-{}-S{}E{}", ep.show_tmdb_id, ep.season_number, ep.episode_number),
            None => format!("series-{tmdb_id}"),
        },
    }
}

impl IdType {
    pub fn parse(s: &str) -> Result<Self, AppError> {
        match s {
            "imdb" => Ok(IdType::Imdb),
            "tmdb" => Ok(IdType::Tmdb),
            "tvdb" => Ok(IdType::Tvdb),
            other => Err(AppError::InvalidIdType(other.to_string())),
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Imdb => "imdb",
            Self::Tmdb => "tmdb",
            Self::Tvdb => "tvdb",
        }
    }
}

#[derive(Debug, Deserialize)]
struct FindResult {
    #[serde(default)]
    movie_results: Vec<FindEntry>,
    #[serde(default)]
    tv_results: Vec<FindEntry>,
    #[serde(default)]
    tv_episode_results: Vec<EpisodeFindEntry>,
}

#[derive(Debug, Deserialize)]
struct EpisodeFindEntry {
    show_id: u64,
    season_number: u32,
    episode_number: u32,
    still_path: Option<String>,
}

#[derive(Debug, Deserialize)]
struct FindEntry {
    id: u64,
    poster_path: Option<String>,
    release_date: Option<String>,
    first_air_date: Option<String>,
    #[serde(default)]
    popularity: f64,
}

pub async fn resolve(
    id_type: IdType,
    id_value: &str,
    tmdb: &TmdbClient,
    cache: &moka::future::Cache<String, ResolvedId>,
    db: &sea_orm::DatabaseConnection,
) -> Result<ResolvedId, AppError> {
    let id_type_str = match id_type {
        IdType::Imdb => "imdb",
        IdType::Tmdb => "tmdb",
        IdType::Tvdb => "tvdb",
    };
    let key = format!("{id_type_str}/{id_value}");
    let tmdb = tmdb.clone();
    let id_value = id_value.to_owned();
    let db = db.clone();
    let cache_key = key.clone();
    cache
        .try_get_with(key, async move {
            let result = match id_type {
                IdType::Imdb => resolve_imdb(&id_value, &tmdb).await,
                IdType::Tmdb => resolve_tmdb(&id_value, &tmdb).await,
                IdType::Tvdb => resolve_tvdb(&id_value, &tmdb).await,
            };
            if let Ok(ref resolved) = result {
                let db = db.clone();
                let cache_key = cache_key.clone();
                let resolved = resolved.clone();
                tokio::spawn(async move {
                    crate::cache::persistence::save_id_cache_entry(&db, &cache_key, &resolved, 3600).await;
                });
            }
            result
        })
        .await
        .map_err(AppError::from_cached)
}

async fn resolve_imdb(imdb_id: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
    // Handle episode format: episode-{series_imdb_id}-S{season}E{episode}
    if let Some(rest) = imdb_id.strip_prefix("episode-") {
        return resolve_imdb_episode(rest, imdb_id, tmdb).await;
    }

    let result: FindResult = tmdb
        .get(&format!("/find/{imdb_id}"), &[("external_source", "imdb_id")])
        .await?;

    // Check episode results first — an episode IMDb ID is unambiguous.
    if let Some(ep) = result.tv_episode_results.first() {
        return resolve_episode_details(tmdb, ep.show_id, ep.season_number, ep.episode_number, ep.still_path.clone(), Some(imdb_id.to_string())).await;
    }

    // Pick the most popular entry across all movie and TV results.
    let best_movie = result.movie_results.iter().max_by(|a, b| a.popularity.total_cmp(&b.popularity));
    let best_tv = result.tv_results.iter().max_by(|a, b| a.popularity.total_cmp(&b.popularity));

    // When both exist, pick the one with higher popularity.
    // Fall back to movie-first ordering when popularity is equal.
    let pick_movie = match (best_movie, best_tv) {
        (Some(m), Some(t)) => m.popularity >= t.popularity,
        (Some(_), None) => true,
        (None, Some(_)) => false,
        (None, None) => false,
    };

    if pick_movie {
        if let Some(movie) = best_movie {
            return Ok(ResolvedId {
                imdb_id: Some(imdb_id.to_string()),
                tmdb_id: movie.id,
                tvdb_id: None,
                media_type: MediaType::Movie,
                poster_path: movie.poster_path.clone(),
                release_date: movie.release_date.clone(),
                episode: None,
            });
        }
    }
    if let Some(tv) = best_tv {
        return Ok(ResolvedId {
            imdb_id: Some(imdb_id.to_string()),
            tmdb_id: tv.id,
            tvdb_id: None,
            media_type: MediaType::Tv,
            poster_path: tv.poster_path.clone(),
            release_date: tv.first_air_date.clone(),
            episode: None,
        });
    }
    Err(AppError::IdNotFound(format!("{imdb_id} (not found on TMDB)")))
}

async fn resolve_tmdb(id_value: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
    // Handle episode format: episode-{show_id}-S{season}E{episode}
    if let Some(rest) = id_value.strip_prefix("episode-") {
        return resolve_tmdb_episode(rest, id_value, tmdb).await;
    }

    let (media_type, tmdb_id) = if let Some(rest) = id_value.strip_prefix("movie-") {
        (MediaType::Movie, rest.parse::<u64>().map_err(|_| AppError::InvalidIdType(id_value.to_string()))?)
    } else if let Some(rest) = id_value.strip_prefix("series-") {
        (MediaType::Tv, rest.parse::<u64>().map_err(|_| AppError::InvalidIdType(id_value.to_string()))?)
    } else {
        return Err(AppError::InvalidIdType(format!(
            "tmdb id must be prefixed with movie-, series-, or episode-: {id_value}"
        )));
    };

    #[derive(Deserialize)]
    struct Details {
        imdb_id: Option<String>,
        poster_path: Option<String>,
        release_date: Option<String>,
        first_air_date: Option<String>,
        #[serde(default)]
        external_ids: Option<ExternalIds>,
    }
    #[derive(Deserialize)]
    struct ExternalIds {
        imdb_id: Option<String>,
        tvdb_id: Option<u64>,
    }

    let path = match media_type {
        MediaType::Movie => format!("/movie/{tmdb_id}"),
        MediaType::Tv => format!("/tv/{tmdb_id}?append_to_response=external_ids"),
        MediaType::Episode => return Err(AppError::Other("unexpected Episode media type in resolve_tmdb".into())),
    };
    let details: Details = tmdb.get(&path, &[]).await?;

    // TMDB returns an empty string (not null) for titles it hasn't cross-referenced
    // to IMDb; treat that as absent so downstream MDBList/Trakt/OMDb lookups take
    // their TMDB-id fallback or skip cleanly instead of querying with a blank id.
    let imdb_id = details
        .imdb_id
        .or_else(|| details.external_ids.as_ref().and_then(|e| e.imdb_id.clone()))
        .filter(|s| !s.is_empty());

    let tvdb_id = details.external_ids.as_ref().and_then(|e| e.tvdb_id);

    let release_date = match media_type {
        MediaType::Movie => details.release_date,
        MediaType::Tv => details.first_air_date,
        MediaType::Episode => return Err(AppError::Other("unexpected Episode media type in resolve_tmdb".into())),
    };

    Ok(ResolvedId {
        imdb_id,
        tmdb_id,
        tvdb_id,
        media_type,
        poster_path: details.poster_path,
        release_date,
        episode: None,
    })
}

/// Parse the `{show_id}-S{season}E{episode}` portion of an episode ID.
/// Returns `(show_id, season, episode)` on success.
fn parse_episode_id(rest: &str, id_value: &str) -> Result<(u64, u32, u32), AppError> {
    let (id_str, season, episode) = parse_episode_external(rest, id_value)?;
    let show_id = id_str
        .parse::<u64>()
        .map_err(|_| AppError::InvalidIdType(id_value.to_string()))?;
    Ok((show_id, season, episode))
}

/// Parse `episode-{show_id}-S{season}E{episode}` and resolve via TMDB.
async fn resolve_tmdb_episode(rest: &str, id_value: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
    let (show_id, season, episode) = parse_episode_id(rest, id_value)?;
    resolve_episode_details(tmdb, show_id, season, episode, None, None).await
}

/// Shared helper: fetch episode details from TMDB and build a `ResolvedId`.
///
/// Called by all three resolvers (IMDb, TMDB, TVDB) after they determine the
/// show ID and season/episode numbers. `hint_still_path` and `hint_imdb_id` are
/// values already known from the `/find` response (if any) to avoid redundant lookups.
async fn resolve_episode_details(
    tmdb: &TmdbClient,
    show_tmdb_id: u64,
    season: u32,
    episode: u32,
    hint_still_path: Option<String>,
    hint_imdb_id: Option<String>,
) -> Result<ResolvedId, AppError> {
    #[derive(Deserialize)]
    struct EpDetails {
        still_path: Option<String>,
        air_date: Option<String>,
        #[serde(default)]
        external_ids: Option<EpExternalIds>,
    }
    #[derive(Deserialize)]
    struct EpExternalIds {
        imdb_id: Option<String>,
        tvdb_id: Option<u64>,
    }

    let details: EpDetails = tmdb
        .get(
            &format!("/tv/{show_tmdb_id}/season/{season}/episode/{episode}"),
            &[("append_to_response", "external_ids")],
        )
        .await?;

    let imdb_id = hint_imdb_id
        .or_else(|| details.external_ids.as_ref().and_then(|e| e.imdb_id.clone()))
        .filter(|s| !s.is_empty());
    let tvdb_id = details.external_ids.as_ref().and_then(|e| e.tvdb_id);
    let still_path = hint_still_path.or(details.still_path.clone());

    // Use still_path as poster_path; fallback to series poster if no still
    let poster_path = if still_path.is_some() {
        still_path.clone()
    } else {
        #[derive(Deserialize)]
        struct ShowInfo {
            poster_path: Option<String>,
        }
        let show: ShowInfo = tmdb.get(&format!("/tv/{show_tmdb_id}"), &[]).await?;
        show.poster_path
    };

    Ok(ResolvedId {
        imdb_id,
        tmdb_id: show_tmdb_id,
        tvdb_id,
        media_type: MediaType::Episode,
        poster_path,
        release_date: details.air_date,
        episode: Some(EpisodeInfo {
            show_tmdb_id,
            season_number: season,
            episode_number: episode,
            still_path,
        }),
    })
}

/// Parse `{external_id}-S{season}E{episode}` for IMDb/TVDB episode lookups.
/// Unlike `parse_episode_id`, the ID portion is returned as a string slice
/// because IMDb IDs like `tt1234567` aren't purely numeric.
fn parse_episode_external<'a>(rest: &'a str, id_value: &str) -> Result<(&'a str, u32, u32), AppError> {
    let upper = rest.to_ascii_uppercase();
    let split_pos = upper.find("-S").ok_or_else(|| {
        AppError::InvalidIdType(format!(
            "episode id must be episode-{{id}}-S{{season}}E{{episode}}: {id_value}"
        ))
    })?;
    let external_id = &rest[..split_pos];
    if external_id.is_empty() {
        return Err(AppError::InvalidIdType(format!(
            "episode id must be episode-{{id}}-S{{season}}E{{episode}}: {id_value}"
        )));
    }
    let se_str = &upper[split_pos + 2..]; // skip "-S"
    let se_parts: Vec<&str> = se_str.splitn(2, 'E').collect();
    if se_parts.len() != 2 {
        return Err(AppError::InvalidIdType(format!(
            "episode id must be episode-{{id}}-S{{season}}E{{episode}}: {id_value}"
        )));
    }
    let season = se_parts[0]
        .parse::<u32>()
        .map_err(|_| AppError::InvalidIdType(id_value.to_string()))?;
    let episode = se_parts[1]
        .parse::<u32>()
        .map_err(|_| AppError::InvalidIdType(id_value.to_string()))?;
    if season > 10_000 || episode > 100_000 {
        return Err(AppError::BadRequest(
            "season must be ≤ 10 000 and episode must be ≤ 100 000".into(),
        ));
    }
    Ok((external_id, season, episode))
}

/// Resolve `episode-{series_imdb_id}-S{season}E{episode}` by first looking up
/// the series via TMDB's Find API, then fetching episode details.
async fn resolve_imdb_episode(
    rest: &str,
    id_value: &str,
    tmdb: &TmdbClient,
) -> Result<ResolvedId, AppError> {
    let (series_imdb_id, season, episode): (&str, u32, u32) =
        parse_episode_external(rest, id_value)?;

    let result: FindResult = tmdb
        .get(
            &format!("/find/{series_imdb_id}"),
            &[("external_source", "imdb_id")],
        )
        .await?;

    let show_tmdb_id = result
        .tv_results
        .first()
        .map(|tv| tv.id)
        .ok_or_else(|| {
            AppError::IdNotFound(format!(
                "{series_imdb_id} (not found as a TV series on TMDB)"
            ))
        })?;

    resolve_episode_details(tmdb, show_tmdb_id, season, episode, None, None).await
}

/// Resolve `episode-{series_tvdb_id}-S{season}E{episode}` by first looking up
/// the series via TMDB's Find API, then fetching episode details.
async fn resolve_tvdb_episode(
    rest: &str,
    id_value: &str,
    tmdb: &TmdbClient,
) -> Result<ResolvedId, AppError> {
    let (series_tvdb_id, season, episode) = parse_episode_external(rest, id_value)?;

    let result: FindResult = tmdb
        .get(
            &format!("/find/{series_tvdb_id}"),
            &[("external_source", "tvdb_id")],
        )
        .await?;

    let show_tmdb_id = result
        .tv_results
        .first()
        .map(|tv| tv.id)
        .ok_or_else(|| {
            AppError::IdNotFound(format!(
                "{series_tvdb_id} (not found as a TV series on TMDB via TVDB lookup)"
            ))
        })?;

    resolve_episode_details(tmdb, show_tmdb_id, season, episode, None, None).await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_imdb() {
        assert_eq!(IdType::parse("imdb").unwrap(), IdType::Imdb);
    }

    #[test]
    fn parse_tmdb() {
        assert_eq!(IdType::parse("tmdb").unwrap(), IdType::Tmdb);
    }

    #[test]
    fn parse_tvdb() {
        assert_eq!(IdType::parse("tvdb").unwrap(), IdType::Tvdb);
    }

    #[test]
    fn parse_invalid_id_type() {
        assert!(IdType::parse("invalid").is_err());
    }

    #[test]
    fn parse_empty_string() {
        assert!(IdType::parse("").is_err());
    }

    #[test]
    fn parse_case_sensitive() {
        // Should not accept uppercase
        assert!(IdType::parse("IMDB").is_err());
        assert!(IdType::parse("Tmdb").is_err());
    }

    #[test]
    fn format_tmdb_id_value_movie() {
        assert_eq!(format_tmdb_id_value(278, &MediaType::Movie, None), "movie-278");
    }

    #[test]
    fn format_tmdb_id_value_tv() {
        assert_eq!(format_tmdb_id_value(1396, &MediaType::Tv, None), "series-1396");
    }

    #[test]
    fn format_tmdb_id_value_episode() {
        let ep = EpisodeInfo {
            show_tmdb_id: 1396,
            season_number: 1,
            episode_number: 1,
            still_path: None,
        };
        assert_eq!(
            format_tmdb_id_value(1396, &MediaType::Episode, Some(&ep)),
            "episode-1396-S1E1"
        );
    }

    #[test]
    fn format_tmdb_id_value_episode_large_numbers() {
        let ep = EpisodeInfo {
            show_tmdb_id: 456,
            season_number: 12,
            episode_number: 24,
            still_path: Some("/still.jpg".into()),
        };
        assert_eq!(
            format_tmdb_id_value(456, &MediaType::Episode, Some(&ep)),
            "episode-456-S12E24"
        );
    }

    #[test]
    fn format_tmdb_id_value_episode_none_falls_back() {
        // Episode with missing EpisodeInfo should not panic, falls back to series format
        assert_eq!(
            format_tmdb_id_value(1396, &MediaType::Episode, None),
            "series-1396"
        );
    }

    // --- parse_episode_id ---

    #[test]
    fn parse_episode_id_valid() {
        let (show, season, ep) = parse_episode_id("1396-S1E1", "episode-1396-S1E1").unwrap();
        assert_eq!(show, 1396);
        assert_eq!(season, 1);
        assert_eq!(ep, 1);
    }

    #[test]
    fn parse_episode_id_multi_digit() {
        let (show, season, ep) = parse_episode_id("456-S12E24", "episode-456-S12E24").unwrap();
        assert_eq!(show, 456);
        assert_eq!(season, 12);
        assert_eq!(ep, 24);
    }

    #[test]
    fn parse_episode_id_missing_season() {
        assert!(parse_episode_id("1396", "episode-1396").is_err());
    }

    #[test]
    fn parse_episode_id_missing_episode() {
        assert!(parse_episode_id("1396-S1", "episode-1396-S1").is_err());
    }

    #[test]
    fn parse_episode_id_non_numeric_show() {
        assert!(parse_episode_id("abc-S1E1", "episode-abc-S1E1").is_err());
    }

    #[test]
    fn parse_episode_id_non_numeric_season() {
        assert!(parse_episode_id("1396-SaE1", "episode-1396-SaE1").is_err());
    }

    #[test]
    fn parse_episode_id_non_numeric_episode() {
        assert!(parse_episode_id("1396-S1Eb", "episode-1396-S1Eb").is_err());
    }

    #[test]
    fn parse_episode_id_lowercase() {
        let (show, season, ep) = parse_episode_id("1396-s1e1", "episode-1396-s1e1").unwrap();
        assert_eq!(show, 1396);
        assert_eq!(season, 1);
        assert_eq!(ep, 1);
    }

    #[test]
    fn parse_episode_id_mixed_case() {
        let (show, season, ep) = parse_episode_id("456-s12E24", "episode-456-s12E24").unwrap();
        assert_eq!(show, 456);
        assert_eq!(season, 12);
        assert_eq!(ep, 24);
    }

    // --- parse_episode_external ---

    #[test]
    fn parse_episode_external_imdb() {
        let (id, season, ep) =
            parse_episode_external("tt14786934-S1E1", "episode-tt14786934-S1E1").unwrap();
        assert_eq!(id, "tt14786934");
        assert_eq!(season, 1);
        assert_eq!(ep, 1);
    }

    #[test]
    fn parse_episode_external_tvdb_numeric() {
        let (id, season, ep) =
            parse_episode_external("81189-S3E5", "episode-81189-S3E5").unwrap();
        assert_eq!(id, "81189");
        assert_eq!(season, 3);
        assert_eq!(ep, 5);
    }

    #[test]
    fn parse_episode_external_lowercase() {
        let (id, season, ep) =
            parse_episode_external("tt14786934-s2e10", "episode-tt14786934-s2e10").unwrap();
        assert_eq!(id, "tt14786934");
        assert_eq!(season, 2);
        assert_eq!(ep, 10);
    }

    #[test]
    fn parse_episode_external_missing_season() {
        assert!(parse_episode_external("tt14786934", "episode-tt14786934").is_err());
    }

    #[test]
    fn parse_episode_external_missing_episode() {
        assert!(parse_episode_external("tt14786934-S1", "episode-tt14786934-S1").is_err());
    }

    #[test]
    fn parse_episode_external_zero_values() {
        let (id, season, ep) =
            parse_episode_external("tt14786934-S0E0", "episode-tt14786934-S0E0").unwrap();
        assert_eq!(id, "tt14786934");
        assert_eq!(season, 0);
        assert_eq!(ep, 0);
    }

    #[test]
    fn parse_episode_external_at_boundary() {
        let (id, season, ep) =
            parse_episode_external("81189-S10000E100000", "episode-81189-S10000E100000").unwrap();
        assert_eq!(id, "81189");
        assert_eq!(season, 10_000);
        assert_eq!(ep, 100_000);
    }

    #[test]
    fn parse_episode_external_over_boundary() {
        assert!(parse_episode_external("81189-S10001E1", "episode-81189-S10001E1").is_err());
        assert!(parse_episode_external("81189-S1E100001", "episode-81189-S1E100001").is_err());
    }

    #[test]
    fn parse_episode_external_empty_id() {
        assert!(parse_episode_external("-S1E1", "episode--S1E1").is_err());
    }

    #[test]
    fn parse_episode_id_rejects_imdb_style_id() {
        assert!(parse_episode_id("tt1234-S1E1", "episode-tt1234-S1E1").is_err());
    }
}

async fn resolve_tvdb(tvdb_id: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
    // Handle episode format: episode-{series_tvdb_id}-S{season}E{episode}
    if let Some(rest) = tvdb_id.strip_prefix("episode-") {
        return resolve_tvdb_episode(rest, tvdb_id, tmdb).await;
    }

    let tvdb_id_num = tvdb_id.parse::<u64>().ok();
    let result: FindResult = tmdb
        .get(&format!("/find/{tvdb_id}"), &[("external_source", "tvdb_id")])
        .await?;
    // Check series/movie results first - a TVDB ID passed to this route is almost
    // always a series or movie ID. TMDB's find-by-tvdb_id can also return an
    // unrelated match in tv_episode_results for the same query (confirmed real
    // case: a TVDB series ID for Game of Thrones also matched an unrelated
    // Alfred Hitchcock Presents episode) - checking series/movie first avoids
    // that false match. Episode results are now only used as a fallback, which
    // still covers legitimate bare-numeric TVDB episode IDs per the OpenAPI spec.
    if let Some(tv) = result.tv_results.first() {
        // We need to fetch details to get the imdb_id
        #[derive(Deserialize)]
        struct TvDetails {
            external_ids: Option<TvExternalIds>,
            poster_path: Option<String>,
            first_air_date: Option<String>,
        }
        #[derive(Deserialize)]
        struct TvExternalIds {
            imdb_id: Option<String>,
        }
        let details: TvDetails = tmdb
            .get(
                &format!("/tv/{}", tv.id),
                &[("append_to_response", "external_ids")],
            )
            .await?;
        return Ok(ResolvedId {
            imdb_id: details
                .external_ids
                .and_then(|e| e.imdb_id)
                .filter(|s| !s.is_empty()),
            tmdb_id: tv.id,
            tvdb_id: tvdb_id_num,
            media_type: MediaType::Tv,
            poster_path: details.poster_path.or_else(|| tv.poster_path.clone()),
            release_date: details.first_air_date,
            episode: None,
        });
    }
    if let Some(movie) = result.movie_results.first() {
        #[derive(Deserialize)]
        struct MovieDetails {
            imdb_id: Option<String>,
            poster_path: Option<String>,
            release_date: Option<String>,
        }
        let details: MovieDetails = tmdb
            .get(&format!("/movie/{}", movie.id), &[])
            .await?;
        return Ok(ResolvedId {
            imdb_id: details.imdb_id.filter(|s| !s.is_empty()),
            tmdb_id: movie.id,
            tvdb_id: tvdb_id_num,
            media_type: MediaType::Movie,
            poster_path: details.poster_path.or_else(|| movie.poster_path.clone()),
            release_date: details.release_date,
            episode: None,
        });
    }
    // Fallback: only reached when no series/movie result matched.
    if let Some(ep) = result.tv_episode_results.first() {
        return resolve_episode_details(tmdb, ep.show_id, ep.season_number, ep.episode_number, ep.still_path.clone(), None).await;
    }
    Err(AppError::IdNotFound(format!("{tvdb_id} (not found on TMDB via TVDB lookup)")))
}