gyazo-mcp-server 0.6.3

Local MCP server for Gyazo with HTTP and stdio transport support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
use std::{fs, io::IsTerminal, path::PathBuf, process::Command};

use anyhow::{Context, Result, bail};
use inquire::Confirm;

use crate::auth::{config as auth_config, paths};

#[cfg(target_os = "linux")]
const SERVICE_NAME: &str = "gyazo-mcp-server";

pub(crate) fn install() -> Result<()> {
    // 既に登録されている場合は何もしない (冪等)。
    // 再登録したい場合は先に uninstall を実行してもらう。
    //
    // 非対応 OS では `is_installed_impl()` が常に false を返すので、
    // ここで早期 return すると常に未登録扱いになり、後段の OS 分岐の
    // `bail!` (非対応 OS エラー) に到達できなくなる。冪等化は対応 OS
    // でだけ行い、非対応 OS では従来どおり下の bail! まで進ませる。
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    if is_installed() {
        println!("サービスは既に登録されています。");
        println!("  状態確認: gyazo-mcp-server service status");
        println!("  再登録するには先に 'gyazo-mcp-server service uninstall' を実行してください。");
        return Ok(());
    }

    // --config-dir で一時 override されているが永続化されていない場合、
    // 常駐後のサービスはデフォルトの設定ディレクトリに戻ってしまう。
    // 意図しない設定不一致を防ぐため、確認を求める。
    if paths::has_config_dir_override() {
        let persisted = auth_config::read_config_dir_from_default_env();
        let override_dir = paths::config_dir()
            .map(|d| d.display().to_string())
            .unwrap_or_default();

        let mismatch = match &persisted {
            None => {
                // 永続化されていない
                Some(format!(
                    "警告: --config-dir が指定されていますが、永続化されていません。\n\
                     \x20 現在の override: {override_dir}\n\
                     \x20 常駐後のサービスはデフォルトの設定ディレクトリを使用します。\n\
                     \n\
                     永続化するには:\n\
                     \x20 gyazo-mcp-server config set config_dir {override_dir}"
                ))
            }
            Some(persisted_dir) if persisted_dir != &override_dir => {
                // 永続化されているが --config-dir と異なる
                Some(format!(
                    "警告: --config-dir と永続化された config_dir が異なります。\n\
                     \x20 --config-dir:  {override_dir}\n\
                     \x20 永続化済み:    {persisted_dir}\n\
                     \x20 常駐後のサービスは永続化された方 ({persisted_dir}) を使用します。\n\
                     \n\
                     --config-dir の値で上書きするには:\n\
                     \x20 gyazo-mcp-server config set config_dir {override_dir}"
                ))
            }
            _ => None, // 一致している
        };

        if let Some(message) = mismatch {
            eprintln!("{message}");
            eprintln!();

            if std::io::stdout().is_terminal() {
                let proceed = Confirm::new("このままサービスを登録しますか?")
                    .with_default(false)
                    .prompt()?;
                if !proceed {
                    println!("中断しました。");
                    return Ok(());
                }
            } else {
                bail!(
                    "--config-dir と永続化された config_dir が一致しない状態でのサービス登録は中断されました。"
                );
            }
        }
    }

    let binary = find_binary()?;

    #[cfg(target_os = "linux")]
    return install_systemd(&binary);

    #[cfg(target_os = "macos")]
    return install_launchd(&binary);

    #[cfg(target_os = "windows")]
    return install_windows_task(&binary);

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = binary;
        bail!(
            "この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。"
        );
    }
}

pub(crate) fn uninstall() -> Result<()> {
    // 登録されていない場合は何もしない (冪等)。
    // 非対応 OS では `is_installed_impl()` が常に false を返すので、
    // ここで早期 return すると後段の `bail!` (非対応 OS エラー) に
    // 到達できなくなる。冪等化は対応 OS でだけ行う。
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    if !is_installed() {
        println!("サービスは登録されていません。");
        println!("  登録するには 'gyazo-mcp-server service install' を実行してください。");
        return Ok(());
    }

    #[cfg(target_os = "linux")]
    return uninstall_systemd();

    #[cfg(target_os = "macos")]
    return uninstall_launchd();

    #[cfg(target_os = "windows")]
    return uninstall_windows_task();

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    bail!("この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。");
}

pub(crate) fn status() -> Result<()> {
    #[cfg(target_os = "linux")]
    return status_systemd();

    #[cfg(target_os = "macos")]
    return status_launchd();

    #[cfg(target_os = "windows")]
    return status_windows_task();

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    bail!("この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。");
}

pub(crate) fn start(tcp_port: u16) -> Result<()> {
    let _ = tcp_port; // Linux / macOS では未使用

    // 対応 OS では冪等化: 既に起動中と確定したら起動処理をスキップして
    // 案内を表示する。判定不能 (`Unknown`) の場合は OS 別ロジックへ流して
    // 本来のエラーを返させる。
    // 非対応 OS では `is_running_impl` が定義されていないためガードしない
    // (後段の `bail!` に到達させる)。
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    {
        ensure_installed()?;
        if is_running(tcp_port) == RunState::Running {
            println!("サービスは既に起動しています。");
            println!("  状態確認: gyazo-mcp-server service status");
            return Ok(());
        }
    }

    #[cfg(target_os = "linux")]
    return start_systemd();

    #[cfg(target_os = "macos")]
    return start_launchd();

    #[cfg(target_os = "windows")]
    return start_windows_task();

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    bail!("この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。");
}

