heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
Documentation
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
//! heroforge-core - Interactive Rhai shell for Fossil repositories
//!
//! Provides a readline-style interface with:
//! - Tab completion for all functions
//! - Command history
//! - Syntax highlighting
//! - Help hints
//! - Daemon mode for faster script execution

use colored::Colorize;
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::highlight::Highlighter;
use rustyline::hint::{Hinter, HistoryHinter};
use rustyline::history::DefaultHistory;
use rustyline::validate::Validator;
use rustyline::{Config, Context, Editor, Helper};
use std::borrow::Cow;
use std::env;
use std::fs;
use std::io::{self, BufRead};
use std::path::PathBuf;
use std::process::{Command, exit};
use std::time::Duration;

use heroforge_core::rhai_api::{ForgeEngine, SocketClient, SocketServer};

/// Repository functions with their signatures and descriptions
const REPO_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("repo_open(path)", "Repository", "Open repository read-only"),
    (
        "repo_open_rw(path)",
        "Repository",
        "Open repository read-write",
    ),
    ("repo_init(path)", "Repository", "Create new repository"),
    ("repo_rebuild(repo)", "void", "Rebuild repository metadata"),
    ("repo_project_name(repo)", "string", "Get project name"),
    ("repo_project_code(repo)", "string", "Get project code"),
];

/// Filesystem functions
const FS_FUNCTIONS: &[(&str, &str, &str)] = &[
    (
        "fs_new(repo, author)",
        "FsHandle",
        "Create filesystem interface",
    ),
    ("fs_read(fs, path)", "string", "Read file as string"),
    ("fs_write(fs, path, content)", "void", "Write file"),
    ("fs_delete(fs, path)", "void", "Delete file"),
    ("fs_exists(fs, path)", "bool", "Check if file exists"),
    ("fs_list(fs, dir)", "array", "List directory contents"),
    ("fs_commit(fs)", "string", "Force commit changes"),
    ("fs_status(fs)", "string", "Get filesystem status"),
];

/// File operations
const FILE_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("files_list(repo)", "array", "List files on trunk"),
    (
        "files_list_branch(repo, branch)",
        "array",
        "List files on branch",
    ),
    ("files_read(repo, path)", "string", "Read file from trunk"),
    (
        "files_read_branch(repo, path, branch)",
        "string",
        "Read file from branch",
    ),
    (
        "files_find(repo, pattern)",
        "array",
        "Find files by pattern",
    ),
];

/// Branch and tag functions
const BRANCH_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("branches_list(repo)", "array", "List all branches"),
    (
        "branches_create(repo, name, parent)",
        "string",
        "Create new branch",
    ),
    ("tags_list(repo)", "array", "List all tags"),
    (
        "tags_create(repo, name, target)",
        "string",
        "Create new tag",
    ),
    ("history_recent(repo, limit)", "array", "Get recent commits"),
];

/// Modify builder functions
const MODIFY_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("modify_new(repo)", "Modify", "Create modify builder"),
    ("modify_copy(m, src, dst)", "Modify", "Copy file"),
    ("modify_move(m, src, dst)", "Modify", "Move file"),
    ("modify_delete(m, path)", "Modify", "Delete file"),
    (
        "modify_execute(m, author, msg)",
        "string",
        "Execute modifications",
    ),
];

/// Find builder functions
const FIND_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("find_new(repo)", "Find", "Create find builder"),
    ("find_name(f, pattern)", "Find", "Filter by name pattern"),
    ("find_extension(f, ext)", "Find", "Filter by extension"),
    ("find_dir(f, path)", "Find", "Filter by directory"),
    ("find_execute(f)", "array", "Execute find"),
];

/// Utility functions
const UTILITY_FUNCTIONS: &[(&str, &str, &str)] = &[
    ("print(msg)", "void", "Print message"),
    ("debug(msg)", "void", "Print debug message"),
    ("sleep(ms)", "void", "Sleep for milliseconds"),
    ("env(name)", "string", "Get environment variable"),
    ("cwd()", "string", "Get current directory"),
    ("home()", "string", "Get home directory"),
    ("uuid()", "string", "Generate UUID"),
    ("timestamp()", "i64", "Get Unix timestamp"),
    ("version()", "string", "Get heroforge-core version"),
];

