summaryrefslogtreecommitdiff
path: root/makima/src/bin/makima.rs
blob: 67eefc6e6393774ab3678362c2ea290556a7b46d (plain) (blame)
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
//! Makima CLI - unified CLI for server, daemon, and task management.

use std::io::{self, Read};
use std::path::Path;
use std::sync::Arc;

use makima::daemon::api::{ApiClient, CreateContractRequest};
use makima::daemon::cli::{
    Cli, CliConfig, Commands, ConfigCommand, ContractCommand, SupervisorCommand, ViewArgs,
};
use makima::daemon::tui::{self, Action, App, ListItem, ViewType, TuiWsClient, WsEvent, OutputLine, OutputMessageType, WsConnectionState, RepositorySuggestion};
use makima::daemon::config::{DaemonConfig, RepoEntry};
use makima::daemon::db::LocalDb;
use makima::daemon::error::DaemonError;
use makima::daemon::task::{TaskConfig, TaskManager};
use makima::daemon::ws::{DaemonCommand, WsClient};
use tokio::process::Command;
use tokio::sync::mpsc;
use tracing_subscriber::{fmt, prelude::*, EnvFilter};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let cli = Cli::parse_args();

    match cli.command {
        Commands::Server(args) => run_server(args).await,
        Commands::Daemon(args) => run_daemon(args).await,
        Commands::Supervisor(cmd) => run_supervisor(cmd).await,
        Commands::Contract(cmd) => run_contract(cmd).await,
        Commands::View(args) => run_view(args).await,
        Commands::Config(cmd) => run_config(cmd).await,
    }
}

/// Run the makima server.
async fn run_server(
    args: makima::daemon::cli::ServerArgs,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Initialize logging
    init_logging(&args.log_level, "text");

    eprintln!("=== Makima Server Starting ===");
    eprintln!("Port: {}", args.port);

    // Create app state
    let mut app_state = makima::server::state::AppState::new(
        &args.parakeet_model_dir,
        &args.parakeet_eou_dir,
        &args.sortformer_model_path,
    );

    // Connect to database if URL provided
    if let Some(ref db_url) = args.database_url {
        eprintln!("Connecting to database...");
        let pool = makima::db::create_pool(db_url).await?;
        app_state = app_state.with_db_pool(pool);
        eprintln!("Database connected");
    }

    let state = Arc::new(app_state);
    let addr = format!("0.0.0.0:{}", args.port);

    eprintln!("Starting server on {}", addr);
    makima::server::run_server(state, &addr).await?;

    Ok(())
}