pub(crate) fn stop(tcp_port: u16) -> Result<()> {
    let _ = tcp_port; // Linux / macOS では未使用

    // 対応 OS では冪等化: 既に停止中と確定したら停止処理をスキップして
    // 案内を表示する。判定不能 (`Unknown`) の場合は OS 別ロジックへ流して
    // 本来のエラーを返させる。
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    {
        ensure_installed()?;
        if is_running(tcp_port) == RunState::Stopped {
            println!("サービスは既に停止しています。");
            println!("  状態確認: gyazo-mcp-server service status");
            return Ok(());
        }
    }

    #[cfg(target_os = "linux")]
    return stop_systemd();

    #[cfg(target_os = "macos")]
    return stop_launchd();

    #[cfg(target_os = "windows")]
    return stop_windows_task(tcp_port);

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    bail!("この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。");
}

pub(crate) fn restart(tcp_port: u16) -> Result<()> {
    let _ = tcp_port;

    // 対応 OS では冪等化: 停止中と確定した場合のみ「起動のみ」案内を出す。
    // 判定不能 (`Unknown`) の場合は何もせず OS 別ロジックへ流して
    // 本来のエラーを返させる。
    #[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
    {
        ensure_installed()?;
        if is_running(tcp_port) == RunState::Stopped {
            println!("サービスは停止しています。起動のみ実行します。");
        }
    }

    #[cfg(target_os = "linux")]
    return restart_systemd();

    #[cfg(target_os = "macos")]
    return restart_launchd();

    #[cfg(target_os = "windows")]
    return restart_windows_task(tcp_port);

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    bail!("この OS ではサービスの自動登録に対応していません。手動でサービス設定を行ってください。");
}

/// サービスが未登録の場合に共通のヒント付きエラーを返す。
fn ensure_installed() -> Result<()> {
    if !is_installed() {
        bail!("サービスが登録されていません。\n  登録: gyazo-mcp-server service install");
    }
    Ok(())
}

/// サービスが登録済みかどうかを返す。
/// 検出できない環境では false を返す。
pub(crate) fn is_installed() -> bool {
    is_installed_impl()
}

/// サービスの実行状態。`Unknown` は判定不能 (環境エラー、コマンド失敗等) を
/// 表す。冪等ガードでは `Running` / `Stopped` の確定状態のときだけスキップし、
/// `Unknown` は従来どおり OS 別ロジックへ流して本来のエラーを返させる。
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RunState {
    Running,
    Stopped,
    Unknown,
}

/// サービス (HTTP transport) の実行状態を返す。
///
/// `tcp_port` は Windows でのみ使用 (TCP listen を起点にプロセスを特定するため)。
/// Linux / macOS では未使用。
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
fn is_running(tcp_port: u16) -> RunState {
    let _ = tcp_port;
    is_running_impl(tcp_port)
}

#[cfg(target_os = "linux")]
fn is_running_impl(_tcp_port: u16) -> RunState {
    // systemctl is-active --quiet の終了コード:
    //   0 = active (Running)
    //   3 = inactive / failed (Stopped)
    //   その他 = 状態不明 (環境エラー、unit 不在、systemctl 自体の失敗等)
    let Ok(status) = Command::new("systemctl")
        .args(["--user", "is-active", "--quiet", SERVICE_NAME])
        .status()
    else {
        return RunState::Unknown;
    };
    match status.code() {
        Some(0) => RunState::Running,
        Some(3) => RunState::Stopped,
        _ => RunState::Unknown,
    }
}

#[cfg(target_os = "macos")]
fn is_running_impl(_tcp_port: u16) -> RunState {
    // 引数なしの `launchctl list` は、ロード済みのジョブをタブ区切りで返す:
    //
    //     PID	Status	Label
    //     12345	0	com.gyazo.mcp-server
    //     -	0	com.other.service
    //
    // PID 列が `-` ならロード済みだが現在実行中ではない (= 停止中)。
    // 数値ならその PID で実行中 (= 起動中)。一覧自体に label が無ければ
    // 未ロード (= 停止中)。
    //
    // `launchctl list <label>` の per-label 呼び出しは未ロード時に
    // 非 0 終了するため、判定不能と未ロードの区別が難しい。引数なしの
    // `launchctl list` は launchctl 自体が動けば常に成功するので、
    // 「launchctl 自体の失敗」と「未ロード = 停止中」を確実に分けられる。
    let Ok(output) = Command::new("launchctl").arg("list").output() else {
        return RunState::Unknown;
    };
    if !output.status.success() {
        return RunState::Unknown;
    }
    let label = launchd_label();
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines().skip(1) {
        let cols: Vec<&str> = line.split('\t').collect();
        if cols.len() >= 3 && cols[2] == label {
            return if cols[0] != "-" {
                RunState::Running
            } else {
                RunState::Stopped
            };
        }
    }
    // 一覧に無い = 未ロード = 停止中
    RunState::Stopped
}

#[cfg(target_os = "windows")]
fn is_running_impl(tcp_port: u16) -> RunState {
    // 設定 TCP ポートを listen している `gyazo-mcp-server` プロセスがいれば
    // 実行中とみなす。stop と同じ判定方針 (port-listen + ProcessName 検証)。
    //
    // 終了コード:
    //   0 = Running (gyazo-mcp-server が listen している)
    //   2 = Stopped (listener が居ない、または listener が別プロセス)
    //   その他 = Unknown (PowerShell 自体の失敗等)
    let command = format!(
        "$conn = Get-NetTCPConnection -LocalPort {tcp_port} -State Listen \
            -ErrorAction SilentlyContinue | Select-Object -First 1; \
         if (-not $conn) {{ exit 2 }} \
         $proc = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue; \
         if ($proc -and $proc.ProcessName -eq 'gyazo-mcp-server') {{ exit 0 }} else {{ exit 2 }}"
    );
    let Ok(status) = Command::new("powershell")
        .args(["-NoProfile", "-Command", &command])
        .status()
    else {
        return RunState::Unknown;
    };
    match status.code() {
        Some(0) => RunState::Running,
        Some(2) => RunState::Stopped,
        _ => RunState::Unknown,
    }
}

#[cfg(target_os = "linux")]
fn is_installed_impl() -> bool {
    systemd_unit_path().is_ok_and(|p| p.exists())
}