/// REPL commands
const REPL_COMMANDS: &[(&str, &str)] = &[
    ("/help", "Show this help"),
    ("/functions", "List all available functions"),
    ("/repo", "Show repository functions"),
    ("/fs", "Show filesystem functions"),
    ("/files", "Show file functions"),
    ("/branches", "Show branch/tag functions"),
    ("/modify", "Show modify builder functions"),
    ("/find", "Show find builder functions"),
    ("/utils", "Show utility functions"),
    ("/scope", "Show current scope variables"),
    ("/clear", "Clear screen"),
    ("/load <file>", "Load and execute a .rhai script"),
    ("/quit", "Exit REPL (or Ctrl+D)"),
];

/// Rhai keywords for syntax highlighting
const RHAI_KEYWORDS: &[&str] = &[
    "let", "const", "if", "else", "while", "loop", "for", "in", "break", "continue", "return",
    "throw", "try", "catch", "fn", "private", "import", "export", "as", "true", "false", "null",
];

/// Helper struct for rustyline
#[derive(Helper)]
struct ReplHelper {
    hinter: HistoryHinter,
}

impl Completer for ReplHelper {
    type Candidate = Pair;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &Context<'_>,
    ) -> rustyline::Result<(usize, Vec<Pair>)> {
        let mut completions = Vec::new();

        // Find the word being typed
        let line_to_cursor = &line[..pos];
        let word_start = line_to_cursor
            .rfind(|c: char| !c.is_alphanumeric() && c != '_')
            .map(|i| i + 1)
            .unwrap_or(0);
        let word = &line_to_cursor[word_start..];

        if word.is_empty() {
            return Ok((pos, completions));
        }

        // Check for REPL commands
        if word.starts_with('/') {
            for (cmd, desc) in REPL_COMMANDS {
                let cmd_name = cmd.split_whitespace().next().unwrap_or(cmd);
                if cmd_name.starts_with(word) {
                    completions.push(Pair {
                        display: format!("{} - {}", cmd, desc),
                        replacement: cmd_name.to_string(),
                    });
                }
            }
            return Ok((word_start, completions));
        }

        // Complete all function categories
        let all_functions: Vec<&(&str, &str, &str)> = REPO_FUNCTIONS
            .iter()
            .chain(FS_FUNCTIONS.iter())
            .chain(FILE_FUNCTIONS.iter())
            .chain(BRANCH_FUNCTIONS.iter())
            .chain(MODIFY_FUNCTIONS.iter())
            .chain(FIND_FUNCTIONS.iter())
            .chain(UTILITY_FUNCTIONS.iter())
            .collect();

        for (func, ret, desc) in all_functions {
            let func_name = func.split('(').next().unwrap_or(func);
            if func_name.starts_with(word) {
                completions.push(Pair {
                    display: format!("{} -> {} - {}", func, ret, desc),
                    replacement: func_name.to_string(),
                });
            }
        }

        // Complete Rhai keywords
        for kw in RHAI_KEYWORDS {
            if kw.starts_with(word) && !completions.iter().any(|p| p.replacement == *kw) {
                completions.push(Pair {
                    display: format!("{} (keyword)", kw),
                    replacement: kw.to_string(),
                });
            }
        }

        Ok((word_start, completions))
    }
}

impl Hinter for ReplHelper {
    type Hint = String;

