tvctl 0.13.0

Play YouTube, Spotify, Netflix, Prime Video and more in windows on your screen and control them from the command line (built for AI agents)
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
mod auth;
mod blackout;
mod cast;
mod cdp;
mod client;
mod duck;
mod layout;
mod plugin;
mod protocol;
mod server;
mod shell;
mod timeparse;

use anyhow::{Result, anyhow};
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use serde_json::{Value, json};

use crate::layout::Layout;
use crate::protocol::{PlayerAction, Request, Switch, WindowOpts};
use crate::timeparse::Seek;

const ABOUT: &str = "Play videos and music (YouTube, Spotify, Netflix, Prime Video, ...) in a window and control it from the command line.";

const LONG_ABOUT: &str = "\
Play videos and music (YouTube, Spotify, Netflix, Prime Video, ...) in a window and control it from the command line.

Workflow:
  1. `tvctl open <URL>` plays the URL in the player window. There is one player
     window: it opens if there is none; otherwise the URL replaces what it shows.
  2. Control it with `tvctl <command> ...` (no id: commands act on the player).
  3. `tvctl close` closes the window.
  Player and auth commands need the background server: start it once with
  `tvctl server up` and stop it with `tvctl server down`. Nothing else starts
  or stops it; commands that need it fail while it is not running.

Each service is a plugin. `tvctl plugins` shows, per plugin, the URL domains it
handles and its `actions` (supported player commands). Unsupported commands
fail with an error that lists the supported ones.";