#[cfg(target_os = "macos")]
fn is_installed_impl() -> bool {
    launchd_plist_path().is_ok_and(|p| p.exists())
}

#[cfg(target_os = "windows")]
fn is_installed_impl() -> bool {
    Command::new("schtasks")
        .args(["/Query", "/TN", task_name()])
        .output()
        .is_ok_and(|o| o.status.success())
}

#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
fn is_installed_impl() -> bool {
    false
}

/// 現在実行中のバイナリのパスを取得する
fn find_binary() -> Result<PathBuf> {
    std::env::current_exe().context("実行中のバイナリのパスを取得できませんでした")
}

// ---------------------------------------------------------------------------
// Linux (systemd)
// ---------------------------------------------------------------------------

#[cfg(target_os = "linux")]
fn systemd_unit_dir() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("HOME 環境変数が設定されていません")?;
    Ok(PathBuf::from(home).join(".config/systemd/user"))
}

#[cfg(target_os = "linux")]
fn systemd_unit_path() -> Result<PathBuf> {
    Ok(systemd_unit_dir()?.join(format!("{SERVICE_NAME}.service")))
}

/// systemd の user manager が利用可能かどうかを確認する。
/// systemctl バイナリの存在だけでなく、user manager が動作しているかを
/// daemon-reload で確認する(unit file の変更なしでも安全に実行できるため)。
#[cfg(target_os = "linux")]
fn has_systemd_user_manager() -> bool {
    Command::new("systemctl")
        .args(["--user", "daemon-reload"])
        .output()
        .is_ok_and(|o| o.status.success())
}

#[cfg(target_os = "linux")]
fn generate_systemd_unit(binary: &std::path::Path) -> String {
    // systemd unit ではパス中の空白が分割されるため、ダブルクォートで囲む
    let env_file = paths::env_file_path()
        .map(|p| format!("EnvironmentFile=-\"{}\"", p.display()))
        .unwrap_or_default();

    format!(
        "[Unit]
Description=Gyazo MCP Server
After=network.target

[Service]
Type=simple
ExecStart=\"{binary}\"
Restart=on-failure
RestartSec=5
{env_file}

[Install]
WantedBy=default.target
",
        binary = binary.display(),
    )
}

#[cfg(target_os = "linux")]
fn install_systemd(binary: &std::path::Path) -> Result<()> {
    if !has_systemd_user_manager() {
        bail!(
            "systemd の user manager が利用できません。\n\
             systemctl --user daemon-reload が失敗しました。\n\
             この環境では手動でサービス設定を行ってください。"
        );
    }

    let unit_path = systemd_unit_path()?;
    let unit_content = generate_systemd_unit(binary);

    fs::create_dir_all(unit_path.parent().unwrap())?;
    fs::write(&unit_path, &unit_content).with_context(|| {
        format!(
            "ユニットファイルを書き込めませんでした: {}",
            unit_path.display()
        )
    })?;

    println!("ユニットファイルを作成しました: {}", unit_path.display());

    run_command("systemctl", &["--user", "daemon-reload"])?;
    run_command("systemctl", &["--user", "enable", SERVICE_NAME])?;
    run_command("systemctl", &["--user", "start", SERVICE_NAME])?;

    println!("\nサービスを登録・起動しました。");
    println!("  状態確認: gyazo-mcp-server service status");
    println!("  ログ確認: journalctl --user -u {SERVICE_NAME} -f");
    Ok(())
}

#[cfg(target_os = "linux")]
fn uninstall_systemd() -> Result<()> {
    if !has_systemd_user_manager() {
        bail!("systemd の user manager が利用できません。");
    }

    // 停止・無効化はエラーでも続行(既に停止済みの場合がある)
    let _ = run_command("systemctl", &["--user", "stop", SERVICE_NAME]);
    let _ = run_command("systemctl", &["--user", "disable", SERVICE_NAME]);

    let unit_path = systemd_unit_path()?;
    if unit_path.exists() {
        fs::remove_file(&unit_path).with_context(|| {
            format!(
                "ユニットファイルを削除できませんでした: {}",
                unit_path.display()
            )
        })?;
        println!("ユニットファイルを削除しました: {}", unit_path.display());
    }

    run_command("systemctl", &["--user", "daemon-reload"])?;

    println!("サービス登録を解除しました。");
    Ok(())
}

#[cfg(target_os = "linux")]
fn status_systemd() -> Result<()> {
    if !has_systemd_user_manager() {
        bail!("systemd の user manager が利用できません。");
    }

    let unit_path = systemd_unit_path()?;
    if !unit_path.exists() {
        println!("サービスは登録されていません。");
        println!("  登録: gyazo-mcp-server service install");
        return Ok(());
    }

    // systemctl status は非 active でも exit code 3 を返すので、出力だけ表示
    let output = Command::new("systemctl")
        .args(["--user", "status", SERVICE_NAME])
        .output()
        .context("systemctl status の実行に失敗しました")?;

    print!("{}", String::from_utf8_lossy(&output.stdout));
    if !output.stderr.is_empty() {
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }
    Ok(())
}

#[cfg(target_os = "linux")]
fn start_systemd() -> Result<()> {
    ensure_installed()?;
    if !has_systemd_user_manager() {
        bail!("systemd の user manager が利用できません。");
    }
    run_command("systemctl", &["--user", "start", SERVICE_NAME])?;
    println!("サービスを起動しました。");
    Ok(())
}

#[cfg(target_os = "linux")]
fn stop_systemd() -> Result<()> {
    ensure_installed()?;
    if !has_systemd_user_manager() {
        bail!("systemd の user manager が利用できません。");
    }
    run_command("systemctl", &["--user", "stop", SERVICE_NAME])?;
    println!("サービスを停止しました。");
    Ok(())
}