    fn hint(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Option<String> {
        // First try history hints
        if let Some(hint) = self.hinter.hint(line, pos, ctx) {
            return Some(hint);
        }

        // Then try function signature hints
        let line_to_cursor = &line[..pos];

        let all_functions: Vec<&(&str, &str, &str)> = REPO_FUNCTIONS
            .iter()
            .chain(FS_FUNCTIONS.iter())
            .chain(FILE_FUNCTIONS.iter())
            .chain(BRANCH_FUNCTIONS.iter())
            .chain(MODIFY_FUNCTIONS.iter())
            .chain(FIND_FUNCTIONS.iter())
            .chain(UTILITY_FUNCTIONS.iter())
            .collect();

        for (func, ret, desc) in all_functions {
            let func_name = func.split('(').next().unwrap_or(func);
            if line_to_cursor.ends_with(func_name) {
                let signature = &func[func_name.len()..];
                return Some(
                    format!("{} -> {} | {}", signature, ret, desc)
                        .dimmed()
                        .to_string(),
                );
            }
        }

        None
    }
}

impl Highlighter for ReplHelper {
    fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
        let mut result = String::with_capacity(line.len() * 2);
        let mut chars = line.chars().peekable();
        let mut current_word = String::new();

        while let Some(c) = chars.next() {
            if c.is_alphanumeric() || c == '_' {
                current_word.push(c);
            } else {
                if !current_word.is_empty() {
                    result.push_str(&highlight_word(&current_word));
                    current_word.clear();
                }
                // Highlight strings
                if c == '"' {
                    result.push_str(&format!("{}", "\"".green()));
                    let mut string_content = String::new();
                    while let Some(&next) = chars.peek() {
                        chars.next();
                        if next == '"' {
                            result.push_str(&format!("{}", string_content.green()));
                            result.push_str(&format!("{}", "\"".green()));
                            break;
                        } else if next == '\\' {
                            string_content.push(next);
                            if let Some(escaped) = chars.next() {
                                string_content.push(escaped);
                            }
                        } else {
                            string_content.push(next);
                        }
                    }
                }
                // Highlight comments
                else if c == '/' && chars.peek() == Some(&'/') {
                    result.push_str(&format!(
                        "{}",
                        format!("//{}", chars.collect::<String>()).dimmed()
                    ));
                    break;
                }
                // Highlight operators
                else if "=+-*/<>!&|".contains(c) {
                    result.push_str(&format!("{}", c.to_string().yellow()));
                }
                // Parentheses and brackets
                else if "()[]{}".contains(c) {
                    result.push_str(&format!("{}", c.to_string().cyan()));
                } else {
                    result.push(c);
                }
            }
        }

        if !current_word.is_empty() {
            result.push_str(&highlight_word(&current_word));
        }

        Cow::Owned(result)
    }

    fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
        &'s self,
        prompt: &'p str,
        _default: bool,
    ) -> Cow<'b, str> {
        Cow::Owned(format!("{}", prompt.cyan().bold()))
    }

    fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
        Cow::Owned(format!("{}", hint.dimmed()))
    }

    fn highlight_char(&self, _line: &str, _pos: usize, _forced: bool) -> bool {
        true
    }
}

/// Highlight a word based on its type
fn highlight_word(word: &str) -> String {
    // Rhai keywords
    if RHAI_KEYWORDS.contains(&word) {
        return format!("{}", word.magenta().bold());
    }

    // Collect all function names
    let all_func_names: Vec<&str> = REPO_FUNCTIONS
        .iter()
        .chain(FS_FUNCTIONS.iter())
        .chain(FILE_FUNCTIONS.iter())
        .chain(BRANCH_FUNCTIONS.iter())
        .chain(MODIFY_FUNCTIONS.iter())
        .chain(FIND_FUNCTIONS.iter())
        .chain(UTILITY_FUNCTIONS.iter())
        .map(|(f, _, _)| f.split('(').next().unwrap_or(f))
        .collect();

    if all_func_names.contains(&word) {
        return format!("{}", word.blue().bold());
    }

    // Numbers
    if word.chars().all(|c| c.is_numeric() || c == '.') {
        return format!("{}", word.yellow());
    }

    // Booleans
    if word == "true" || word == "false" {
        return format!("{}", word.yellow().bold());
    }

    word.to_string()
}

impl Validator for ReplHelper {}

