#!/usr/bin/env raku
# Rakuish —— Raku 原生 REPL / 脚本入口（API v3）
#
# 用法：
#   raku bin/rakuish                    REPL（TTY 带提示符；管道则逐行求值）
#   raku bin/rakuish -e '1 + 1'        求值一段 Raku 后退出
#   raku bin/rakuish foo.raku [args]   跑 Raku 脚本（预加载 DSL）
#   raku bin/rakuish --agent [args...] 转发到 Agent 入口（结构化 op）
#   raku bin/rakuish --help | --version
#
# 这是唯一入口。v2 的双语言 REPL（! bash 子集 + %magic + 独立 shell 引擎）
# 已在 0.34.0（Phase 5b）整体下线：没有兼容开关、没有第二套语法、没有后台守护进程。
#
# 输入只有两类：
#   ! git status          → argv 分词后交给 sys.exec（元字符原样当参数）
#   其它（含 % 开头）    → Raku 表达式，直接 EVAL；失败就是失败，不回退 shell
#
# 模块搜索路径按脚本自身位置推算，所以从任意目录调用都能找到 lib/。

use lib $?FILE.IO.parent.parent.add('lib');
use Rakuish::REPL::Session;
use Rakuish::REPL::Chrome;
use Rakuish::REPL::Keymap;
use Terminal::LineEditor;
use Terminal::LineEditor::RawTerminalInput;

my constant FALLBACK_VERSION = '0.74.0';   # 与 META6.json 同步（t/51 守护）

# 注意：不要用 $?FILE.IO.dirname —— 它在 Windows 上返回 Str 且**丢掉盘符**
# （C:/Users/... → /Users/...），从其它盘调用时会指到错误位置。
sub project-root(--> IO::Path) { $?FILE.IO.parent.parent }
sub sibling(Str $name --> IO::Path) { $?FILE.IO.parent.add($name) }