#[cfg(target_os = "linux")]
fn restart_systemd() -> Result<()> {
    ensure_installed()?;
    if !has_systemd_user_manager() {
        bail!("systemd の user manager が利用できません。");
    }
    run_command("systemctl", &["--user", "restart", SERVICE_NAME])?;
    println!("サービスを再起動しました。");
    Ok(())
}

// ---------------------------------------------------------------------------
// macOS (launchd)
// ---------------------------------------------------------------------------

#[cfg(target_os = "macos")]
fn launchd_plist_dir() -> Result<PathBuf> {
    let home = std::env::var("HOME").context("HOME 環境変数が設定されていません")?;
    Ok(PathBuf::from(home).join("Library/LaunchAgents"))
}

#[cfg(target_os = "macos")]
fn launchd_label() -> String {
    "com.gyazo.mcp-server".to_string()
}

#[cfg(target_os = "macos")]
fn launchd_plist_path() -> Result<PathBuf> {
    Ok(launchd_plist_dir()?.join(format!("{}.plist", launchd_label())))
}

#[cfg(target_os = "macos")]
fn generate_launchd_plist(binary: &std::path::Path) -> String {
    let label = launchd_label();
    let log_dir = paths::config_dir()
        .map(|d| d.display().to_string())
        .unwrap_or_else(|| "/tmp".to_string());

    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>{label}</string>
    <key>ProgramArguments</key>
    <array>
        <string>{binary}</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <dict>
        <key>SuccessfulExit</key>
        <false/>
    </dict>
    <key>StandardOutPath</key>
    <string>{log_dir}/stdout.log</string>
    <key>StandardErrorPath</key>
    <string>{log_dir}/stderr.log</string>
</dict>
</plist>
"#,
        binary = binary.display(),
    )
}

#[cfg(target_os = "macos")]
fn install_launchd(binary: &std::path::Path) -> Result<()> {
    let plist_path = launchd_plist_path()?;
    let plist_content = generate_launchd_plist(binary);

    fs::create_dir_all(plist_path.parent().unwrap())?;
    fs::write(&plist_path, &plist_content)
        .with_context(|| format!("plist を書き込めませんでした: {}", plist_path.display()))?;

    println!("plist を作成しました: {}", plist_path.display());

    run_command("launchctl", &["load", &plist_path.display().to_string()])?;

    println!("\nサービスを登録・起動しました。");
    println!("  状態確認: gyazo-mcp-server service status");
    Ok(())
}

#[cfg(target_os = "macos")]
fn uninstall_launchd() -> Result<()> {
    let plist_path = launchd_plist_path()?;

    if plist_path.exists() {
        let _ = run_command("launchctl", &["unload", &plist_path.display().to_string()]);
        fs::remove_file(&plist_path)
            .with_context(|| format!("plist を削除できませんでした: {}", plist_path.display()))?;
        println!("plist を削除しました: {}", plist_path.display());
    }

    println!("サービス登録を解除しました。");
    Ok(())
}

#[cfg(target_os = "macos")]
fn status_launchd() -> Result<()> {
    let plist_path = launchd_plist_path()?;
    if !plist_path.exists() {
        println!("サービスは登録されていません。");
        println!("  登録: gyazo-mcp-server service install");
        return Ok(());
    }

    let label = launchd_label();
    let output = Command::new("launchctl")
        .args(["list", &label])
        .output()
        .context("launchctl list の実行に失敗しました")?;

    if output.status.success() {
        print!("{}", String::from_utf8_lossy(&output.stdout));
    } else {
        println!("サービスは登録されていますが、現在実行されていません。");
        println!("  plist: {}", plist_path.display());
    }
    Ok(())
}

#[cfg(target_os = "macos")]
fn start_launchd() -> Result<()> {
    ensure_installed()?;
    let plist_path = launchd_plist_path()?;
    // 既に load 済みでも冪等にしたいので、エラーは無視せず bail
    run_command("launchctl", &["load", &plist_path.display().to_string()])?;
    println!("サービスを起動しました。");
    Ok(())
}

#[cfg(target_os = "macos")]
fn stop_launchd() -> Result<()> {
    ensure_installed()?;
    let plist_path = launchd_plist_path()?;
    run_command("launchctl", &["unload", &plist_path.display().to_string()])?;
    println!("サービスを停止しました。");
    Ok(())
}

#[cfg(target_os = "macos")]
fn restart_launchd() -> Result<()> {
    ensure_installed()?;
    let plist_path = launchd_plist_path()?;
    // unload は既に停止していると失敗するので無視。load の方は失敗を伝える。
    let _ = run_command("launchctl", &["unload", &plist_path.display().to_string()]);
    run_command("launchctl", &["load", &plist_path.display().to_string()])?;
    println!("サービスを再起動しました。");
    Ok(())
}

// ---------------------------------------------------------------------------
// Windows (タスクスケジューラ)
// ---------------------------------------------------------------------------

#[cfg(target_os = "windows")]
fn task_name() -> &'static str {
    "GyazoMcpServer"
}

#[cfg(target_os = "windows")]
fn scripts_dir() -> Result<PathBuf> {
    paths::config_dir().ok_or_else(|| anyhow::anyhow!("設定ディレクトリを特定できませんでした"))
}

/// Windows PowerShell 5.x が生成する標準出力の文字コードを UTF-8 に固定する
/// プレリュード。Rust 側で `String::from_utf8_lossy` する前提なので、これを
/// 仕込まないと OEM コードページ (日本語環境では CP932) で書き出されて
/// 文字化けする。`.ps1` 自体は BOM 付き UTF-8 で書き出している。
#[cfg(target_os = "windows")]
fn ps1_utf8_prelude() -> &'static str {
    "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n\
     $OutputEncoding = [System.Text.Encoding]::UTF8\n"
}