/// Print the welcome banner
fn print_banner() {
    println!(
        "{}",
        "╔═══════════════════════════════════════════════════════════╗".cyan()
    );
    println!(
        "{}",
        "║           Heroforge Core Interactive Shell                ║".cyan()
    );
    println!(
        "{}",
        "╠═══════════════════════════════════════════════════════════╣".cyan()
    );
    println!(
        "{}  {}",
        "".cyan(),
        format!(
            "{:<56} {}",
            "Tab: completion | Up/Down: history | Ctrl+D: exit", ""
        )
        .cyan()
    );
    println!(
        "{}  {}",
        "".cyan(),
        format!(
            "{:<56} {}",
            "Type /help for commands, /functions for API", ""
        )
        .cyan()
    );
    println!(
        "{}",
        "╚═══════════════════════════════════════════════════════════╝".cyan()
    );
    println!();
}

/// Print help
fn print_help() {
    println!("{}", "REPL Commands:".yellow().bold());
    for (cmd, desc) in REPL_COMMANDS {
        println!("  {:15} {}", cmd.cyan(), desc);
    }
    println!();
    println!("{}", "Tips:".yellow().bold());
    println!("  - Press {} to autocomplete function names", "Tab".cyan());
    println!("  - Use {} arrows for command history", "Up/Down".cyan());
    println!(
        "  - Multi-line input: end lines with {} or use {}",
        "\\".cyan(),
        "{ }".cyan()
    );
}

/// Print all functions
fn print_functions() {
    print_category("Repository Functions", REPO_FUNCTIONS);
    println!();
    print_category("Filesystem Functions", FS_FUNCTIONS);
    println!();
    print_category("File Functions", FILE_FUNCTIONS);
    println!();
    print_category("Branch/Tag Functions", BRANCH_FUNCTIONS);
    println!();
    print_category("Modify Builder Functions", MODIFY_FUNCTIONS);
    println!();
    print_category("Find Builder Functions", FIND_FUNCTIONS);
    println!();
    print_category("Utility Functions", UTILITY_FUNCTIONS);
}

/// Print a category of functions
fn print_category(title: &str, functions: &[(&str, &str, &str)]) {
    println!("{}", format!("=== {} ===", title).yellow().bold());
    for (func, ret, desc) in functions {
        println!(
            "  {} {} {} {}",
            func.blue(),
            "->".dimmed(),
            ret.green(),
            format!("- {}", desc).dimmed()
        );
    }
}

/// Print current scope
fn print_scope(scope: &rhai::Scope) {
    if scope.is_empty() {
        println!("{}", "Scope is empty.".dimmed());
        return;
    }
    println!("{}", "Current scope:".yellow().bold());
    for (name, _constant, value) in scope.iter() {
        println!("  {} = {:?}", name.cyan(), value);
    }
}

/// Get the socket path from args or default
fn get_socket_path(args: &[String]) -> PathBuf {
    for i in 0..args.len() {
        if args[i] == "-s" && i + 1 < args.len() {
            return PathBuf::from(&args[i + 1]);
        }
    }
    heroforge_core::rhai_api::socket_server::default_socket_path()
}

/// Check if daemon is running
fn is_daemon_running(socket_path: &PathBuf) -> bool {
    socket_path.exists()
        && tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(heroforge_core::rhai_api::socket_server::ping(socket_path))
}