const AFTER_LONG_HELP: &str = "\
Output:
  Every successful command prints one JSON document to stdout and exits 0,
  except `config <shell>`, which prints shell code for eval.
  Player commands (open, status, play, seek, ...) print:
    {\"service\": \"youtube\", \"player\": {...}, \"window\": {...}}
  With no player window open, player commands (including status) fail.
  `player` comes from the plugin. Common fields: `state` (\"playing\", \"paused\",
  \"buffering\", \"ended\", \"unstarted\", \"cued\"), `title`, `current_time` and
  `duration` (seconds), `volume` (0-100), `muted`, `playback_rate`, `subtitles`,
  `quality`, `available_qualities`. Fields a plugin cannot report are null or absent.
  `window`: `position` {x, y} and `outer_size` of the window frame, `size` of the
  video area, `fullscreen`, `blackout` (the window has turned black
  after 60 s paused or ended; the mouse, playback or a player command other
  than status brings the picture back), `work_area` (usable screen area). Coordinates are logical
  pixels from the top-left of the main screen.

Errors:
  On failure, a message starting with `error:` is printed to stderr and the exit
  code is 1 (no JSON on stdout).

Examples:
  tvctl open 'https://www.youtube.com/watch?v=iG9CE55wbtY' --subtitles ja
  tvctl open 'https://youtu.be/jNQXAC9IVRw' --layout bottom-right --size 480x270
  tvctl open 'https://open.spotify.com/album/5Z9iiGl2FcIfa3BMiv6OIw'
  tvctl open 'https://www.netflix.com/watch/81716297' --subtitles ja
  tvctl open 'https://www.amazon.com/gp/video/detail/B0GHXVBQLM' --subtitles ja
  tvctl status                    # read state, time, title, window
  tvctl seek +30                  # relative; `seek 1:30` is absolute
  tvctl subtitles ja              # Japanese subtitles (auto-translated if needed)
  tvctl window --layout left      # snap to the left half of the screen
  tvctl screenshot /tmp/now.png   # see what the window shows
  tvctl duck on --apps ChatGPT    # lower the player while ChatGPT speaks
  tvctl auth login youtube        # one-time login (needed for Spotify, Netflix, Prime Video, Crunchyroll)";

#[derive(Parser)]
#[command(version, about = ABOUT, long_about = LONG_ABOUT, after_long_help = AFTER_LONG_HELP)]
struct Cli {
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Play a URL in the player window; prints the player's status.
    ///
    /// There is one player window: it opens if there is none, otherwise the URL
    /// replaces what it shows. The window goes fullscreen unless `--windowed`,
    /// `--size`, `--position` or `--layout` is given (leaving fullscreen returns
    /// it to its place and size). The plugin is chosen by the URL's
    /// domain (see `tvctl plugins`). Fails unless the background server is
    /// running (`tvctl server up`).
    Open {
        /// Video or music URL of a supported service, e.g. a YouTube watch/youtu.be/shorts
        /// URL, an open.spotify.com track/album/playlist URL, a netflix.com
        /// /watch or /title URL, or an amazon.com / amazon.co.jp /gp/video/detail
        /// (Prime Video) URL, or a crunchyroll.com /watch or /series URL.
        url: String,
        /// Start position: seconds (90), clock (1:30, 1:02:03) or units (1m30s).
        /// Overrides `t=` in the URL.
        #[arg(long, value_name = "TIME")]
        start: Option<String>,
        /// Load without starting playback.
        #[arg(long)]
        paused: bool,
        /// Turn subtitles on in this language (e.g. ja, en); auto-translated if the
        /// video has no track in that language.
        #[arg(long, value_name = "LANG")]
        subtitles: Option<String>,
        #[command(flatten)]
        window: GeometryArgs,
        /// Fullscreen after applying --size, --position or --layout (the window
        /// returns there when leaving fullscreen). Without them, fullscreen is
        /// the default.
        #[arg(long, conflicts_with = "windowed")]
        fullscreen: bool,
        /// Show in a window instead of fullscreen (leaves fullscreen if needed).
        #[arg(long)]
        windowed: bool,
    },
    /// Show the player's playback and window status.
    Status,
    /// Start or resume playback.
    Play,
    /// Pause playback.
    Pause,
    /// Toggle between playing and paused.
    Toggle,
    /// Go to the next item (track, album/playlist entry).
    Next,
    /// Go to the previous item.
    Prev,
    /// Seek to an absolute position or by a relative offset.
    Seek {
        /// Absolute: 90, 1:30, 1:02:03, 1m30s. Relative: +10, -30, -1m.
        #[arg(allow_hyphen_values = true)]
        position: String,
    },
    /// Skip forward.
    Forward {
        /// How far: 10, 1:00, 2m.
        #[arg(default_value = "10")]
        duration: String,
    },
    /// Skip back.
    Back {
        /// How far: 10, 1:00, 2m.
        #[arg(default_value = "10")]
        duration: String,
    },
    /// Show, choose or turn off subtitles.
    Subtitles {
        /// `on`, `off`, `list` (adds `tracks` and `translation_languages` to the
        /// output), or a language code such as `ja` (auto-translated if needed).
        mode: String,
    },
    /// List or choose the audio track (e.g. dubbed languages).
    Audio {
        /// `list` (adds `audio_tracks` to the output) or a language code such as `ja`.
        lang: String,
    },
    /// Set the volume.
    Volume {
        /// 0-100.
        #[arg(value_parser = clap::value_parser!(u8).range(0..=100))]
        level: u8,
    },
    /// Mute audio.
    Mute,
    /// Unmute audio.
    Unmute,
    /// Set the playback speed.
    Speed {
        /// Rate, e.g. 0.5, 1, 1.5, 2 (0.0625-16).
        rate: f64,
    },
    /// Request a playback quality.
    Quality {
        /// A value from `available_qualities` in `status`, or `auto`. YouTube:
        /// small (240p), medium (360p), large (480p), hd720, hd1080, hd1440, hd2160.
        level: String,
    },
    /// Move or resize the window, snap it to a screen region, or change fullscreen
    /// and always-on-top.
    Window {
        #[command(flatten)]
        geometry: GeometryArgs,
        /// Fullscreen state.
        #[arg(long, value_enum)]
        fullscreen: Option<Switch>,
    },
    /// Turn fullscreen on, off, or toggle it.
    Fullscreen {
        /// on, off or toggle.
        #[arg(value_enum, default_value = "toggle")]
        mode: Switch,
    },
    /// Save a PNG of what the player window shows (works when it is covered).
    Screenshot {
        /// Output file (.png).
        path: std::path::PathBuf,
    },
    /// Close the player window.
    Close,
    /// Search a service (see `tvctl plugins` for which have search) and print
    /// results with URLs for `tvctl open`. Runs in a hidden tab of tvctl's Chrome
    /// (with its logins); the player is not touched.
    Search {
        /// Plugin name, e.g. youtube or spotify.
        service: String,
        /// What to search for.
        #[arg(required = true, num_args = 1..)]
        query: Vec<String>,
        /// Only results of this kind, e.g. track or artist (see `tvctl plugins`).
        #[arg(long)]
        kind: Option<String>,
        /// Another site of the service, e.g. jp for amazon.co.jp (see `tvctl plugins`).
        #[arg(long)]
        site: Option<String>,
        /// Maximum number of results.
        #[arg(long, default_value_t = 10)]
        limit: usize,
    },
    /// Log in to a service in tvctl's Chrome profile.
    Auth {
        #[command(subcommand)]
        action: AuthCmd,
    },
    /// Lower the player while other audio plays (e.g. a voice assistant
    /// speaking), and restore them when it stops.
    Duck {
        #[command(subcommand)]
        action: DuckCmd,
    },
    /// Let the YouTube app on phones and computers cast to this Mac: it appears
    /// in the app's Cast menu, and what is cast plays in the player window.
    Cast {
        #[command(subcommand)]
        action: CastCmd,
    },
    /// List the supported services (plugins), or show one: URL domains and
    /// examples, supported commands, login, and notes on its limits and values.
    Plugins {
        /// Plugin name, e.g. netflix; all plugins when omitted.
        name: Option<String>,
    },
    /// Start, stop or inspect the background server.
    Server {
        #[command(subcommand)]
        action: ServerCmd,
    },
    /// Output shell integration: eval "$(tvctl config zsh)" (or bash).
    Config {
        /// Shell to configure. In zsh, run compinit before evaluating the output.
        #[arg(value_enum)]
        shell: shell::Shell,
    },
    #[command(name = "__serve", hide = true)]
    Serve,
    /// Evaluate JavaScript in the player page (plugin development).
    #[command(name = "__eval", hide = true)]
    Eval { script: String },
}

#[derive(Subcommand)]
enum ServerCmd {
    /// Start the server (needed by `open`, player commands, `auth` and casting).
    ///
    /// It keeps running, with or without a player, until `server down`.
    Up,
    /// Stop the server and close the player.
    Down,
    /// Show whether the server is running, its pid, players and mode.
    Status,
}

#[derive(Subcommand)]
enum DuckCmd {
    /// Turn ducking on (saved; applies whenever the player is open).
    ///
    /// While other audio plays, the player plays at `--level` percent of its
    /// own volume (`volume` and `status` keep showing the player's own volume).
    /// Other audio is every app except tvctl's player, or only `--apps`.
    /// macOS 14.2+; macOS asks once for permission to record system audio, on
    /// behalf of the app that started tvctl (e.g. the terminal).
    On {
        /// Volume while other audio plays, in percent of the player's volume.
        #[arg(long, default_value_t = 10, value_parser = clap::value_parser!(u8).range(0..=100))]
        level: u8,
        /// Only these apps count, comma-separated: app names (ChatGPT), process
        /// names or bundle ids (com.openai.chat). See `tvctl duck apps`.
        #[arg(long, value_delimiter = ',')]
        apps: Option<Vec<String>>,
    },
    /// Turn ducking off and restore the player's volume.
    Off,
    /// Show the settings and whether the player is lowered now (`ducking`), the
    /// level of the monitored audio (`peak_db`) and which apps play (`sources`).
    Status,
    /// List the processes playing audio now, with the names usable in `--apps`.
    Apps,
}

#[derive(Subcommand)]
enum CastCmd {
    /// Turn the cast receiver on (saved; the receiver runs while the server runs,
    /// so start it with `tvctl server up`).
    ///
    /// Devices on the same network then list this Mac in the YouTube app's Cast
    /// menu. A cast video plays in the player window, replacing what it shows;
    /// play, pause, seek, volume and the queue (next/previous) are controlled
    /// from the app, and player commands such as `pause` or `next` from the
    /// command line show in the app. YouTube only (not YouTube Music). Uses YouTube's unpublished TV (Lounge) API.
    On {
        /// Name shown in the Cast menu. Default: the saved name, or
        /// "tvctl (<computer name>)".
        #[arg(long)]
        name: Option<String>,
    },
    /// Turn the cast receiver off.
    Off,
    /// Show whether the receiver runs, connected devices (`senders`) and the
    /// player and video being cast.
    Status,
    /// Get a code for the YouTube app's "Link with TV code" (Settings > Watch on
    /// TV), for devices that do not find this Mac on their own.
    Code,
}

#[derive(Subcommand)]
enum AuthCmd {
    /// Open the service's login page in tvctl's Chrome profile and wait.
    ///
    /// Sign in, then quit that Chrome (Cmd+Q). Prints `{"service", "logged_in"}`
    /// (plus `sites` with each site's state for services with several sites).
    /// Needs a person at the screen. Logged in, YouTube plays in Chrome (no ads with
    /// Premium); Spotify, Netflix, Prime Video and Crunchyroll require a login.
    Login {
        /// Plugin name, e.g. youtube, spotify, netflix, primevideo, crunchyroll.
        service: String,
        /// For services with several sites (`auth.sites` in `tvctl plugins`), the
        /// site to sign in to, e.g. `jp` for primevideo on amazon.co.jp. Default:
        /// the main site.
        #[arg(long)]
        site: Option<String>,
    },
    /// Show login state for one service or all services that support login.
    Status {
        /// Plugin name; all when omitted.
        service: Option<String>,
    },
}

#[derive(Args)]
struct GeometryArgs {
    /// Size of the video area in logical pixels, e.g. 1280x720.
    #[arg(long, value_parser = parse_pair::<'x'>)]
    size: Option<(f64, f64)>,
    /// Top-left corner of the window on screen, e.g. 100,50.
    #[arg(long, value_parser = parse_pair::<','>)]
    position: Option<(f64, f64)>,
    /// Snap to a screen region (fills it). With --size, the window keeps that size
    /// and is anchored to that side or corner.
    #[arg(long, value_enum)]
    layout: Option<Layout>,
}

fn parse_pair<const SEP: char>(s: &str) -> Result<(f64, f64), String> {
    let (a, b) = s
        .split_once(SEP)
        .ok_or_else(|| format!("expected two numbers separated by '{SEP}'"))?;
    let parse = |v: &str| v.trim().parse::<f64>().map_err(|e| format!("{v:?}: {e}"));
    Ok((parse(a)?, parse(b)?))
}

fn player(action: PlayerAction) -> Request {
    Request::Player { action }
}

fn seek_request(seek: Seek) -> Request {
    let (seconds, relative) = match seek {
        Seek::Absolute(s) => (s, false),
        Seek::Relative(s) => (s, true),
    };
    player(PlayerAction::Seek { seconds, relative })
}

/// What a command does: something local, or one request to the server.
#[derive(Debug)]
enum Plan {
    Config(shell::Shell),
    Serve,
    ServerUp,
    ServerDown,
    ServerStatus,
    Plugins(Option<String>),
    DuckSet(duck::Config),
    DuckStatus,
    DuckApps,
    CastSet(cast::Config),
    CastStatus,
    CastCode,
    Remote(Request),
}

fn plan(cmd: Cmd) -> Result<Plan> {
    let req = match cmd {
        Cmd::Config { shell } => return Ok(Plan::Config(shell)),
        Cmd::Serve => return Ok(Plan::Serve),
        Cmd::Server { action } => {
            return Ok(match action {
                ServerCmd::Up => Plan::ServerUp,
                ServerCmd::Down => Plan::ServerDown,
                ServerCmd::Status => Plan::ServerStatus,
            });
        }
        Cmd::Plugins { name } => return Ok(Plan::Plugins(name)),
        Cmd::Cast { action } => {
            return Ok(match action {
                CastCmd::On { name } => {
                    let name = cast::name_or_saved(name).trim().to_string();
                    if name.is_empty() {
                        return Err(anyhow!("--name must not be empty"));
                    }
                    Plan::CastSet(cast::Config {
                        enabled: true,
                        name,
                    })
                }
                CastCmd::Off => Plan::CastSet(cast::Config {
                    enabled: false,
                    ..cast::load()
                }),
                CastCmd::Status => Plan::CastStatus,
                CastCmd::Code => Plan::CastCode,
            });
        }
        Cmd::Duck { action } => {
            return Ok(match action {
                DuckCmd::On { level, apps } => {
                    let apps: Option<Vec<String>> = apps.map(|a| {
                        a.into_iter()
                            .map(|s| s.trim().to_string())
                            .filter(|s| !s.is_empty())
                            .collect()
                    });
                    if apps.as_ref().is_some_and(Vec::is_empty) {
                        return Err(anyhow!("--apps needs at least one app"));
                    }
                    Plan::DuckSet(duck::Config {
                        enabled: true,
                        level,
                        apps,
                    })
                }
                DuckCmd::Off => Plan::DuckSet(duck::Config {
                    enabled: false,
                    ..duck::load()
                }),
                DuckCmd::Status => Plan::DuckStatus,
                DuckCmd::Apps => Plan::DuckApps,
            });
        }
        Cmd::Open {
            url,
            start,
            paused,
            subtitles,
            window,
            fullscreen,
            windowed,
        } => {
            let start = start.map(|s| timeparse::parse_duration(&s)).transpose()?;
            let mut window = WindowOpts {
                size: window.size,
                position: window.position,
                layout: window.layout,
                fullscreen: None,
            };
            // Fullscreen by default; window options or --windowed show it in
            // a window (window options already leave fullscreen).
            window.fullscreen = if windowed {
                Some(Switch::Off)
            } else if fullscreen || !window.changes_geometry() {
                Some(Switch::On)
            } else {
                None
            };
            Request::Open {
                url,
                start,
                paused,
                subtitles,
                window,
            }
        }
        Cmd::Search {
            service,
            query,
            kind,
            site,
            limit,
        } => Request::Search {
            service,
            query: query.join(" "),
            kind,
            site,
            limit: limit.max(1),
        },
        Cmd::Auth { action } => match action {
            AuthCmd::Login { service, site } => Request::AuthLogin { service, site },
            AuthCmd::Status { service } => Request::AuthStatus { service },
        },
        Cmd::Audio { lang } => player(PlayerAction::Audio { lang }),
        Cmd::Status => player(PlayerAction::Status),
        Cmd::Play => player(PlayerAction::Play),
        Cmd::Pause => player(PlayerAction::Pause),
        Cmd::Toggle => player(PlayerAction::Toggle),
        Cmd::Next => player(PlayerAction::Next),
        Cmd::Prev => player(PlayerAction::Previous),
        Cmd::Eval { script } => Request::Eval { script },
        Cmd::Seek { position } => seek_request(timeparse::parse_seek(&position)?),
        Cmd::Forward { duration } => {
            seek_request(Seek::Relative(timeparse::parse_duration(&duration)?))
        }
        Cmd::Back { duration } => {
            seek_request(Seek::Relative(-timeparse::parse_duration(&duration)?))
        }
        Cmd::Subtitles { mode } => player(PlayerAction::Subtitles { lang: mode }),
        Cmd::Volume { level } => player(PlayerAction::Volume {
            level: Some(level),
            muted: None,
        }),
        Cmd::Mute => player(PlayerAction::Volume {
            level: None,
            muted: Some(true),
        }),
        Cmd::Unmute => player(PlayerAction::Volume {
            level: None,
            muted: Some(false),
        }),
        Cmd::Speed { rate } => {
            if !(0.0625..=16.0).contains(&rate) {
                return Err(anyhow!("speed must be between 0.0625 and 16"));
            }
            player(PlayerAction::Speed { rate })
        }
        Cmd::Quality { level } => player(PlayerAction::Quality { level }),
        Cmd::Window {
            geometry,
            fullscreen,
        } => Request::Window {
            opts: WindowOpts {
                size: geometry.size,
                position: geometry.position,
                layout: geometry.layout,
                fullscreen,
            },
        },
        Cmd::Fullscreen { mode } => Request::Window {
            opts: WindowOpts {
                fullscreen: Some(mode),
                ..Default::default()
            },
        },
        Cmd::Close => Request::Close,
        Cmd::Screenshot { path } => {
            // The server has a different working directory; send an absolute path.
            let path = std::path::absolute(&path)?;
            Request::Screenshot {
                path: path.to_string_lossy().into_owned(),
            }
        }
    };
    Ok(Plan::Remote(req))
}

fn run(cmd: Cmd) -> Result<Value> {
    match plan(cmd)? {
        Plan::Config(shell) => {
            shell::register(shell, &mut std::io::stdout().lock())?;
            Ok(Value::Null)
        }
        Plan::Serve => {
            server::run()?;
            Ok(Value::Null)
        }
        Plan::ServerUp => client::server_up(),
        Plan::ServerDown => client::server_down(),
        Plan::ServerStatus => client::server_status(),
        Plan::DuckSet(config) => client::duck_set(config),
        Plan::DuckStatus => client::duck_status(),
        Plan::DuckApps => client::duck_apps(),
        Plan::CastSet(config) => client::cast_set(config),
        Plan::CastStatus => client::cast_status(),
        Plan::CastCode => client::cast_code(),
        Plan::Plugins(name) => {
            let registry = plugin::Registry::load()?;
            match name {
                Some(name) => registry.describe(&name),
                None => Ok(json!({
                    "external_dir": plugin::external_dir(),
                    "plugins": registry.plugins().iter().map(plugin::Plugin::summary).collect::<Vec<_>>(),
                })),
            }
        }
        Plan::Remote(req) => {
            if let Request::AuthLogin { service, site } = &req
                && client::is_running()
            {
                let service = match site {
                    Some(s) => format!("{service} ({s})"),
                    None => service.clone(),
                };
                eprintln!(
                    "Sign in to {service} in the Chrome window that opens, then quit that Chrome (Cmd+Q) \
                     (for some services, closing the login window is enough)."
                );
            }
            client::send(&req)
        }
    }
}

/// The command line with the installed services listed in `--help`.
fn command() -> clap::Command {
    let services = match plugin::Registry::load() {
        Ok(r) => r.help_section(),
        Err(e) => format!("Services: could not load plugins: {e:#}"),
    };
    Cli::command().after_long_help(format!("{AFTER_LONG_HELP}\n\n{services}"))
}

fn main() {
    clap_complete::CompleteEnv::with_factory(shell::command)
        .var("TVCTL_COMPLETE")
        .complete();
    let cli = match Cli::from_arg_matches(&command().get_matches()) {
        Ok(cli) => cli,
        Err(e) => e.exit(),
    };
    let raw_output = matches!(cli.command, Cmd::Serve | Cmd::Config { .. });
    match run(cli.command) {
        Ok(v) if !raw_output => {
            println!(
                "{}",
                serde_json::to_string_pretty(&v).expect("serializable")
            );
        }
        Ok(_) => {}
        Err(e) => {
            eprintln!("error: {e:#}");
            std::process::exit(1);
        }
    }
}

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

    /// Parses a command line and returns the request JSON sent to the server.
    fn req(args: &[&str]) -> Value {
        let mut argv = vec!["tvctl"];
        argv.extend_from_slice(args);
        let cli = Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{args:?}: {e}"));
        match plan(cli.command).unwrap_or_else(|e| panic!("{args:?}: {e}")) {
            Plan::Remote(r) => serde_json::to_value(r).unwrap(),
            other => panic!("{args:?}: expected a remote request, got {other:?}"),
        }
    }

    fn rejects(args: &[&str]) {
        let mut argv = vec!["tvctl"];
        argv.extend_from_slice(args);
        let ok = Cli::try_parse_from(argv)
            .map(|c| plan(c.command).is_ok())
            .unwrap_or(false);
        assert!(!ok, "{args:?} should be rejected");
    }

    fn action(action: Value) -> Value {
        json!({ "cmd": "player", "action": action })
    }

    #[test]
    fn local_commands() {
        for (args, expect) in [
            (vec!["config", "zsh"], "Config(Zsh)"),
            (vec!["config", "bash"], "Config(Bash)"),
            (vec!["server", "up"], "ServerUp"),
            (vec!["server", "down"], "ServerDown"),
            (vec!["server", "status"], "ServerStatus"),
            (vec!["plugins"], "Plugins(None)"),
            (vec!["plugins", "netflix"], "Plugins(Some(\"netflix\"))"),
            (vec!["__serve"], "Serve"),
        ] {
            let mut argv = vec!["tvctl"];
            argv.extend(args.iter());
            let p = plan(Cli::try_parse_from(argv).unwrap().command).unwrap();
            assert_eq!(format!("{p:?}"), expect);
        }
    }

    fn duck_plan(args: &[&str]) -> Plan {
        let mut argv = vec!["tvctl", "duck"];
        argv.extend_from_slice(args);
        plan(Cli::try_parse_from(argv).unwrap().command).unwrap()
    }

    #[test]
    fn duck_commands() {
        let config = |p: Plan| match p {
            Plan::DuckSet(c) => c,
            other => panic!("expected DuckSet, got {other:?}"),
        };
        assert_eq!(
            config(duck_plan(&["on"])),
            duck::Config {
                enabled: true,
                level: 10,
                apps: None
            }
        );
        assert_eq!(
            config(duck_plan(&[
                "on",
                "--level",
                "25",
                "--apps",
                "ChatGPT, com.zoom.xos"
            ])),
            duck::Config {
                enabled: true,
                level: 25,
                apps: Some(vec!["ChatGPT".into(), "com.zoom.xos".into()])
            }
        );
        assert!(!config(duck_plan(&["off"])).enabled);
        assert!(matches!(duck_plan(&["status"]), Plan::DuckStatus));
        assert!(matches!(duck_plan(&["apps"]), Plan::DuckApps));
        rejects(&["duck", "on", "--level", "101"]);
        rejects(&["duck", "on", "--apps", " , "]);
    }

    #[test]
    fn open() {
        assert_eq!(
            req(&["open", "https://youtu.be/x"]),
            json!({
                "cmd": "open", "url": "https://youtu.be/x", "start": null,
                "paused": false, "subtitles": null,
                "window": { "size": null, "position": null, "layout": null, "fullscreen": "on" },
            })
        );
        let window = |args: &[&str]| {
            let mut all = vec!["open", "u"];
            all.extend_from_slice(args);
            req(&all)["window"].clone()
        };
        assert_eq!(window(&["--fullscreen"])["fullscreen"], "on");
        assert_eq!(window(&["--windowed"])["fullscreen"], "off");
        // Window options show it in a window unless --fullscreen is given.
        for opts in [
            &["--size", "640x360"][..],
            &["--position", "10,20"],
            &["--layout", "left"],
        ] {
            assert_eq!(window(opts)["fullscreen"], Value::Null, "{opts:?}");
        }
        assert_eq!(
            window(&["--layout", "left", "--windowed"])["fullscreen"],
            "off"
        );
        rejects(&["open", "u", "--fullscreen", "--windowed"]);
        assert_eq!(
            req(&[
                "open",
                "u",
                "--start",
                "1:30",
                "--paused",
                "--subtitles",
                "ja",
                "--size",
                "640x360",
                "--position",
                "10,20",
                "--layout",
                "bottom-right",
                "--fullscreen",
            ]),
            json!({
                "cmd": "open", "url": "u", "start": 90.0, "paused": true, "subtitles": "ja",
                "window": { "size": [640.0, 360.0], "position": [10.0, 20.0], "layout": "bottom-right",
                            "fullscreen": "on" },
            })
        );
        rejects(&["open"]);
        rejects(&["open", "u", "--start", "abc"]);
        rejects(&["open", "u", "--size", "640"]);
        rejects(&["open", "u", "--position", "1x2"]);
        rejects(&["open", "u", "--layout", "middle"]);
        // The WebView backend and its options are gone.
        rejects(&["open", "u", "--backend", "chrome"]);
        rejects(&["open", "u", "--on-top"]);
    }

    #[test]
    fn playback() {
        assert_eq!(req(&["status"]), action(json!({ "action": "status" })));
        assert_eq!(req(&["play"]), action(json!({ "action": "play" })));
        assert_eq!(req(&["pause"]), action(json!({ "action": "pause" })));
        assert_eq!(req(&["toggle"]), action(json!({ "action": "toggle" })));
        assert_eq!(req(&["next"]), action(json!({ "action": "next" })));
        assert_eq!(req(&["prev"]), action(json!({ "action": "previous" })));
        assert_eq!(
            req(&["__eval", "1+1"]),
            json!({ "cmd": "eval", "script": "1+1" })
        );
        rejects(&["play", "1"]);
    }

    #[test]
    fn seeking() {
        let seek =
            |s: f64, r: bool| action(json!({ "action": "seek", "seconds": s, "relative": r }));
        assert_eq!(req(&["seek", "90"]), seek(90.0, false));
        assert_eq!(req(&["seek", "1:02:03"]), seek(3723.0, false));
        assert_eq!(req(&["seek", "+10"]), seek(10.0, true));
        assert_eq!(req(&["seek", "-1m"]), seek(-60.0, true));
        assert_eq!(req(&["forward"]), seek(10.0, true));
        assert_eq!(req(&["forward", "30"]), seek(30.0, true));
        assert_eq!(req(&["back"]), seek(-10.0, true));
        assert_eq!(req(&["back", "1:00"]), seek(-60.0, true));
        rejects(&["seek", "soon"]);
        rejects(&["forward", "-5"]);
    }

    #[test]
    fn tracks_and_audio_settings() {
        assert_eq!(
            req(&["subtitles", "ja"]),
            action(json!({ "action": "subtitles", "lang": "ja" }))
        );
        assert_eq!(
            req(&["subtitles", "off"]),
            action(json!({ "action": "subtitles", "lang": "off" }))
        );
        assert_eq!(
            req(&["audio", "list"]),
            action(json!({ "action": "audio", "lang": "list" }))
        );
        assert_eq!(
            req(&["quality", "hd1080"]),
            action(json!({ "action": "quality", "level": "hd1080" }))
        );
        // Quality values are plugin-specific and validated by the plugin.
        assert_eq!(
            req(&["quality", "very-high"]),
            action(json!({ "action": "quality", "level": "very-high" }))
        );
        assert_eq!(
            req(&["volume", "30"]),
            action(json!({ "action": "volume", "level": 30, "muted": null }))
        );
        rejects(&["volume", "101"]);
        assert_eq!(
            req(&["mute"]),
            action(json!({ "action": "volume", "level": null, "muted": true }))
        );
        assert_eq!(
            req(&["unmute"]),
            action(json!({ "action": "volume", "level": null, "muted": false }))
        );
        assert_eq!(
            req(&["speed", "1.5"]),
            action(json!({ "action": "speed", "rate": 1.5 }))
        );
        rejects(&["speed", "0"]);
        rejects(&["speed", "32"]);
    }

    #[test]
    fn window_commands() {
        let opts = |v: Value| {
            let mut o =
                json!({ "size": null, "position": null, "layout": null, "fullscreen": null });
            for (k, val) in v.as_object().unwrap() {
                o[k] = val.clone();
            }
            o
        };
        assert_eq!(
            req(&["window", "--size", "800x450", "--position", "5,6"]),
            json!({ "cmd": "window", "opts": opts(json!({ "size": [800.0, 450.0], "position": [5.0, 6.0] })) })
        );
        for l in [
            "left",
            "right",
            "top",
            "bottom",
            "top-left",
            "top-right",
            "bottom-left",
            "bottom-right",
            "center",
            "maximize",
        ] {
            assert_eq!(
                req(&["window", "--layout", l]),
                json!({ "cmd": "window", "opts": opts(json!({ "layout": l })) })
            );
        }
        assert_eq!(
            req(&["window", "--fullscreen", "off"]),
            json!({ "cmd": "window", "opts": opts(json!({ "fullscreen": "off" })) })
        );
        assert_eq!(
            req(&["fullscreen"]),
            json!({ "cmd": "window", "opts": opts(json!({ "fullscreen": "toggle" })) })
        );
        assert_eq!(
            req(&["fullscreen", "on"]),
            json!({ "cmd": "window", "opts": opts(json!({ "fullscreen": "on" })) })
        );
        rejects(&["fullscreen", "maybe"]);
    }

    #[test]
    fn management_commands() {
        assert_eq!(req(&["close"]), json!({ "cmd": "close" }));
        // Commands take no player id, and `list` is gone.
        rejects(&["close", "4"]);
        rejects(&["list"]);
        assert_eq!(
            req(&["auth", "login", "youtube"]),
            json!({ "cmd": "auth_login", "service": "youtube", "site": null })
        );
        assert_eq!(
            req(&["auth", "login", "primevideo", "--site", "jp"]),
            json!({ "cmd": "auth_login", "service": "primevideo", "site": "jp" })
        );
        assert_eq!(
            req(&["auth", "status"]),
            json!({ "cmd": "auth_status", "service": null })
        );
        assert_eq!(
            req(&["auth", "status", "netflix"]),
            json!({ "cmd": "auth_status", "service": "netflix" })
        );
        let shot = req(&["screenshot", "shot.png"]);
        let path = shot["path"].as_str().unwrap();
        assert!(
            std::path::Path::new(path).is_absolute() && path.ends_with("shot.png"),
            "{path}"
        );
    }

    /// Agents rely on `--help`: every visible command and argument is described.
    #[test]
    fn help_is_complete() {
        fn check(cmd: &clap::Command, path: &str) {
            for sub in cmd
                .get_subcommands()
                .filter(|c| !c.is_hide_set() && c.get_name() != "help")
            {
                let name = format!("{path} {}", sub.get_name());
                assert!(sub.get_about().is_some(), "{name}: missing about");
                for arg in sub.get_arguments().filter(|a| !a.is_hide_set()) {
                    let id = arg.get_id().as_str();
                    if id == "help" || id == "version" {
                        continue;
                    }
                    assert!(
                        arg.get_help().is_some() || arg.get_long_help().is_some(),
                        "{name}: argument {id} has no help"
                    );
                }
                check(sub, &name);
            }
        }
        let cli = Cli::command();
        cli.clone().debug_assert();
        check(&cli, "tvctl");
        let long = cli.clone().render_long_help().to_string();
        for needle in [
            "Workflow:",
            "Output:",
            "Errors:",
            "Examples:",
            "tvctl plugins",
            "exit",
        ] {
            assert!(long.contains(needle), "long help lacks {needle:?}");
        }
        // The real command lists the installed services, with how to learn more.
        let long = command().render_long_help().to_string();
        for needle in [
            "Services (installed plugins)",
            "tvctl plugins <name>",
            "netflix",
            "primevideo",
            "(login required)",
            "e.g. tvctl open 'https://www.netflix.com/",
        ] {
            assert!(long.contains(needle), "long help lacks {needle:?}");
        }
    }
}