sub meta-version(--> Str) {
    my $f = project-root().add('META6.json');
    if $f.e {
        my $t = try { $f.slurp };
        if $t.defined && $t ~~ /'"version"' \s* ':' \s* '"' (<-["]>+) '"'/ {
            return $0.Str;
        }
    }
    my $v = try { $?DISTRIBUTION.meta<version> };
    return $v.Str if $v.defined && $v.Str.chars;
    FALLBACK_VERSION;
}

# 转发到另一个入口：stdio 全部继承，退出码原样带回。
# 用 argv 数组调用，不经过 shell，参数里的空格 / 引号 / 元字符都不解释。
sub forward(Str $name, *@args --> Int) {
    my $target = sibling($name);
    unless $target.e {
        $*ERR.say: "rakuish: 找不到 {$name} 入口 {$target.Str}";
        return 127;
    }
    my $p = run($*EXECUTABLE.Str, $target.Str, |@args);
    $p.exitcode // 1
}

sub help-text(--> Str) {
    q:to/END/;
    Rakuish · Raku 原生命令与脚本环境（API v3）

    用法
      rakuish                       启动 REPL
      rakuish -e '1 + 1'            求值一段 Raku 后退出
      rakuish foo.raku [args...]    跑 Raku 脚本（已预加载 DSL）
      rakuish --agent [args...]     Agent（结构化 op，见 rakuish-agent --help）
      rakuish --help / --version    本说明 / 版本号

    输入（只有两类）
      ! git status             argv 分词 → sys.exec（| > $ * && 原样当参数）
      其它全部                 Raku 表达式（%foo<a> 就是哈希访问，不是魔法命令）
      没有 %magic、没有 auto-shell、没有反引号 shellq、没有 bash 语法

    REPL 对象与短命令（表达式里直接可用）
      sys.read('a.txt') / sys.ls('docs') / sys.exec('git','status')
      repl.history / repl.config<key> / repl.trace = True
      registry.names / registry.get('read').spec
      ls / read / write / append / stat / rm / cp / mv / mkdir / glob
      exec / cd / pwd / env / timed { ... } / bench({ ... }) / recent(7, 'md') / help()
      perf [N] 查看每格耗时（Shell 薄层命令，数据来自会话而非文本魔法）

    快捷键（TTY 宿主）
      Up / Down 历史 · Ctrl-R 搜索 · Ctrl-C 中断输入（不退出） · Ctrl-D 退出
      Ctrl-X Ctrl-E 外部编辑器 · Tab 补全

    界面与计时（0.62）
      banner / prompt 显示时间、cwd、git 分支、格号与上格耗时
      timed { ... } / bench({ ... }, :repeat(5)) / perf [N] 查看耗时历史
      config set color auto|on|off · clock on|off · timing on|off
      config set git on|off · prompt-style full|compact|plain · banner on|off
      NO_COLOR 强制关色；FORCE_COLOR=1 强制开；管道下自动纯文本

    声明与 glob（0.65）
      class Box { ... } 单独成格后，后续格可直接用 Box.new(...)
      role / grammar 同理；sub / use 也跨格；混合语句格不缓存
      glob('{a,{b,c}}.txt') 嵌套 brace · glob('\{a,b\}.txt') 转义字面量
      Shell 薄层文件名参数只展开 * ?；边界见 docs/MANUAL.md / SPEC V-153

    交互体验（0.66，ADR-0003）
      config set edit-mode emacs|vi|helix  行编辑键位 / 模态（默认 emacs）
      config set vi-start insert|normal   每行起始模式（vi/helix 下）
      config set hints on|off             上下文提示（默认 on，同一首词只提示一次）
      config set plugins on|off           允许加载本地 Raku 插件（默认 off）
      Esc 进 normal · i/a/A/I/o/O 进 insert · h/l/w/b/0/$/x/dd/u · j/k 翻历史
      hint [输入行] 查询提示 · plugin list|load PATH|unload NAME|info NAME
      插件 = 返回 Command 对象（或 List）的本地 .rakumod/.raku；加载即执行本地代码

    数据工作台（0.67 / 0.68，ADR-0004 / ADR-0005）
      my $c = $db.cursor('select ...')  惰性分批：batches / take / close
      open-data('x.csv', :allow-external)  由 DuckDB 推断 int/num（默认仍走 Sys）
      save-data('x.csv', $t, :allow-external)  COPY ... FORMAT CSV, HEADER
      open-db(...) 注册当前会话 Engine；Tab 在 SQL 字符串里补表名 / 列名

    数据剖析与方言（0.69，ADR-0006）
      describe [表名]            列摘要 Table（name/type/nullable/non_null/…）
      describe($t) / describe('表名')   Raku 值 API，可继续 .where / .to-json
      open-data('x.csv', :allow-external, :csv-options({ delimiter => ';' }))
        CSV 方言：delimiter/quote/escape/nullstr/header/skip/all-varchar
        读选项全部 ? 绑定；写出仅支持 delimiter/quote/escape/header/nullstr
      Tab 支持表别名前缀（s.am → s.amount）与关键字大小写（SEL → SELECT）
      不做 SQL AST 解析；边界见 docs/MANUAL.md / SPEC V-162…165

    嵌套 REPL / 交互式子进程（0.70，ADR-0007）
      ! --tty rakupp          或 -t：把 TTY 直通给子进程，无 30s 超时
      tty-exec('rakupp')      Raku 原生入口（表达式里可用）
      ! -- --tty foo         -- 之后是字面 argv，不解析元选项
      输出实时可见但不进 _ / Out[n]；非 TTY 明确拒绝；Agent 不开放
      普通 ! 命令仍受 30s 超时与输出捕获约束，超时会给提示

    输入中断与补全形态（0.71，ADR-0008）
      Ctrl-C 中断当前输入 / 清空续行缓冲，重画 prompt（不退出、不产生空 Out）
      Ctrl-D / exit 才退出会话；求值中的 SIGINT 仍按 Rakudo 默认
      $db.query(q[select * from sales where region = 'east' and am])  Tab 补 amount
      query(sql => '...') / query(:sql('...'))  具名参数也进 SQL 补全
      仍不做 SQL AST / qq / heredoc；边界见 docs/MANUAL.md / SPEC V-168…169

    退出：Ctrl-D 或输入 exit / exit N；管道 EOF 自动结束。
    END
}

sub run-start-hooks($session --> Nil) {
    for $session.run-hooks('start') -> $r {
        print $r.out if $r.out.chars;
        $*ERR.print($r.err) if $r.err.chars;
        unless $r.ok {
            $*ERR.say: 'rakuish: 启动 hook 失败，停止启动';
            exit 1;
        }
    }
}

my @a = @*ARGS;

if @a.elems {
    given @a[0] {
        when '--agent' {
            exit forward('rakuish-agent', |@a.skip(1));
        }
        when '--help' | '-h' {
            say "rakuish " ~ meta-version();
            say help-text();
            exit 0;
        }
        when '--version' | '-V' {
            say 'rakuish ' ~ meta-version();
            exit 0;
        }
        when '-e' {
            unless @a.elems >= 2 {
                $*ERR.say: 'rakuish: -e 后面要跟一段 Raku 代码';
                exit 2;
            }
            my $session = Rakuish::REPL::Session.new(
                :color(color-mode('auto', :tty(so try { $*OUT.t }))));
            run-start-hooks($session);
            my $r = $session.eval-line(@a[1]);
            # `-e` 等于跑一个 REPL 格，默认仍打印 `Out[1] = ...`。
            # 唯一例外：值恰好是 `Bool::True` 时不打印那行 —— Raku 里 say / print /
            # note 都返回 True，渲染它只会给 `-e 'say 1'` 添噪声。
            # 注意要**保留**捕获到的 stdout（不然 `-e 'say 1'` 会什么都不输出）；
            # 确实想看 True 就写 `-e 'True.raku'` 或 `-e 'say True'`。
            if $r.ok && $r.value ~~ Bool && $r.value {
                print $r.out if $r.out.chars;
            }
            else {
                my $text = $session.render($r);
                if $text.chars {
                    $r.no-newline ?? print($text) !! say($text);
                }
            }
            exit($r.ok ?? 0 !! 1);
        }
        default {
            if @a[0].starts-with('-') {
                $*ERR.say: "rakuish: 未知选项 {@a[0]}（用 --help 查看用法）";
                exit 2;
            }
            # 脚本就是 Raku 脚本：整份源码作为一个 cell 求值，
            # 与 REPL 共用同一套词法环境（sys / repl / registry + DSL），
            # 不另建解释器、不解析 shebang、不模拟 %magic。
            my $file = @a[0].IO;
            unless $file.e {
                $*ERR.say: "rakuish: 找不到脚本 {@a[0]}";
                exit 2;
            }
            @*ARGS = @a.skip(1);
            my $session = Rakuish::REPL::Session.new(
                :color(color-mode('auto', :tty(so try { $*OUT.t }))));
            run-start-hooks($session);
            my $r = $session.eval-line($file.slurp);
            if $r.op eq 'more' {
                $*ERR.say: "rakuish: 脚本 {@a[0]} 存在未闭合结构，拒绝静默不执行";
                exit 2;
            }
            # 脚本模式不打印 Out[n]（那是 REPL 的格子标签）：
            # stdout 原样透传，stderr 原样透传，值不另作展示。
            print $r.out if $r.out.chars;
            $*ERR.print($r.err) if $r.err.chars;
            exit($r.ok ?? 0 !! 1);
        }
    }
}

# ── 交互式 REPL ─────────────────────────────────────────────────────
# 管道下不打印 banner / prompt，保证 stdout 只有求值结果（SPEC V-116）。
my Bool $tty     = so try { $*IN.t };
my Bool $tty-out = so try { $*OUT.t };

my $session = Rakuish::REPL::Session.new(
    :color(color-mode('auto', :tty($tty-out))));
run-start-hooks($session);

# 交互式行编辑：上下翻历史、Ctrl-R 搜索、光标编辑、历史落盘。
# 管道/脚本仍走 $*IN.get，避免把控制序列混进 stdout。
my $cli;
my $history-file;
my Str $edit-mode = ($session.config<edit-mode> // 'emacs').Str.lc;
my Str $vi-start  = ($session.config<vi-start>  // 'insert').Str.lc;
# 闭包（具名 sub 捕获不到这里的 $session）：vi/helix 走 Keymap 的子类行编辑器，
# 构造失败由 make-cli 自动回退到原生 CLIInput。
my &build-cli = -> Str $style --> Any {
    make-cli(
        :$style,
        :start-mode($vi-start),
        :get-completions(-> $line, $pos { $session.completions($line, $pos) })
    )
};
if $tty {
    $cli = build-cli($edit-mode);
    $history-file = try { $*HOME.add('.rakuish-history') };
    if $cli.defined && $history-file.defined && $history-file.e {
        try { $cli.load-history($history-file.Str) };
    }
}

# 展示配置都是扁平字符串键；每格重新读取，config set 当格即生效。
# 用闭包而不是具名 sub —— 具名 sub 无法捕获这里的词法 $session。
my &conf = -> Str $key, Str $default --> Str {
    ($session.config{$key} // $default).Str
};
my &on = -> Str $key --> Bool { conf($key, 'on').lc ne 'off' };

if $tty && on('banner') {
    print banner-text(
        :version(meta-version()),
        :cwd($session.sys.cwd.Str),
        :editor($cli.defined ?? 'LineEditor' !! '基础输入'),
        :mode($edit-mode),
        :plugins($session.plugins.names.elems.Str),
        :color(color-mode(conf('color', 'auto'), :tty($tty-out))),
    );
}

my Bool $last-ok = True;
my Int  $last-code = 0;
my      $last-elapsed;
my Bool $continuing = False;
my Str  $hint-text = '';

loop {
    my Bool $color   = color-mode(conf('color', 'auto'), :tty($tty-out));
    # 0.74.0 / ADR-0011：结果渲染层与输入行高亮的开关都要跟着 config 走，
    # 且当格生效（`config set color off` 之后下一格就该没有颜色）。
    $session.set-color($color);
    set-highlight($color);

    # config set edit-mode vi|helix|emacs 当格生效：重建行编辑器并迁移历史。
    if $tty {
        my Str $want = conf('edit-mode', 'emacs').lc;
        if $want ne $edit-mode {
            if $cli.defined && $history-file.defined {
                try { $cli.save-history($history-file.Str) };
            }
            $edit-mode = $want;
            $cli = build-cli($edit-mode);
            if $cli.defined && $history-file.defined && $history-file.e {
                try { $cli.load-history($history-file.Str) };
            }
        }
    }

    # hints 是「上一格给下一格的提示」；管道 / 非 TTY 完全不输出。
    if $tty && on('hints') && $hint-text.chars {
        my Str $hint-line = '  · ' ~ $hint-text;
        say $color ?? "\e[90m" ~ $hint-line ~ "\e[0m" !! $hint-line;
    }

    my Str  $cwd     = $session.sys.cwd.Str;
    my Str  $branch  = ($tty && on('git'))
        ?? git-branch($session.sys, $session.sys.cwd) !! '';
    my Str  $mode-badge = $edit-mode eq 'emacs'
        ?? '' !! $edit-mode.uc ~ '·' ~ vi-state().mode-label;
    my Str  $prompt  = prompt-text(
        :$cwd,
        :index($session.index),
        :elapsed($last-elapsed),
        :ok($last-ok), :code($last-code),
        :$branch, :$color,
        :clock(on('clock')), :timing(on('timing')),
        :$continuing, :style(conf('prompt-style', 'full')),
        :mode($mode-badge),
    );

    my $line;
    if $tty && $cli.defined {
        my $in = try { $cli.prompt($prompt) };
        if $! {
            # 行编辑器在异常终端上不可用时退回普通行输入，不阻塞用户。
            $cli = Nil;
            print $prompt;
            $line = $*IN.get;
            $! = Nil;
        }
        elsif !$in.defined {
            last;
        }
        else {
            $line = $in;
        }
    }
    else {
        print $prompt if $tty;
        $line = $*IN.get;
    }
    last unless $line.defined;

    # 0.71 / ADR-0008 §3.1：Ctrl-C 只中断当前输入，不退出宿主 REPL。
    # 复用 Session.handle-key 的值 API 清掉续行缓冲；不 eval、不进历史、
    # 不产生空 Out[n] 格。原生 CLIInput 回退路径没有 take-interrupt，
    # 语义保持 0.70 不变。
    if $cli.defined && $cli.^can('take-interrupt') && $cli.take-interrupt {
        $session.handle-key('Ctrl-C');
        $continuing = False;
        $hint-text = '';
        say $color ?? "\e[90m  · 已中断当前输入（Ctrl-C）；Ctrl-D 退出\e[0m"
                   !! '  · 已中断当前输入（Ctrl-C）；Ctrl-D 退出';
        next;
    }
    $cli.add-history($line) if $cli.defined && $line.trim.chars;

    my Instant $t0 = now;
    my $r = $session.eval-line($line);
    my Duration $dt = now - $t0;
    $session.note-timing($dt, $line, $r.ok);
    $last-elapsed = $dt;
    $last-ok      = $r.ok;
    $last-code    = $r.code;
    $continuing   = $r.op eq 'more';
    $hint-text    = $session.next-hint($line, $r);

    my $text = $session.render($r);
    if $text.chars {
        $r.no-newline ?? print($text) !! say($text);
    }
    # 最常见的误用：把启动参数当 REPL 命令敲。这里不会为它开魔法分支
    # （输入一律按 Raku 求值），但值得给一句提示，省掉读栈回溯。
    if !$r.ok && $line.trim ~~ /^ '--' \w+ $/ {
        say '提示: --help / --version / --agent 是**启动参数**，要在 shell 里写 '
          ~ '`rakuish --help`；提示符里输入一律按 Raku 求值，所以 `--help` 被当成 `--` 运算符。';
    }
    last if $session.exit-requested;
}
if $cli.defined && $history-file.defined {
    try { $cli.save-history($history-file.Str) };
}
exit $session.exit-code;