/// Run the makima daemon.
async fn run_daemon(
    args: makima::daemon::cli::DaemonArgs,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    eprintln!("=== Makima Daemon Starting ===");

    // Build a temporary CLI struct for config loading
    let cli = makima::daemon::cli::daemon::DaemonArgs {
        config: args.config,
        repos_dir: args.repos_dir,
        worktrees_dir: args.worktrees_dir,
        server_url: args.server_url,
        api_key: args.api_key,
        max_tasks: args.max_tasks,
        log_level: args.log_level,
        bubblewrap: args.bubblewrap,
    };

    // Load configuration with CLI overrides
    eprintln!("[1/5] Loading configuration...");
    let config = match DaemonConfig::load_with_daemon_args(&cli) {
        Ok(cfg) => {
            eprintln!("      Config loaded: server={}", cfg.server.url);
            cfg
        }
        Err(e) => {
            eprintln!("Failed to load configuration: {}", e);
            eprintln!();
            eprintln!("Use CLI flags:");
            eprintln!("  makima daemon --server-url ws://localhost:8080 --api-key your-api-key");
            eprintln!();
            eprintln!("Or set environment variables:");
            eprintln!("  MAKIMA_DAEMON_SERVER_URL=ws://localhost:8080");
            eprintln!("  MAKIMA_API_KEY=your-api-key");
            eprintln!();
            eprintln!("Or create a config file: makima-daemon.toml");
            std::process::exit(1);
        }
    };

    // Initialize logging
    init_logging(&config.logging.level, &config.logging.format);
    eprintln!("[2/5] Logging initialized");

    // Initialize local database
    eprintln!(
        "[3/5] Opening local database: {}",
        config.local_db.path.display()
    );
    let _local_db = LocalDb::open(&config.local_db.path)?;
    eprintln!("      Database opened");

    // Initialize worktree directories
    eprintln!("[4/5] Setting up directories...");
    tokio::fs::create_dir_all(&config.worktree.base_dir).await?;
    tokio::fs::create_dir_all(&config.worktree.repos_dir).await?;
    tokio::fs::create_dir_all(&config.repos.home_dir).await?;
    eprintln!(
        "      Worktree base: {}",
        config.worktree.base_dir.display()
    );
    eprintln!("      Repos cache: {}", config.worktree.repos_dir.display());
    eprintln!("      Home dir: {}", config.repos.home_dir.display());

    // Auto-clone repositories if configured
    if !config.repos.auto_clone.is_empty() {
        eprintln!(
            "      Auto-cloning {} repositories...",
            config.repos.auto_clone.len()
        );
        for repo_entry in &config.repos.auto_clone {
            if let Err(e) = auto_clone_repo(repo_entry, &config.repos.home_dir).await {
                eprintln!("      WARNING: Failed to clone {}: {}", repo_entry.url(), e);
            }
        }
    }

    // Create channels for communication
    let (command_tx, mut command_rx) = mpsc::channel::<DaemonCommand>(64);

    // Get machine info
    let machine_id = get_machine_id();
    let hostname = get_hostname();
    eprintln!("      Machine ID: {}", machine_id);
    eprintln!("      Hostname: {}", hostname);

    // Create WebSocket client
    eprintln!("[5/5] Connecting to server: {}", config.server.url);
    let mut ws_client = WsClient::new(
        config.server.clone(),
        machine_id,
        hostname,
        config.process.max_concurrent_tasks as i32,
        command_tx,
    );

    // Get sender for task manager
    let ws_tx = ws_client.sender();

    // Create task configuration
    let bubblewrap_config = if config.process.bubblewrap.enabled {
        Some(config.process.bubblewrap.clone())
    } else {
        None
    };
    // Derive HTTP API URL from WebSocket server URL (wss://... -> https://...)
    let api_url = config
        .server
        .url
        .replace("wss://", "https://")
        .replace("ws://", "http://");
    let task_config = TaskConfig {
        max_concurrent_tasks: config.process.max_concurrent_tasks,
        worktree_base_dir: config.worktree.base_dir.clone(),
        env_vars: config.process.env_vars.clone(),
        claude_command: config.process.claude_command.clone(),
        claude_args: config.process.claude_args.clone(),
        claude_pre_args: config.process.claude_pre_args.clone(),
        enable_permissions: config.process.enable_permissions,
        disable_verbose: config.process.disable_verbose,
        bubblewrap: bubblewrap_config,
        api_url,
        api_key: config.server.api_key.clone(),
        heartbeat_commit_interval_secs: config.process.heartbeat_commit_interval_secs,
    };

    // Create task manager
    let task_manager = Arc::new(TaskManager::new(task_config, ws_tx.clone()));

    // Spawn command handler
    let task_manager_clone = task_manager.clone();
    tokio::spawn(async move {
        tracing::info!("Command handler started, waiting for commands...");
        while let Some(command) = command_rx.recv().await {
            tracing::info!("Received command from channel: {:?}", command);
            if let Err(e) = task_manager_clone.handle_command(command).await {
                tracing::error!("Failed to handle command: {}", e);
            }
        }
        tracing::info!("Command handler stopped");
    });

    // Handle shutdown signals
    let shutdown_signal = async {
        tokio::signal::ctrl_c()
            .await
            .expect("Failed to install Ctrl+C handler");
        eprintln!("\nReceived shutdown signal");
    };

    eprintln!("=== Daemon running (Ctrl+C to stop) ===");

    // Run WebSocket client with shutdown handling
    tokio::select! {
        result = ws_client.run() => {
            match result {
                Ok(()) => eprintln!("WebSocket client exited cleanly"),
                Err(DaemonError::AuthFailed(msg)) => {
                    eprintln!("ERROR: Authentication failed: {}", msg);
                    std::process::exit(1);
                }
                Err(e) => {
                    eprintln!("ERROR: WebSocket client error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        _ = shutdown_signal => {
            eprintln!("Shutting down...");
        }
    }

    // Gracefully shutdown all running Claude processes
    eprintln!("Terminating Claude processes...");
    task_manager
        .shutdown_all_processes(std::time::Duration::from_secs(5))
        .await;

    // Cleanup
    tracing::info!("Daemon stopped");

    Ok(())
}

/// Run supervisor commands.
async fn run_supervisor(
    cmd: SupervisorCommand,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use makima::daemon::api::supervisor::*;

    match cmd {
        SupervisorCommand::Tasks(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.supervisor_tasks(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Tree(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.supervisor_tree(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Spawn(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Creating task: {}...", args.name);
            let req = SpawnTaskRequest {
                name: args.name,
                plan: args.plan,
                contract_id: args.common.contract_id,
                parent_task_id: args.parent,
                checkpoint_sha: args.checkpoint,
            };
            let result = client.supervisor_spawn(req).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Wait(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!(
                "Waiting for task {} (timeout: {}s)...",
                args.task_id, args.timeout
            );
            let result = client.supervisor_wait(args.task_id, args.timeout).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::ReadFile(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client
                .supervisor_read_file(args.task_id, &args.file_path)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Branch(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Creating branch: {}...", args.name);
            let result = client.supervisor_branch(&args.name, args.from).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Merge(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Merging task {}...", args.task_id);
            let result = client
                .supervisor_merge(args.task_id, args.to, args.squash)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Pr(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Creating PR for task {}...", args.task_id);
            let body = args.body.as_deref().unwrap_or("");
            let result = client
                .supervisor_pr(args.task_id, &args.title, body, &args.base)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Diff(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client.supervisor_diff(args.task_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Checkpoint(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let task_id = args
                .common
                .self_task_id
                .ok_or("MAKIMA_TASK_ID is required for checkpoint")?;
            let result = client
                .supervisor_checkpoint(task_id, &args.message)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Checkpoints(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let task_id = args.self_task_id.ok_or("MAKIMA_TASK_ID is required")?;
            let result = client.supervisor_checkpoints(task_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Status(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.supervisor_status(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Ask(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Asking user: {}...", args.question);
            let choices = args
                .choices
                .map(|c| c.split(',').map(|s| s.trim().to_string()).collect())
                .unwrap_or_default();
            let result = client
                .supervisor_ask(&args.question, choices, args.context, args.timeout, args.phaseguard, args.multi_select, args.non_blocking, args.question_type)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::AdvancePhase(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Advancing contract to phase: {}...", args.phase);
            let result = client
                .supervisor_advance_phase(args.common.contract_id, &args.phase)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Task(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client.supervisor_get_task(args.target_task_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::Output(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client.supervisor_get_task_output(args.target_task_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        SupervisorCommand::TaskHistory(args) => {
            eprintln!(
                "Task history for {} (limit: {:?}, format: {})",
                args.task_id, args.limit, args.format
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!("  GET /api/v1/mesh/tasks/{}/conversation", args.task_id);
        }
        SupervisorCommand::TaskCheckpoints(args) => {
            eprintln!(
                "Task checkpoints for {} (with_diff: {})",
                args.task_id, args.with_diff
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!("  GET /api/v1/mesh/tasks/{}/checkpoints", args.task_id);
        }
        SupervisorCommand::Resume(args) => {
            eprintln!(
                "Resume supervisor for contract {} (mode: {}, checkpoint: {:?})",
                args.common.contract_id, args.mode, args.checkpoint
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!(
                "  POST /api/v1/contracts/{}/supervisor/resume",
                args.common.contract_id
            );
        }
        SupervisorCommand::TaskResumeFrom(args) => {
            eprintln!(
                "Resume task {} from checkpoint {} with plan: {}",
                args.task_id, args.checkpoint, args.plan
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!(
                "  POST /api/v1/mesh/tasks/{}/checkpoints/{}/resume",
                args.task_id, args.checkpoint
            );
        }
        SupervisorCommand::TaskRewind(args) => {
            eprintln!(
                "Rewind task {} to checkpoint {} (preserve: {}, branch: {:?})",
                args.task_id, args.checkpoint, args.preserve, args.branch_name
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!("  POST /api/v1/mesh/tasks/{}/rewind", args.task_id);
        }
        SupervisorCommand::TaskFork(args) => {
            eprintln!(
                "Fork task {} from checkpoint {} as '{}' with plan: {}",
                args.task_id, args.checkpoint, args.name, args.plan
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!("  POST /api/v1/mesh/tasks/{}/fork", args.task_id);
        }
        SupervisorCommand::RewindConversation(args) => {
            eprintln!(
                "Rewind conversation for contract {} (by: {:?}, to: {:?}, rewind_code: {})",
                args.common.contract_id, args.by_messages, args.to_message, args.rewind_code
            );
            eprintln!("CLI integration not yet implemented. Use the API directly:");
            eprintln!(
                "  POST /api/v1/contracts/{}/supervisor/conversation/rewind",
                args.common.contract_id
            );
        }
        SupervisorCommand::Complete(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            eprintln!("Marking contract {} as complete...", args.common.contract_id);
            match client.supervisor_complete(args.common.contract_id).await {
                Ok(_) => {
                    println!(r#"{{"success": true, "message": "Contract marked as complete"}}"#);
                }
                Err(e) => {
                    eprintln!("Error: {}", e);
                    println!(r#"{{"success": false, "error": "{}"}}"#, e);
                    std::process::exit(1);
                }
            }
        }
        SupervisorCommand::ResumeContract(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            eprintln!("Resuming contract {}...", args.contract_id);
            let result = client.supervisor_resume_contract(args.contract_id).await?;
            println!("{}", serde_json::to_string(&serde_json::json!({
                "success": true,
                "message": "Contract resumed",
                "contract": result.0
            }))?);
        }
    }

    Ok(())
}

/// Run contract commands.
async fn run_contract(
    cmd: ContractCommand,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match cmd {
        ContractCommand::Status(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.contract_status(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::Checklist(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.contract_checklist(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::Goals(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.contract_goals(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::Files(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.contract_files(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::File(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client
                .contract_file(args.common.contract_id, args.file_id)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::Report(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let result = client
                .contract_report(args.common.contract_id, &args.message, args.common.task_id)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::SuggestAction(args) => {
            let client = ApiClient::new(args.api_url, args.api_key)?;
            let result = client.contract_suggest_action(args.contract_id).await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::CompletionAction(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            let files = args.files.map(|f| {
                f.split(',')
                    .map(|s| s.trim().to_string())
                    .collect::<Vec<_>>()
            });
            let result = client
                .contract_completion_action(
                    args.common.contract_id,
                    args.common.task_id,
                    files,
                    args.lines_added,
                    args.lines_removed,
                    args.code,
                )
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::UpdateFile(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            // Read content from stdin
            let mut content = String::new();
            io::stdin().read_to_string(&mut content)?;
            let result = client
                .contract_update_file(args.common.contract_id, args.file_id, &content)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
        ContractCommand::CreateFile(args) => {
            let client = ApiClient::new(args.common.api_url, args.common.api_key)?;
            // Read content from stdin
            let mut content = String::new();
            io::stdin().read_to_string(&mut content)?;
            let result = client
                .contract_create_file(args.common.contract_id, &args.name, &content)
                .await?;
            println!("{}", serde_json::to_string(&result.0)?);
        }
    }

    Ok(())
}

/// Run the TUI view command.
async fn run_view(args: ViewArgs) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Load CLI config for defaults
    let config = CliConfig::load();

    // Get API URL and key, preferring CLI args > env vars > config file
    // Filter out empty strings
    let api_url = args.api_url
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| config.get_api_url());
    let api_key = match args.api_key.filter(|s| !s.is_empty()) {
        Some(key) => key,
        None => config.get_api_key().ok_or_else(|| {
            eprintln!("Error: No API key provided.");
            eprintln!();
            eprintln!("Set your API key using one of these methods:");
            eprintln!("  1. Run: makima config set-key YOUR_API_KEY");
            eprintln!("  2. Set environment variable: export MAKIMA_API_KEY=YOUR_API_KEY");
            eprintln!("  3. Pass via CLI: makima view --api-key YOUR_API_KEY");
            "No API key configured"
        })?,
    };

    // Create API client
    let client = ApiClient::new(api_url.clone(), api_key.clone())?;

    // Start WebSocket client for task output streaming
    let ws_client = TuiWsClient::start(api_url, api_key);

    // Start at contracts view
    let mut app = App::new(ViewType::Contracts);

    // Set initial search query if provided
    if let Some(ref query) = args.query {
        app.search_query = query.clone();
    }

    // Load initial contracts
    let items = load_contracts(&client).await?;
    app.set_items(items);

    // Run TUI with navigation support
    let result = run_tui_with_navigation(app, client, ws_client).await;

    result
}

/// Run config commands.
async fn run_config(cmd: ConfigCommand) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match cmd {
        ConfigCommand::SetKey(args) => {
            let mut config = CliConfig::load();
            config.api_key = Some(args.api_key);
            config.save()?;
            println!("API key saved to {:?}", CliConfig::config_path().unwrap_or_default());
            Ok(())
        }
        ConfigCommand::SetUrl(args) => {
            let mut config = CliConfig::load();
            config.api_url = args.api_url;
            config.save()?;
            println!("API URL saved to {:?}", CliConfig::config_path().unwrap_or_default());
            Ok(())
        }
        ConfigCommand::Show => {
            let config = CliConfig::load();
            println!("Configuration:");
            println!("  API URL: {}", config.api_url);
            println!("  API Key: {}", config.api_key.as_ref().map(|k| {
                if k.len() > 10 {
                    format!("{}...{}", &k[..6], &k[k.len()-4..])
                } else {
                    "***".to_string()
                }
            }).unwrap_or_else(|| "(not set)".to_string()));
            println!();
            println!("Config file: {:?}", CliConfig::config_path().unwrap_or_default());
            Ok(())
        }
        ConfigCommand::Path => {
            if let Some(path) = CliConfig::config_path() {
                println!("{}", path.display());
            } else {
                eprintln!("Could not determine config path");
            }
            Ok(())
        }
    }
}

/// Load contracts from API
async fn load_contracts(client: &ApiClient) -> Result<Vec<ListItem>, Box<dyn std::error::Error + Send + Sync>> {
    let result = client.list_contracts().await?;
    let items = result.0.get("contracts")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(ListItem::from_contract).collect())
        .unwrap_or_default();
    Ok(items)
}

/// Load tasks for a contract from API
async fn load_tasks(client: &ApiClient, contract_id: uuid::Uuid) -> Result<Vec<ListItem>, Box<dyn std::error::Error + Send + Sync>> {
    // Use get_contract which returns tasks as part of the response (works with regular API key auth)
    let result = client.get_contract(contract_id).await?;
    let mut items: Vec<ListItem> = result.0.get("tasks")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(ListItem::from_task).collect())
        .unwrap_or_default();

    // Sort tasks: supervisor first, then by status (running first), then by name
    items.sort_by(|a, b| {
        // Check if task is supervisor (role field in extra data)
        let a_is_supervisor = a.extra.get("role")
            .and_then(|v| v.as_str())
            .map(|s| s == "supervisor")
            .unwrap_or(false);
        let b_is_supervisor = b.extra.get("role")
            .and_then(|v| v.as_str())
            .map(|s| s == "supervisor")
            .unwrap_or(false);

        // Supervisor first
        match (a_is_supervisor, b_is_supervisor) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => {
                // Then by status: running/working tasks first
                let status_order = |s: Option<&String>| -> i32 {
                    match s.map(|x| x.as_str()) {
                        Some("running") | Some("working") => 0,
                        Some("pending") | Some("queued") => 1,
                        Some("completed") | Some("done") => 2,
                        Some("failed") | Some("error") => 3,
                        _ => 4,
                    }
                };
                let a_order = status_order(a.status.as_ref());
                let b_order = status_order(b.status.as_ref());

                match a_order.cmp(&b_order) {
                    std::cmp::Ordering::Equal => a.name.cmp(&b.name),
                    other => other,
                }
            }
        }
    });

    Ok(items)
}

/// Run the TUI with navigation support for drill-down views
async fn run_tui_with_navigation(
    mut app: App,
    client: ApiClient,
    ws_client: TuiWsClient,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use crossterm::{
        event::{DisableMouseCapture, EnableMouseCapture},
        execute,
        terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
    };
    use ratatui::backend::CrosstermBackend;
    use std::io;

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen, EnableMouseCapture)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = ratatui::Terminal::new(backend)?;

    let result = run_tui_loop(&mut terminal, &mut app, &client, &ws_client).await;

    // Cleanup WebSocket
    ws_client.shutdown();

    // Cleanup terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    match result {
        Ok(Some(path)) => {
            // Output the path for shell integration
            tui::print_path(&path);
        }
        Ok(None) => {
            // Normal exit
        }
        Err(e) => {
            eprintln!("TUI error: {}", e);
            std::process::exit(1);
        }
    }

    Ok(())
}

/// Main TUI event loop with async data loading
async fn run_tui_loop(
    terminal: &mut ratatui::Terminal<ratatui::backend::CrosstermBackend<std::io::Stdout>>,
    app: &mut App,
    client: &ApiClient,
    ws_client: &TuiWsClient,
) -> Result<Option<String>, Box<dyn std::error::Error + Send + Sync>> {
    use crossterm::event::{self, Event};
    use std::time::Duration;

    // Track currently subscribed task for cleanup
    let mut subscribed_task_id: Option<uuid::Uuid> = None;

    loop {
        terminal.draw(|f| tui::ui::render(f, app))?;

        // Process WebSocket events (non-blocking)
        while let Some(ws_event) = ws_client.try_recv() {
            handle_ws_event(app, ws_event);
        }

        // Poll for keyboard events with short timeout (50ms for responsive WS handling)
        if event::poll(Duration::from_millis(50))? {
            if let Event::Key(key) = event::read()? {
                let action = tui::event::handle_key_event(app, key);
                match action {
                    Action::Quit => break,
                    Action::OutputPath(path) => return Ok(Some(path)),
                    Action::None => {}
                    _ => {
                        let result = app.handle_action(action);
                        match result {
                            Action::OutputPath(path) => return Ok(Some(path)),
                            Action::LoadTasks { contract_id, contract_name: _ } => {
                                // Unsubscribe from any previous task
                                if let Some(task_id) = subscribed_task_id.take() {
                                    ws_client.unsubscribe(task_id);
                                }
                                // Load tasks for the selected contract
                                match load_tasks(client, contract_id).await {
                                    Ok(items) => {
                                        app.set_items(items);
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Failed to load tasks: {}", e));
                                    }
                                }
                            }
                            Action::LoadTaskOutput { task_id, task_name: _ } => {
                                // Clear previous output
                                app.output_buffer.clear();
                                app.ws_state = WsConnectionState::Connecting;

                                // Unsubscribe from previous task if any
                                if let Some(old_task_id) = subscribed_task_id.take() {
                                    ws_client.unsubscribe(old_task_id);
                                }

                                // Load task output history first
                                app.status_message = Some("Loading output history...".to_string());
                                match client.get_task_output(task_id).await {
                                    Ok(result) => {
                                        // Parse the entries array from response
                                        if let Some(entries) = result.0.get("entries").and_then(|v| v.as_array()) {
                                            for entry in entries {
                                                if let Some(line) = parse_output_entry(entry) {
                                                    app.output_buffer.add_line(line);
                                                }
                                            }
                                            let count = entries.len();
                                            app.status_message = Some(format!("Loaded {} history entries, streaming live...", count));
                                        }
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Failed to load history: {}", e));
                                    }
                                }

                                // Subscribe to new task output for live updates
                                ws_client.subscribe(task_id);
                                subscribed_task_id = Some(task_id);
                            }
                            Action::PerformDelete { id, item_type } => {
                                // Perform the delete API call
                                let delete_result = match item_type {
                                    ViewType::Contracts => {
                                        client.delete_contract(id).await
                                    }
                                    ViewType::Tasks => {
                                        client.delete_task(id).await
                                    }
                                    ViewType::TaskOutput => {
                                        // Can't delete from output view
                                        Ok(())
                                    }
                                };

                                match delete_result {
                                    Ok(()) => {
                                        app.status_message = Some("Deleted successfully".to_string());
                                        // Remove item from list
                                        app.items.retain(|item| item.id != id);
                                        app.update_filtered_items();
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Delete failed: {}", e));
                                    }
                                }
                            }
                            Action::PerformUpdate { id, item_type, name, description } => {
                                // Perform the update API call
                                let update_result = match item_type {
                                    ViewType::Contracts => {
                                        client.update_contract(id, Some(name.clone()), Some(description.clone())).await.map(|_| ())
                                    }
                                    ViewType::Tasks => {
                                        // For tasks, description is the plan
                                        client.update_task(id, Some(name.clone()), Some(description.clone())).await.map(|_| ())
                                    }
                                    ViewType::TaskOutput => {
                                        // Can't edit from output view
                                        Ok(())
                                    }
                                };

                                match update_result {
                                    Ok(()) => {
                                        app.status_message = Some("Updated successfully".to_string());
                                        // Update item in list
                                        for item in &mut app.items {
                                            if item.id == id {
                                                item.name = name.clone();
                                                item.description = Some(description.clone());
                                                break;
                                            }
                                        }
                                        app.update_filtered_items();
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Update failed: {}", e));
                                    }
                                }
                            }
                            Action::Refresh => {
                                // Reload data for current view
                                match app.view_type {
                                    ViewType::Contracts => {
                                        // Unsubscribe from task when going back to contracts
                                        if let Some(task_id) = subscribed_task_id.take() {
                                            ws_client.unsubscribe(task_id);
                                        }
                                        match load_contracts(client).await {
                                            Ok(items) => app.set_items(items),
                                            Err(e) => app.status_message = Some(format!("Refresh failed: {}", e)),
                                        }
                                    }
                                    ViewType::Tasks => {
                                        // Unsubscribe from task when going back to tasks
                                        if let Some(task_id) = subscribed_task_id.take() {
                                            ws_client.unsubscribe(task_id);
                                        }
                                        if let Some(contract_id) = app.contract_id {
                                            match load_tasks(client, contract_id).await {
                                                Ok(items) => app.set_items(items),
                                                Err(e) => app.status_message = Some(format!("Refresh failed: {}", e)),
                                            }
                                        }
                                    }
                                    ViewType::TaskOutput => {
                                        // Re-subscribe to the task output
                                        if let Some(task_id) = app.task_id {
                                            app.output_buffer.clear();
                                            app.ws_state = WsConnectionState::Connecting;
                                            ws_client.subscribe(task_id);
                                            subscribed_task_id = Some(task_id);
                                            app.status_message = Some("Reconnecting...".to_string());
                                        }
                                    }
                                }
                            }
                            Action::GoBack => {
                                // Unsubscribe when going back from output view
                                if let Some(task_id) = subscribed_task_id.take() {
                                    ws_client.unsubscribe(task_id);
                                    app.ws_state = WsConnectionState::Disconnected;
                                }
                            }
                            Action::PerformCreateContract { name, description, contract_type, repository_url } => {
                                // Create the contract via API
                                let req = CreateContractRequest {
                                    name: name.clone(),
                                    description: if description.is_empty() { None } else { Some(description) },
                                    contract_type: Some(contract_type),
                                    initial_phase: None,
                                    autonomous_loop: None,
                                    phase_guard: None,
                                };

                                match client.create_contract(req).await {
                                    Ok(result) => {
                                        let contract_name = result.0.get("name")
                                            .and_then(|v| v.as_str())
                                            .unwrap_or(&name)
                                            .to_string();
                                        let contract_id = result.0.get("id")
                                            .and_then(|v| v.as_str())
                                            .and_then(|s| uuid::Uuid::parse_str(s).ok());

                                        // Add repository if provided
                                        if let (Some(repo_url), Some(cid)) = (repository_url.as_ref(), contract_id) {
                                            if !repo_url.is_empty() {
                                                // Extract repo name from URL (e.g., "owner/repo" from GitHub URL)
                                                let repo_name = extract_repo_name(repo_url);
                                                match client.add_remote_repository(cid, &repo_name, repo_url, true).await {
                                                    Ok(_) => {
                                                        app.status_message = Some(format!(
                                                            "Created contract '{}' with repository",
                                                            contract_name
                                                        ));
                                                    }
                                                    Err(e) => {
                                                        app.status_message = Some(format!(
                                                            "Created contract but failed to add repository: {}",
                                                            e
                                                        ));
                                                    }
                                                }
                                            } else {
                                                app.status_message = Some(format!("Created contract: {}", contract_name));
                                            }
                                        } else {
                                            app.status_message = Some(format!("Created contract: {}", contract_name));
                                        }

                                        // Refresh the contracts list
                                        match load_contracts(client).await {
                                            Ok(items) => app.set_items(items),
                                            Err(e) => {
                                                let msg = app.status_message.take().unwrap_or_default();
                                                app.status_message = Some(format!("{} (refresh failed: {})", msg, e));
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Create failed: {}", e));
                                    }
                                }
                            }
                            Action::LoadRepoSuggestions => {
                                // Load repository suggestions for the create form
                                app.status_message = Some("Loading recent repositories...".to_string());
                                // Force a redraw to show the status
                                terminal.draw(|f| tui::ui::render(f, app)).ok();

                                // Fetch all repository types (remote and local)
                                match client.get_repository_suggestions(None, Some(10)).await {
                                    Ok(result) => {
                                        // Parse suggestions from API response
                                        let suggestions: Vec<RepositorySuggestion> = result.0
                                            .get("entries")
                                            .and_then(|v| v.as_array())
                                            .map(|arr| {
                                                arr.iter().filter_map(|entry| {
                                                    let name = entry.get("name")
                                                        .and_then(|v| v.as_str())
                                                        .unwrap_or("")
                                                        .to_string();
                                                    let repository_url = entry.get("repositoryUrl")
                                                        .or_else(|| entry.get("repository_url"))
                                                        .and_then(|v| v.as_str())
                                                        .map(|s| s.to_string());
                                                    let local_path = entry.get("localPath")
                                                        .or_else(|| entry.get("local_path"))
                                                        .and_then(|v| v.as_str())
                                                        .map(|s| s.to_string());
                                                    let source_type = entry.get("sourceType")
                                                        .or_else(|| entry.get("source_type"))
                                                        .and_then(|v| v.as_str())
                                                        .unwrap_or("remote")
                                                        .to_string();
                                                    let use_count = entry.get("useCount")
                                                        .or_else(|| entry.get("use_count"))
                                                        .and_then(|v| v.as_i64())
                                                        .unwrap_or(0) as i32;

                                                    // Only include if we have a URL or path
                                                    if repository_url.is_some() || local_path.is_some() {
                                                        Some(RepositorySuggestion {
                                                            name,
                                                            repository_url,
                                                            local_path,
                                                            source_type,
                                                            use_count,
                                                        })
                                                    } else {
                                                        None
                                                    }
                                                }).collect()
                                            })
                                            .unwrap_or_default();

                                        let count = suggestions.len();
                                        app.create_state.set_suggestions(suggestions);
                                        if count > 0 {
                                            app.status_message = Some(format!("Found {} recent repositories", count));
                                        } else {
                                            app.status_message = Some("No recent repositories found".to_string());
                                        }
                                    }
                                    Err(e) => {
                                        app.status_message = Some(format!("Could not load suggestions: {}", e));
                                        app.create_state.suggestions_loaded = true;
                                    }
                                }
                            }
                            _ => {}
                        }
                    }
                }
            }
        }

        if app.should_quit {
            break;
        }
    }

    Ok(None)
}

/// Extract a repository name from a URL.
/// E.g., "https://github.com/owner/repo.git" -> "owner/repo"
fn extract_repo_name(url: &str) -> String {
    // Remove .git suffix if present
    let url = url.trim_end_matches(".git");

    // Try to extract owner/repo from common Git hosting URLs
    if let Some(path) = url.strip_prefix("https://github.com/")
        .or_else(|| url.strip_prefix("https://gitlab.com/"))
        .or_else(|| url.strip_prefix("https://bitbucket.org/"))
        .or_else(|| url.strip_prefix("git@github.com:"))
        .or_else(|| url.strip_prefix("git@gitlab.com:"))
        .or_else(|| url.strip_prefix("git@bitbucket.org:"))
    {
        // Return owner/repo
        return path.to_string();
    }

    // Fallback: try to get the last path segment
    if let Some(last_segment) = url.rsplit('/').next() {
        if !last_segment.is_empty() {
            return last_segment.to_string();
        }
    }

    // Last resort: use the full URL as the name
    url.to_string()
}

/// Parse an output entry from the API response into an OutputLine
fn parse_output_entry(entry: &serde_json::Value) -> Option<OutputLine> {
    let message_type = entry.get("messageType")
        .and_then(|v| v.as_str())
        .unwrap_or("raw");
    let content = entry.get("content")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let tool_name = entry.get("toolName")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let is_error = entry.get("isError")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let cost_usd = entry.get("costUsd")
        .and_then(|v| v.as_f64());
    let duration_ms = entry.get("durationMs")
        .and_then(|v| v.as_u64());

    Some(OutputLine {
        message_type: OutputMessageType::from_str(message_type),
        content,
        tool_name,
        is_error,
        cost_usd,
        duration_ms,
    })
}

/// Handle a WebSocket event and update app state
fn handle_ws_event(app: &mut App, event: WsEvent) {
    match event {
        WsEvent::Connected => {
            app.ws_state = WsConnectionState::Connected;
            app.status_message = Some("Connected".to_string());
        }
        WsEvent::Disconnected => {
            app.ws_state = WsConnectionState::Disconnected;
            app.status_message = Some("Disconnected".to_string());
        }
        WsEvent::Reconnecting { attempt } => {
            app.ws_state = WsConnectionState::Reconnecting;
            app.status_message = Some(format!("Reconnecting (attempt {})...", attempt));
        }
        WsEvent::Subscribed { task_id: _ } => {
            app.ws_state = WsConnectionState::Connected;
            app.status_message = Some("Subscribed to task output".to_string());
        }
        WsEvent::Unsubscribed { task_id: _ } => {
            // No status update needed
        }
        WsEvent::TaskOutput(output) => {
            // Convert WebSocket event to OutputLine
            let line = OutputLine {
                message_type: OutputMessageType::from_str(&output.message_type),
                content: output.content,
                tool_name: output.tool_name,
                is_error: output.is_error.unwrap_or(false),
                cost_usd: output.cost_usd,
                duration_ms: output.duration_ms,
            };
            app.output_buffer.add_line(line);
            // Clear status message once we're receiving output
            if app.status_message.as_ref().map(|s| s.contains("Subscribed")).unwrap_or(false) {
                app.status_message = None;
            }
        }
        WsEvent::Error { message } => {
            app.status_message = Some(format!("WS Error: {}", message));
        }
    }
}

fn init_logging(level: &str, format: &str) {
    let filter = EnvFilter::try_from_default_env()
        .or_else(|_| EnvFilter::try_new(level))
        .unwrap_or_else(|_| EnvFilter::new("info"));

    let subscriber = tracing_subscriber::registry().with(filter);

    if format == "json" {
        subscriber.with(fmt::layer().json()).init();
    } else {
        subscriber.with(fmt::layer()).init();
    }
}

fn get_machine_id() -> String {
    // Try to read machine-id from standard locations
    #[cfg(target_os = "linux")]
    {
        if let Ok(id) = std::fs::read_to_string("/etc/machine-id") {
            return id.trim().to_string();
        }
        if let Ok(id) = std::fs::read_to_string("/var/lib/dbus/machine-id") {
            return id.trim().to_string();
        }
    }

    #[cfg(target_os = "macos")]
    {
        // Use IOPlatformSerialNumber
        if let Ok(output) = std::process::Command::new("ioreg")
            .args(["-rd1", "-c", "IOPlatformExpertDevice"])
            .output()
        {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines() {
                if line.contains("IOPlatformUUID") {
                    if let Some(uuid) = line.split('"').nth(3) {
                        return uuid.to_string();
                    }
                }
            }
        }
    }

    // Fallback: generate a random ID and persist it
    let state_dir = dirs_next::data_local_dir()
        .unwrap_or_else(|| std::path::PathBuf::from("."))
        .join("makima");
    let machine_id_file = state_dir.join("machine-id");

    if let Ok(id) = std::fs::read_to_string(&machine_id_file) {
        return id.trim().to_string();
    }

    // Generate new ID
    let new_id = uuid::Uuid::new_v4().to_string();
    std::fs::create_dir_all(&state_dir).ok();
    std::fs::write(&machine_id_file, &new_id).ok();
    new_id
}

fn get_hostname() -> String {
    hostname::get()
        .map(|h| h.to_string_lossy().to_string())
        .unwrap_or_else(|_| "unknown".to_string())
}

/// Auto-clone a repository to the home directory if it doesn't exist.
async fn auto_clone_repo(
    repo_entry: &RepoEntry,
    home_dir: &Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let dir_name = repo_entry
        .dir_name()
        .ok_or("Could not determine directory name from URL")?;
    let target_dir = home_dir.join(&dir_name);

    // Check if already cloned
    if target_dir.exists() {
        eprintln!("      [skip] {} (already exists)", dir_name);
        return Ok(());
    }

    let url = repo_entry.expanded_url();
    eprintln!("      [clone] {} -> {}", url, target_dir.display());

    // Build git clone command
    let mut args = vec!["clone".to_string()];

    // Add shallow clone if requested
    if repo_entry.shallow() {
        args.push("--depth".to_string());
        args.push("1".to_string());
    }

    // Add branch if specified
    if let Some(branch) = repo_entry.branch() {
        args.push("--branch".to_string());
        args.push(branch.to_string());
    }

    args.push(url.clone());
    args.push(target_dir.to_string_lossy().to_string());

    // Run git clone
    let output = Command::new("git").args(&args).output().await?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("git clone failed: {}", stderr).into());
    }

    eprintln!("      [done] {}", dir_name);
    Ok(())
}

/// dirs_next minimal replacement
mod dirs_next {
    use std::path::PathBuf;

    pub fn data_local_dir() -> Option<PathBuf> {
        #[cfg(target_os = "macos")]
        {
            std::env::var("HOME")
                .ok()
                .map(|h| PathBuf::from(h).join("Library").join("Application Support"))
        }
        #[cfg(target_os = "linux")]
        {
            std::env::var("XDG_DATA_HOME")
                .ok()
                .map(PathBuf::from)
                .or_else(|| {
                    std::env::var("HOME")
                        .ok()
                        .map(|h| PathBuf::from(h).join(".local").join("share"))
                })
        }
        #[cfg(target_os = "windows")]
        {
            std::env::var("LOCALAPPDATA").ok().map(PathBuf::from)
        }
        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
        {
            None
        }
    }
}