/// Wait for daemon to be ready
fn wait_for_daemon(socket_path: &PathBuf, timeout_secs: u64) -> bool {
    let start = std::time::Instant::now();
    let timeout = Duration::from_secs(timeout_secs);

    while start.elapsed() < timeout {
        if is_daemon_running(socket_path) {
            return true;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    false
}

/// Start the daemon in foreground
fn start_daemon_foreground(socket_path: PathBuf) {
    let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");

    rt.block_on(async {
        match SocketServer::new(socket_path) {
            Ok(server) => {
                let (shutdown_tx, shutdown_rx) = tokio::sync::broadcast::channel::<()>(1);

                let shutdown_tx_clone = shutdown_tx.clone();
                tokio::spawn(async move {
                    tokio::signal::ctrl_c().await.ok();
                    eprintln!("\nReceived Ctrl+C, shutting down...");
                    let _ = shutdown_tx_clone.send(());
                });

                if let Err(e) = server.run_with_shutdown(shutdown_rx).await {
                    eprintln!("Server error: {}", e);
                    exit(1);
                }
            }
            Err(e) => {
                eprintln!("Failed to create server: {}", e);
                exit(1);
            }
        }
    });
}

/// Start the daemon in background using double-fork
fn start_daemon_background(socket_path: PathBuf) {
    use nix::unistd::{ForkResult, fork, setsid};

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            if wait_for_daemon(&socket_path, 5) {
                println!("Daemon started successfully");
                println!("Socket: {}", socket_path.display());
            } else {
                eprintln!("Warning: Daemon may not have started properly");
                exit(1);
            }
            return;
        }
        Ok(ForkResult::Child) => {}
        Err(e) => {
            eprintln!("Fork failed: {}", e);
            exit(1);
        }
    }

    if setsid().is_err() {
        eprintln!("setsid failed");
        exit(1);
    }

    match unsafe { fork() } {
        Ok(ForkResult::Parent { .. }) => {
            exit(0);
        }
        Ok(ForkResult::Child) => {}
        Err(e) => {
            eprintln!("Second fork failed: {}", e);
            exit(1);
        }
    }

    use std::fs::OpenOptions;
    use std::os::unix::io::AsRawFd;

    if let Ok(devnull) = OpenOptions::new().read(true).write(true).open("/dev/null") {
        let fd = devnull.as_raw_fd();
        unsafe {
            libc::dup2(fd, 0);
            libc::dup2(fd, 1);
            libc::dup2(fd, 2);
        }
    }

    start_daemon_foreground(socket_path);
}

/// Stop the daemon
fn stop_daemon(socket_path: &PathBuf) {
    if !socket_path.exists() {
        println!("Daemon is not running");
        return;
    }

    let rt = tokio::runtime::Runtime::new().unwrap();
    let result = rt.block_on(async {
        let client = SocketClient::new(socket_path.clone());
        client.send_script("// shutdown").await
    });

    if let Err(e) = std::fs::remove_file(socket_path) {
        if e.kind() != std::io::ErrorKind::NotFound {
            eprintln!("Warning: Could not remove socket file: {}", e);
        }
    }

    match result {
        Ok(_) => println!("Daemon stopped"),
        Err(_) => println!("Daemon stopped (or was not running)"),
    }
}

/// Run a script via daemon
fn run_script_via_daemon(socket_path: &PathBuf, script: &str) {
    if !is_daemon_running(socket_path) {
        eprintln!("Daemon not running, starting...");

        let exe = env::current_exe().expect("Failed to get current executable");
        let status = Command::new(&exe)
            .args(["start", "-bg", "-s", &socket_path.to_string_lossy()])
            .status();

        match status {
            Ok(s) if s.success() => {}
            _ => {
                eprintln!("Failed to start daemon, running locally instead");
                run_script_local(script);
                return;
            }
        }

        if !wait_for_daemon(socket_path, 5) {
            eprintln!("Daemon failed to start, running locally");
            run_script_local(script);
            return;
        }
    }

    let rt = tokio::runtime::Runtime::new().expect("Failed to create runtime");
    let result = rt.block_on(async {
        let client = SocketClient::new(socket_path.clone());
        client.send_script_streaming(script).await
    });

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        exit(1);
    }
}

/// Run a script locally without daemon
fn run_script_local(script: &str) {
    match ForgeEngine::new() {
        Ok(engine) => match engine.run(script) {
            Ok(()) => {
                let output = heroforge_core::rhai_api::engine::take_output_buffer();
                if !output.is_empty() {
                    print!("{}", output);
                }
            }
            Err(e) => {
                eprintln!("{}: {}", "Script error".red().bold(), e);
                exit(1);
            }
        },
        Err(e) => {
            eprintln!("{}: {}", "Failed to create engine".red().bold(), e);
            exit(1);
        }
    }
}