#[cfg(target_os = "windows")]
fn generate_install_ps1(binary: &std::path::Path) -> String {
    // タスクスケジューラから直接 EXE を起動するとフォアグラウンドのコンソール
    // ウィンドウが残ってしまうため、`powershell.exe -WindowStyle Hidden` の中で
    // さらに `Start-Process -WindowStyle Hidden` を呼んでバックグラウンドに回す。
    // PowerShell の文字列リテラル中のダブルクォートは `""` でエスケープする。
    let task = task_name();
    let prelude = ps1_utf8_prelude();
    format!(
        r#"{prelude}$action = New-ScheduledTaskAction `
  -Execute "powershell.exe" `
  -Argument "-WindowStyle Hidden -Command ""Start-Process -WindowStyle Hidden -FilePath '{binary}'"""
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit 0
Register-ScheduledTask -TaskName '{task}' -Action $action -Trigger $trigger -Settings $settings -Description 'Gyazo MCP Server (HTTP transport)'
Write-Host 'タスク "{task}" を登録しました。'
"#,
        binary = binary.display(),
    )
}

#[cfg(target_os = "windows")]
fn generate_uninstall_ps1() -> String {
    let task = task_name();
    let prelude = ps1_utf8_prelude();
    // タスク登録を解除したあと、実行中の gyazo-mcp-server.exe
    // (HTTP listen 中) を検出して、もし残っていれば警告だけを出す。
    //
    // タスクは `powershell.exe -Command "Start-Process ..."` で本体を
    // 切り離して起動しているため、`Unregister-ScheduledTask` だけでは
    // 本体プロセスが停止せず、サービスが解除された後もそのまま動き続ける。
    // ただし、停止まで自動で行うと「別ポートで手動起動した HTTP インスタンス」
    // など、サービス管理対象でない gyazo-mcp-server まで巻き込んでしまう
    // 可能性があるため、停止操作はユーザーに委ねる。
    //
    // 検出対象は次の方針:
    //   1. `Get-NetTCPConnection -State Listen` で全 listen ポートを列挙
    //   2. その OwningProcess の `ProcessName` が `gyazo-mcp-server` のものだけ抽出
    //   3. 該当する PID と LocalPort を警告として表示
    //
    // この方式は HTTP モードのインスタンスを正確に拾え、stdio モードで動いて
    // いる同名プロセスは TCP listen していないので検出対象に含まれない。
    format!(
        r#"{prelude}Unregister-ScheduledTask -TaskName '{task}' -Confirm:$false
Write-Host 'タスク "{task}" を解除しました。'

$listeners = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue
$running = @()
foreach ($conn in $listeners) {{
    $proc = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
    if ($proc -and $proc.ProcessName -eq 'gyazo-mcp-server') {{
        $running += [PSCustomObject]@{{ ProcessId = $conn.OwningProcess; LocalPort = $conn.LocalPort }}
    }}
}}
$running = $running | Sort-Object ProcessId, LocalPort -Unique
if ($running) {{
    Write-Warning '実行中の gyazo-mcp-server (HTTP transport) プロセスが残っています。サービス登録は解除されましたが、これらのプロセスは引き続き動作します。停止が必要な場合は手動で停止してください。'
    $running | Format-Table -AutoSize ProcessId, LocalPort | Out-String | Write-Host
    Write-Host '停止例: Stop-Process -Id <PID> -Force'
}}
"#,
    )
}

#[cfg(target_os = "windows")]
fn run_powershell_script(script_path: &std::path::Path) -> Result<()> {
    let output = Command::new("powershell")
        .args([
            "-ExecutionPolicy",
            "Bypass",
            "-File",
            &script_path.display().to_string(),
        ])
        .output()
        .with_context(|| {
            format!(
                "PowerShell スクリプトの実行に失敗しました: {}",
                script_path.display()
            )
        })?;

    print!("{}", String::from_utf8_lossy(&output.stdout));
    if !output.stderr.is_empty() {
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }
    if !output.status.success() {
        bail!(
            "PowerShell スクリプトがエラーで終了しました (exit code: {:?})",
            output.status.code()
        );
    }
    Ok(())
}

/// PowerShell スクリプトを UTF-8 BOM 付きで書き出す。
///
/// Windows PowerShell 5.x は歴史的経緯により BOM なし UTF-8 を OS の現行
/// ANSI コードページとして解釈してしまい、日本語等の非 ASCII 文字が文字化け
/// したりパースエラーを起こす。BOM (`EF BB BF`) を先頭に付けると Unicode
/// として正しく扱われるため、`.ps1` を出力するときは必ずこのヘルパーを使う。
#[cfg(target_os = "windows")]
fn write_ps1_with_bom(path: &std::path::Path, content: &str) -> Result<()> {
    let mut bytes = Vec::with_capacity(content.len() + 3);
    bytes.extend_from_slice(b"\xEF\xBB\xBF");
    bytes.extend_from_slice(content.as_bytes());
    fs::write(path, bytes)
        .with_context(|| format!("スクリプトを書き込めませんでした: {}", path.display()))
}

#[cfg(target_os = "windows")]
fn install_windows_task(binary: &std::path::Path) -> Result<()> {
    let dir = scripts_dir()?;
    fs::create_dir_all(&dir)?;

    let script_path = dir.join("service-install.ps1");
    let script_content = generate_install_ps1(binary);
    write_ps1_with_bom(&script_path, &script_content)?;

    println!("スクリプトを作成しました: {}", script_path.display());

    run_powershell_script(&script_path)?;

    println!("\n  状態確認: gyazo-mcp-server service status");
    Ok(())
}

#[cfg(target_os = "windows")]
fn uninstall_windows_task() -> Result<()> {
    let dir = scripts_dir()?;
    fs::create_dir_all(&dir)?;

    let script_path = dir.join("service-uninstall.ps1");
    let script_content = generate_uninstall_ps1();
    write_ps1_with_bom(&script_path, &script_content)?;

    run_powershell_script(&script_path)?;

    // スクリプト自体も掃除
    let _ = fs::remove_file(dir.join("service-install.ps1"));
    let _ = fs::remove_file(&script_path);

    Ok(())
}

/// schtasks.exe をサブコマンド付きで実行し、出力を表示する。
/// schtasks の標準出力は OEM コードページなので、PowerShell 経由で
/// `[Console]::OutputEncoding` を UTF-8 に固定してから受け取る。
#[cfg(target_os = "windows")]
fn run_schtasks(action: &str) -> Result<()> {
    let task = task_name();
    let command = format!(
        "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; \
         schtasks.exe {action} /TN '{task}'"
    );
    let output = Command::new("powershell")
        .args(["-NoProfile", "-Command", &command])
        .output()
        .with_context(|| format!("schtasks {action} の実行に失敗しました"))?;

    if !output.stdout.is_empty() {
        print!("{}", String::from_utf8_lossy(&output.stdout));
    }
    if !output.stderr.is_empty() {
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }
    if !output.status.success() {
        bail!(
            "schtasks {action} がエラーで終了しました (exit code: {:?})",
            output.status.code()
        );
    }
    Ok(())
}

#[cfg(target_os = "windows")]
fn start_windows_task() -> Result<()> {
    ensure_installed()?;
    run_schtasks("/Run")?;
    println!("サービスを起動しました。");
    Ok(())
}

/// 指定 TCP ポートを listen している HTTP サーバープロセスを停止する。
///
/// タスクスケジューラ側のタスクは `powershell.exe -Command "Start-Process ..."`
/// で本体を切り離して起動しているため、`schtasks /End` で止められるのは
/// 即時終了する PowerShell ラッパーだけで、`gyazo-mcp-server.exe` 本体は
/// 残ってしまう。一方、プロセス名 (`Get-Process -Name gyazo-mcp-server`) で
/// 止めると stdio モードや手動起動した別プロセスまで巻き込む。
///
/// HTTP サーバーは `tcp_port` を必ず bind するため、`Get-NetTCPConnection`
/// から OwningProcess の PID を取得して、その PID だけを `Stop-Process` する
/// ことで「サービスとして動いている本体」だけを正確に停止する。
/// `stop_gyazo_mcp_server_by_port` で実行する PowerShell コマンド文字列を
/// 構築する。テスト容易性のため `format!` を関数化している。
#[cfg(target_os = "windows")]
fn build_stop_by_port_command(tcp_port: u16) -> String {
    format!(
        "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; \
         $owners = Get-NetTCPConnection -LocalPort {tcp_port} -State Listen \
             -ErrorAction SilentlyContinue \
             | Select-Object -ExpandProperty OwningProcess -Unique; \
         if (-not $owners) {{ \
             Write-Host 'ポート {tcp_port} を listen しているプロセスは見つかりませんでした。'; \
             exit 0; \
         }} \
         foreach ($pid_ in $owners) {{ \
             $proc = Get-Process -Id $pid_ -ErrorAction SilentlyContinue; \
             if ($proc -and $proc.ProcessName -eq 'gyazo-mcp-server') {{ \
                 Stop-Process -Id $pid_ -Force; \
                 Write-Host (\"PID $pid_ (gyazo-mcp-server) を停止しました。\"); \
             }} else {{ \
                 $name = if ($proc) {{ $proc.ProcessName }} else {{ 'unknown' }}; \
                 Write-Error (\"ポート {tcp_port} を listen しているのは gyazo-mcp-server ではありません (PID $pid_, name $name)。停止を中断します。\"); \
                 exit 1; \
             }} \
         }}"
    )
}

#[cfg(target_os = "windows")]
fn stop_gyazo_mcp_server_by_port(tcp_port: u16) -> Result<()> {
    let command = build_stop_by_port_command(tcp_port);
    let output = Command::new("powershell")
        .args(["-NoProfile", "-Command", &command])
        .output()
        .context("gyazo-mcp-server プロセスの停止に失敗しました")?;

    if !output.stdout.is_empty() {
        print!("{}", String::from_utf8_lossy(&output.stdout));
    }
    if !output.stderr.is_empty() {
        eprint!("{}", String::from_utf8_lossy(&output.stderr));
    }
    if !output.status.success() {
        bail!(
            "gyazo-mcp-server プロセスの停止がエラーで終了しました (exit code: {:?})",
            output.status.code()
        );
    }
    Ok(())
}

#[cfg(target_os = "windows")]
fn stop_windows_task(tcp_port: u16) -> Result<()> {
    ensure_installed()?;
    stop_gyazo_mcp_server_by_port(tcp_port)?;
    println!("サービスを停止しました。");
    Ok(())
}

#[cfg(target_os = "windows")]
fn restart_windows_task(tcp_port: u16) -> Result<()> {
    ensure_installed()?;
    stop_gyazo_mcp_server_by_port(tcp_port)?;
    run_schtasks("/Run")?;
    println!("サービスを再起動しました。");
    Ok(())
}

#[cfg(target_os = "windows")]
fn status_windows_task() -> Result<()> {
    // schtasks.exe の出力は OEM コードページ (日本語環境では CP932) なので、
    // Rust 側で UTF-8 として読むと文字化けする。PowerShell 経由で
    // `[Console]::OutputEncoding` を UTF-8 に固定してから schtasks を起動し、
    // 標準出力を UTF-8 で受け取る。
    let task = task_name();
    let command = format!(
        "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; \
         schtasks.exe /Query /TN '{task}' /FO LIST /V"
    );
    let output = Command::new("powershell")
        .args(["-NoProfile", "-Command", &command])
        .output()
        .context("schtasks の実行に失敗しました")?;

    if output.status.success() {
        print!("{}", String::from_utf8_lossy(&output.stdout));
    } else {
        println!("サービスは登録されていません。");
        println!("  登録: gyazo-mcp-server service install");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// 共通ユーティリティ
// ---------------------------------------------------------------------------

#[cfg(any(target_os = "linux", target_os = "macos"))]
fn run_command(program: &str, args: &[&str]) -> Result<()> {
    let output = Command::new(program)
        .args(args)
        .output()
        .with_context(|| format!("{program} の実行に失敗しました"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("{program} がエラーで終了しました: {stderr}");
    }
    Ok(())
}

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

    #[test]
    fn find_binary_returns_current_exe() {
        let binary = find_binary().unwrap();
        assert!(binary.exists());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn systemd_unit_contains_binary_path() {
        let binary = PathBuf::from("/usr/local/bin/gyazo-mcp-server");
        let unit = generate_systemd_unit(&binary);

        assert!(unit.contains("ExecStart=\"/usr/local/bin/gyazo-mcp-server\""));
        assert!(unit.contains("[Install]"));
        assert!(unit.contains("WantedBy=default.target"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn systemd_unit_quotes_paths_with_spaces() {
        let binary = PathBuf::from("/opt/my programs/gyazo-mcp-server");
        let unit = generate_systemd_unit(&binary);

        // 空白入りパスがダブルクォートで囲まれていること
        assert!(unit.contains("ExecStart=\"/opt/my programs/gyazo-mcp-server\""));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn launchd_plist_contains_binary_path() {
        let binary = PathBuf::from("/usr/local/bin/gyazo-mcp-server");
        let plist = generate_launchd_plist(&binary);

        assert!(plist.contains("/usr/local/bin/gyazo-mcp-server"));
        assert!(plist.contains("RunAtLoad"));
        assert!(plist.contains(&launchd_label()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn install_ps1_contains_task_name() {
        let binary = PathBuf::from(r"C:\Users\test\.cargo\bin\gyazo-mcp-server.exe");
        let ps1 = generate_install_ps1(&binary);

        assert!(ps1.contains(task_name()));
        assert!(ps1.contains(r"C:\Users\test\.cargo\bin\gyazo-mcp-server.exe"));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn stop_by_port_command_uses_owning_process_and_validates_name() {
        // 回帰テスト:
        // - `schtasks /End` 方式 (本体ではなくラッパー PowerShell しか止まらない) に
        //   戻していないこと
        // - `Get-Process -Name gyazo-mcp-server` 方式 (stdio や手動起動の同名プロセス
        //   まで巻き込む) に戻していないこと
        // - `Get-NetTCPConnection -LocalPort <port> -State Listen` から OwningProcess
        //   の PID を取り、`gyazo-mcp-server` であることを検証してから Stop-Process
        //   する形式を維持していること
        let command = build_stop_by_port_command(18449);

        assert!(
            command.contains("Get-NetTCPConnection -LocalPort 18449 -State Listen"),
            "ポートで listen プロセスを特定する形式になっていません: {command}"
        );
        assert!(
            command.contains("OwningProcess"),
            "OwningProcess から PID を取得していません: {command}"
        );
        assert!(
            command.contains("Stop-Process -Id"),
            "PID を指定した Stop-Process になっていません: {command}"
        );
        assert!(
            command.contains("ProcessName -eq 'gyazo-mcp-server'"),
            "停止対象が gyazo-mcp-server かどうかを検証していません: {command}"
        );
        assert!(
            !command.contains("schtasks /End"),
            "schtasks /End 方式に回帰しています (タスク本体ではなくラッパーしか止まりません): {command}"
        );
        assert!(
            !command.contains("Get-Process -Name gyazo-mcp-server"),
            "Get-Process -Name 方式に回帰しています (同名プロセスを巻き込みます): {command}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn stop_by_port_command_embeds_dynamic_port() {
        // tcp_port が format に流れ込んでいることを保証する。
        let command = build_stop_by_port_command(19000);
        assert!(
            command.contains("LocalPort 19000"),
            "渡した tcp_port が反映されていません: {command}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn install_ps1_runs_binary_via_hidden_powershell() {
        // タスクスケジューラから直接 EXE を起動するとフォアグラウンドの
        // コンソールウィンドウが残るため、powershell.exe + Start-Process で
        // バックグラウンド化していることを保証する。
        let binary = PathBuf::from(r"C:\bin\gyazo-mcp-server.exe");
        let ps1 = generate_install_ps1(&binary);

        assert!(
            ps1.contains(r#"-Execute "powershell.exe""#),
            "powershell.exe を Execute に指定していません"
        );
        assert!(
            ps1.contains("Start-Process -WindowStyle Hidden"),
            "Start-Process でバックグラウンド起動にしていません"
        );
        assert!(
            ps1.contains("-WindowStyle Hidden -Command"),
            "powershell.exe の WindowStyle が Hidden ではありません"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn uninstall_ps1_contains_task_name() {
        let ps1 = generate_uninstall_ps1();
        assert!(ps1.contains(task_name()));
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn generated_ps1_sets_utf8_output_encoding() {
        // Windows PowerShell 5.x の標準出力は既定で OEM コードページなので、
        // Rust 側で UTF-8 として読むと文字化けする。生成スクリプトの先頭で
        // `[Console]::OutputEncoding` を UTF-8 に固定していることを保証する。
        let install = generate_install_ps1(&PathBuf::from(r"C:\bin\gyazo-mcp-server.exe"));
        let uninstall = generate_uninstall_ps1();
        for (label, ps1) in [("install", &install), ("uninstall", &uninstall)] {
            assert!(
                ps1.contains("[Console]::OutputEncoding = [System.Text.Encoding]::UTF8"),
                "{label} ps1 に Console::OutputEncoding の UTF-8 化が含まれていません"
            );
            assert!(
                ps1.contains("$OutputEncoding = [System.Text.Encoding]::UTF8"),
                "{label} ps1 に $OutputEncoding の UTF-8 化が含まれていません"
            );
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn uninstall_ps1_warns_about_running_listener_processes_without_stopping_them() {
        // 回帰テスト:
        // - uninstall は本体プロセスを自動停止しない (別ポートで手動起動した
        //   HTTP インスタンス等を巻き込まないため)。
        // - そのかわり、Unregister-ScheduledTask の後に
        //   `Get-NetTCPConnection -State Listen` で listen 中のプロセスを
        //   走査し、`ProcessName -eq 'gyazo-mcp-server'` のものが残っていれば
        //   PID と LocalPort を警告として表示する。
        // - Stop-Process 方式 (どんな形でも自動停止する) には回帰していない
        //   こと。
        let ps1 = generate_uninstall_ps1();

        // 検出ロジックの存在
        assert!(
            ps1.contains("Get-NetTCPConnection -State Listen"),
            "listen ポートを起点に走査する形式になっていません: {ps1}"
        );
        assert!(
            ps1.contains("OwningProcess"),
            "OwningProcess から PID を辿っていません: {ps1}"
        );
        assert!(
            ps1.contains("ProcessName -eq 'gyazo-mcp-server'"),
            "検出対象を gyazo-mcp-server に限定していません: {ps1}"
        );
        assert!(
            ps1.contains("Write-Warning"),
            "残存プロセスを警告として通知していません: {ps1}"
        );

        // 自動停止していないこと:
        // `Stop-Process` という文字列はヒント表示用の `Write-Host '停止例: ...'`
        // 内に出てくるため、単純な `!contains("Stop-Process")` だと誤検知する。
        // 「実行コマンドとして書かれた `Stop-Process`」だけを禁止したいので、
        // `Stop-Process` を含む行はすべて `Write-Host` (= ヒント表示) で
        // 始まることを確認する形に変更。
        for line in ps1.lines() {
            let trimmed = line.trim_start();
            if trimmed.contains("Stop-Process") {
                assert!(
                    trimmed.starts_with("Write-Host"),
                    "Stop-Process が Write-Host (ヒント表示) 以外の行で使われています \
                     (自動停止に回帰): {line}"
                );
            }
        }
        assert!(
            !ps1.contains("Get-Process -Name gyazo-mcp-server"),
            "Get-Process -Name 方式に回帰しています: {ps1}"
        );

        // 検出ブロックは Unregister-ScheduledTask の後に書かれていること
        // (まずサービス登録を解除してから残存検出する順序の回帰防止)
        let unregister_pos = ps1
            .find("Unregister-ScheduledTask")
            .expect("Unregister-ScheduledTask が含まれていません");
        let detect_pos = ps1
            .find("Get-NetTCPConnection -State Listen")
            .expect("検出ブロックが含まれていません");
        assert!(
            unregister_pos < detect_pos,
            "Unregister-ScheduledTask が検出ブロックより後にあります (順序が逆): {ps1}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn write_ps1_with_bom_prepends_utf8_bom() {
        // Windows PowerShell 5.x が日本語を文字化けせず読めるよう、
        // 出力先頭に UTF-8 BOM (EF BB BF) が付くことを保証する。
        let unique = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("gyazo-mcp-ps1-bom-test-{unique}"));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.ps1");

        write_ps1_with_bom(&path, "Write-Host 'こんにちは'\n").unwrap();

        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(&bytes[..3], b"\xEF\xBB\xBF", "UTF-8 BOM が付いていません");
        assert_eq!(
            std::str::from_utf8(&bytes[3..]).unwrap(),
            "Write-Host 'こんにちは'\n"
        );

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn is_installed_returns_bool_without_panic() {
        // is_installed() がパニックせずに bool を返すことを確認。
        // 開発環境では登録済みの場合もあるため、値自体はアサートしない。
        let _result: bool = is_installed();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn systemd_unit_path_is_under_user_config() {
        let path = systemd_unit_path().unwrap();
        let path_str = path.display().to_string();
        assert!(path_str.contains(".config/systemd/user"));
        assert!(path_str.ends_with("gyazo-mcp-server.service"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn systemd_unit_includes_restart_on_failure() {
        let binary = PathBuf::from("/usr/bin/gyazo-mcp-server");
        let unit = generate_systemd_unit(&binary);
        assert!(unit.contains("Restart=on-failure"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn launchd_plist_path_is_under_launch_agents() {
        let path = launchd_plist_path().unwrap();
        let path_str = path.display().to_string();
        assert!(path_str.contains("Library/LaunchAgents"));
        assert!(path_str.ends_with(".plist"));
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn launchd_plist_includes_keep_alive() {
        let binary = PathBuf::from("/usr/local/bin/gyazo-mcp-server");
        let plist = generate_launchd_plist(&binary);
        assert!(plist.contains("KeepAlive"));
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn has_systemd_user_manager_returns_bool_without_panic() {
        // systemd がある環境でもない環境でもパニックせず bool を返すことを確認
        let _result: bool = has_systemd_user_manager();
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn systemd_unit_does_not_contain_config_dir_flag() {
        // サービス定義に --config-dir を含めない(起動時の bootstrap で解決するため)
        let binary = PathBuf::from("/usr/bin/gyazo-mcp-server");
        let unit = generate_systemd_unit(&binary);
        assert!(
            !unit.contains("--config-dir"),
            "サービス定義に --config-dir を含めてはならない"
        );
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn launchd_plist_does_not_contain_config_dir_flag() {
        let binary = PathBuf::from("/usr/local/bin/gyazo-mcp-server");
        let plist = generate_launchd_plist(&binary);
        assert!(
            !plist.contains("--config-dir"),
            "サービス定義に --config-dir を含めてはならない"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn install_ps1_does_not_contain_config_dir_flag() {
        let binary = PathBuf::from(r"C:\Users\test\.cargo\bin\gyazo-mcp-server.exe");
        let ps1 = generate_install_ps1(&binary);
        assert!(
            !ps1.contains("--config-dir"),
            "サービス定義に --config-dir を含めてはならない"
        );
    }
}