/// Load and execute a script file in REPL
fn load_script_repl(
    file_path: &str,
    engine: &rhai::Engine,
    scope: &mut rhai::Scope,
) -> Result<(), String> {
    let expanded_path = if file_path.starts_with("~/") {
        dirs::home_dir()
            .map(|h| h.join(&file_path[2..]))
            .unwrap_or_else(|| PathBuf::from(file_path))
    } else {
        PathBuf::from(file_path)
    };

    if !expanded_path.exists() {
        return Err(format!("File not found: {}", expanded_path.display()));
    }

    println!("{} {}", "Loading:".green(), expanded_path.display());

    let script =
        fs::read_to_string(&expanded_path).map_err(|e| format!("Failed to read file: {}", e))?;

    engine
        .run_with_scope(scope, &script)
        .map_err(|e| format!("{}", e))
}

/// Run the interactive REPL
fn run_repl() -> Result<(), Box<dyn std::error::Error>> {
    print_banner();

    let forge_engine = ForgeEngine::new()?;
    let engine = forge_engine.engine();
    let mut scope = rhai::Scope::new();

    let config = Config::builder()
        .history_ignore_space(true)
        .completion_type(rustyline::CompletionType::List)
        .edit_mode(rustyline::EditMode::Emacs)
        .build();

    let helper = ReplHelper {
        hinter: HistoryHinter::new(),
    };

    let mut rl: Editor<ReplHelper, DefaultHistory> = Editor::with_config(config)?;
    rl.set_helper(Some(helper));

    let history_path = dirs::home_dir()
        .map(|h| h.join(".heroforge_core_history"))
        .unwrap_or_else(|| PathBuf::from(".heroforge_core_history"));
    let _ = rl.load_history(&history_path);

    let mut multiline_buffer = String::new();

    loop {
        let prompt = if multiline_buffer.is_empty() {
            "forge> "
        } else {
            "  ... "
        };

        match rl.readline(prompt) {
            Ok(line) => {
                let line = line.trim();

                // Handle REPL commands
                if multiline_buffer.is_empty() {
                    match line {
                        "/help" | "/h" => {
                            print_help();
                            continue;
                        }
                        "/functions" | "/fn" => {
                            print_functions();
                            continue;
                        }
                        "/repo" => {
                            print_category("Repository Functions", REPO_FUNCTIONS);
                            continue;
                        }
                        "/fs" => {
                            print_category("Filesystem Functions", FS_FUNCTIONS);
                            continue;
                        }
                        "/files" => {
                            print_category("File Functions", FILE_FUNCTIONS);
                            continue;
                        }
                        "/branches" => {
                            print_category("Branch/Tag Functions", BRANCH_FUNCTIONS);
                            continue;
                        }
                        "/modify" => {
                            print_category("Modify Builder Functions", MODIFY_FUNCTIONS);
                            continue;
                        }
                        "/find" => {
                            print_category("Find Builder Functions", FIND_FUNCTIONS);
                            continue;
                        }
                        "/utils" => {
                            print_category("Utility Functions", UTILITY_FUNCTIONS);
                            continue;
                        }
                        "/scope" => {
                            print_scope(&scope);
                            continue;
                        }
                        "/clear" => {
                            print!("\x1B[2J\x1B[1;1H");
                            print_banner();
                            continue;
                        }
                        "/quit" | "/exit" | "/q" => {
                            println!("{}", "Goodbye!".cyan());
                            break;
                        }
                        _ if line.starts_with("/load ") => {
                            let file_path = line.strip_prefix("/load ").unwrap().trim();
                            match load_script_repl(file_path, engine, &mut scope) {
                                Ok(_) => println!("{}", "Script executed successfully.".green()),
                                Err(e) => println!("{}: {}", "Error".red().bold(), e),
                            }
                            continue;
                        }
                        _ if line.starts_with('/') => {
                            println!(
                                "{}: Unknown command '{}'. Type /help for commands.",
                                "Error".red().bold(),
                                line
                            );
                            continue;
                        }
                        _ => {}
                    }
                }

                // Add to multiline buffer
                multiline_buffer.push_str(line);
                multiline_buffer.push('\n');

                // Check for line continuation
                let trimmed = line.trim_end();
                if trimmed.ends_with('\\') {
                    multiline_buffer = multiline_buffer
                        .trim_end()
                        .strip_suffix('\\')
                        .unwrap_or(&multiline_buffer)
                        .to_string();
                    multiline_buffer.push('\n');
                    continue;
                }

                // Check for unclosed braces/brackets
                let open_braces = multiline_buffer.matches('{').count();
                let close_braces = multiline_buffer.matches('}').count();
                let open_brackets = multiline_buffer.matches('[').count();
                let close_brackets = multiline_buffer.matches(']').count();
                let open_parens = multiline_buffer.matches('(').count();
                let close_parens = multiline_buffer.matches(')').count();

                if open_braces > close_braces
                    || open_brackets > close_brackets
                    || open_parens > close_parens
                {
                    continue;
                }

                // Execute the script
                let script = std::mem::take(&mut multiline_buffer);
                let script = script.trim();

                if script.is_empty() {
                    continue;
                }

                let _ = rl.add_history_entry(script);

                match engine.eval_with_scope::<rhai::Dynamic>(&mut scope, script) {
                    Ok(result) => {
                        // Print any buffered output first
                        let output = heroforge_core::rhai_api::engine::take_output_buffer();
                        if !output.is_empty() {
                            print!("{}", output);
                        }
                        if !result.is_unit() {
                            println!("{} {}", "=>".green(), result);
                        }
                    }
                    Err(e) => {
                        println!("{}: {}", "Error".red().bold(), e);
                    }
                }
                println!();
            }
            Err(ReadlineError::Interrupted) => {
                if !multiline_buffer.is_empty() {
                    multiline_buffer.clear();
                    println!("{}", "^C (input cleared)".dimmed());
                } else {
                    println!("{}", "^C (use /quit or Ctrl+D to exit)".dimmed());
                }
            }
            Err(ReadlineError::Eof) => {
                println!("{}", "Goodbye!".cyan());
                break;
            }
            Err(err) => {
                println!("{}: {:?}", "Error".red(), err);
                break;
            }
        }
    }

    let _ = rl.save_history(&history_path);

    Ok(())
}

/// Run a script from a file
fn run_script_file(path: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let script = fs::read_to_string(path)?;
    run_script_local(&script);
    Ok(())
}

/// Run a script from stdin
fn run_from_stdin() -> Result<(), Box<dyn std::error::Error>> {
    let stdin = io::stdin();
    let script: String = stdin
        .lock()
        .lines()
        .filter_map(|l| l.ok())
        .collect::<Vec<_>>()
        .join("\n");

    run_script_local(&script);
    Ok(())
}

/// Print usage information
fn print_usage() {
    println!(
        "{}",
        "heroforge-core - Rhai scripting for Fossil repositories"
            .cyan()
            .bold()
    );
    println!();
    println!("{}", "USAGE:".yellow().bold());
    println!("    heroforge-core                    Start interactive REPL");
    println!("    heroforge-core <script.rhai>      Run a script file");
    println!("    heroforge-core --ui               Start interactive REPL");
    println!("    heroforge-core -i                 Read script from stdin");
    println!("    heroforge-core -e <script>        Execute inline script");
    println!("    heroforge-core --local <script>   Run script locally (no daemon)");
    println!();
    println!("{}", "DAEMON COMMANDS:".yellow().bold());
    println!("    heroforge-core start              Start daemon in foreground");
    println!("    heroforge-core start -bg          Start daemon in background");
    println!("    heroforge-core stop               Stop the daemon");
    println!("    heroforge-core status             Check daemon status");
    println!();
    println!("{}", "OPTIONS:".yellow().bold());
    println!("    -s <path>                         Custom socket path");
    println!("    --help                            Show this help");
    println!("    --version                         Show version");
    println!();
    println!("{}", "EXAMPLES:".yellow().bold());
    println!("    {}", "heroforge-core --ui".dimmed());
    println!(
        "    {}",
        "heroforge-core -e 'let repo = repo_open(\"my.fossil\"); print(branches_list(repo));'"
            .dimmed()
    );
    println!(
        "    {}",
        "echo 'print(version())' | heroforge-core -i".dimmed()
    );
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        // Default to REPL mode
        if let Err(e) = run_repl() {
            eprintln!("{}: {}", "Error".red().bold(), e);
            std::process::exit(1);
        }
        return;
    }

    let socket_path = get_socket_path(&args);
    let run_local = args.contains(&"--local".to_string());

    match args[1].as_str() {
        "-h" | "--help" | "help" => {
            print_usage();
        }
        "-V" | "--version" | "version" => {
            println!("heroforge-core {}", env!("CARGO_PKG_VERSION"));
        }
        "--ui" | "--repl" => {
            if let Err(e) = run_repl() {
                eprintln!("{}: {}", "Error".red().bold(), e);
                std::process::exit(1);
            }
        }
        "-i" | "--stdin" => {
            if let Err(e) = run_from_stdin() {
                eprintln!("{}: {}", "Error".red().bold(), e);
                std::process::exit(1);
            }
        }
        "-e" => {
            if args.len() < 3 {
                eprintln!("{}: -e requires a script argument", "Error".red().bold());
                std::process::exit(1);
            }
            let script = &args[2];
            if run_local {
                run_script_local(script);
            } else {
                run_script_via_daemon(&socket_path, script);
            }
        }
        "start" => {
            if is_daemon_running(&socket_path) {
                println!("Daemon is already running");
                return;
            }
            let background = args.contains(&"-bg".to_string());
            if background {
                start_daemon_background(socket_path);
            } else {
                start_daemon_foreground(socket_path);
            }
        }
        "stop" => {
            stop_daemon(&socket_path);
        }
        "status" => {
            if is_daemon_running(&socket_path) {
                println!("Daemon is running");
                println!("Socket: {}", socket_path.display());
            } else {
                println!("Daemon is not running");
                std::process::exit(1);
            }
        }
        "--local" => {
            // --local requires a script file or -e argument after it
            if args.len() < 3 {
                eprintln!(
                    "{}: --local requires a script file or -e <script>",
                    "Error".red().bold()
                );
                std::process::exit(1);
            }
            match args[2].as_str() {
                "-e" => {
                    if args.len() < 4 {
                        eprintln!("{}: -e requires a script argument", "Error".red().bold());
                        std::process::exit(1);
                    }
                    run_script_local(&args[3]);
                }
                path => {
                    let script_path = PathBuf::from(path);
                    if script_path.exists() {
                        if run_script_file(&script_path).is_err() {
                            std::process::exit(1);
                        }
                    } else {
                        eprintln!("{}: File not found: {}", "Error".red().bold(), path);
                        std::process::exit(1);
                    }
                }
            }
        }
        "-s" => {
            // Socket path specified, skip to next relevant arg
            if args.len() < 4 {
                eprintln!("{}: -s requires a path argument", "Error".red().bold());
                std::process::exit(1);
            }
            // Re-parse starting from arg after socket path
            // For now, just show usage
            print_usage();
        }
        arg => {
            if arg.starts_with('-') {
                eprintln!("{}: Unknown option '{}'", "Error".red().bold(), arg);
                print_usage();
                std::process::exit(1);
            }

            let script_path = PathBuf::from(arg);
            if script_path.exists() {
                if run_local {
                    if run_script_file(&script_path).is_err() {
                        std::process::exit(1);
                    }
                } else {
                    let script = fs::read_to_string(&script_path).unwrap_or_else(|e| {
                        eprintln!("{}: {}", "Error reading file".red().bold(), e);
                        std::process::exit(1);
                    });
                    run_script_via_daemon(&socket_path, &script);
                }
            } else {
                eprintln!("{}: File not found: {}", "Error".red().bold(), arg);
                println!();
                print_usage();
                std::process::exit(1);
            }
        }
    }
}