#!/usr/bin/env python3
# 用法：
#   1) 创建虚拟环境并安装依赖：
#        python -m venv ".venv"
#        source ".venv/bin/activate"
#        python -m pip install flask
#   2) 启动 Web UI（固定端口 8000）：
#        python "src/web_main.py"
#
# 说明：
#   - Web 端只做“按 Stage 单步执行”，复用 CLI 的核心能力（src/pipeline_runner.py）。
#   - 前端是单页（src/web/index.html），通过 REST API 轮询状态并发起控制操作。
#   - Web 允许依赖第三方包；CLI 核心仍保持标准库实现。

from __future__ import annotations

import os
import shlex
import signal
import threading
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Optional

from flask import Flask, Response, jsonify, request
from tomlkit import array as toml_array
from tomlkit import dumps as toml_dumps
from tomlkit import parse as toml_parse
from tomlkit import table as toml_table

import procfs
from config_loader import RunConfig, _build_argv_from_stage_args, load_config
from pipeline_runner import (
    MODE_PIPE,
    SUPPORTED_MODES,
    StageInvocation,
    StepRunPaths,
    StepStageResult,
    make_step_output_path,
    prepare_step_run,
    run_stage_step,
    validate_chain,
)
from stage_registry import StageSpec, get_stage_specs


def _project_root() -> Path:
    return Path(__file__).resolve().parent.parent


def _read_first_comment_title(path: Path) -> str:
    """
    从 experiments/*.toml 中提取标题（约定：首行以 # 开头）。
    若不存在则回退为空字符串。
    """
    try:
        with path.open("r", encoding="utf-8", errors="replace") as f:
            first = f.readline().strip()
    except OSError:
        return ""
    if first.startswith("#"):
        return first.lstrip("#").strip()
    return ""


def _read_text(path: Path, *, max_chars: int) -> str:
    if max_chars <= 0:
        return ""
    try:
        text = path.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return ""
    if len(text) <= max_chars:
        return text
    return text[:max_chars] + "\n\n...(已截断)...\n"


def _tail_text(path: Path, *, max_bytes: int) -> str:
    if max_bytes <= 0:
        return ""
    try:
        with path.open("rb") as f:
            f.seek(0, os.SEEK_END)
            size = f.tell()
            start = max(0, size - max_bytes)
            f.seek(start, os.SEEK_SET)
            data = f.read()
        return data.decode("utf-8", errors="replace")
    except OSError:
        return ""


def _proc_to_dict(info: Optional[procfs.ProcInfo]) -> dict[str, Any]:
    if info is None:
        return {"available": False}
    return {
        "available": True,
        "pid": info.pid,
        "ppid": info.ppid,
        "state": info.state,
        "cmdline": info.cmdline,
        "cpu_time_seconds": info.cpu_time_seconds,
        "cpu_time_hms": procfs.format_duration_seconds(info.cpu_time_seconds),
        "rss_bytes": info.rss_bytes,
        "rss_human": procfs.format_bytes(info.rss_bytes),
        "start_time_epoch": info.start_time_epoch,
        "start_time_text": procfs.format_epoch(info.start_time_epoch),
    }


def _spec_to_dict(spec: StageSpec) -> dict[str, Any]:
    return {
        "stage_id": spec.stage_id,
        "script": spec.script,
        "input_type": spec.input_type,
        "output_type": spec.output_type,
        "description": spec.description,
    }


def _invocation_to_dict(inv: StageInvocation, *, specs: dict[str, StageSpec]) -> dict[str, Any]:
    spec = specs.get(inv.stage_id)
    return {
        "stage_id": inv.stage_id,
        "argv": list(inv.argv),
        "enabled": bool(inv.enabled),
        "description": spec.description if spec is not None else "",
        "input_type": spec.input_type if spec is not None else None,
        "output_type": spec.output_type if spec is not None else None,
    }


def _parse_pipeline_lines(lines: list[str]) -> tuple[Optional[list[StageInvocation]], str]:
    invocations: list[StageInvocation] = []
    for i, line in enumerate(lines):
        try:
            parts = shlex.split(line)
        except ValueError as exc:
            return None, f"pipeline[{i}] 参数解析失败：{exc}"
        if not parts:
            return None, f"pipeline[{i}] 为空"
        stage_id = parts[0]
        argv = parts[1:]
        invocations.append(StageInvocation(stage_id=stage_id, argv=argv, enabled=True))
    ok, msg = validate_chain(invocations)
    if not ok:
        return None, msg
    return invocations, "OK"


def _invocations_to_lines(invocations: list[StageInvocation]) -> list[str]:
    out: list[str] = []
    for inv in invocations:
        parts = [inv.stage_id, *inv.argv]
        out.append(" ".join(shlex.quote(x) for x in parts))
    return out


def _is_within_dir(path: Path, root_dir: Path) -> bool:
    try:
        path.resolve().relative_to(root_dir.resolve())
    except ValueError:
        return False
    return True


def _build_multiline_toml_string_array(values: list[str]) -> Any:
    arr = toml_array()
    arr.multiline(True)
    for v in values:
        arr.add_line(v)
    return arr


def _build_stage_args_toml_table(stage_args: dict[str, dict[str, Any]]) -> Any:
    root = toml_table()
    for stage_id in sorted(stage_args.keys()):
        parts = [p for p in stage_id.split(".") if p]
        if not parts:
            continue
        cur = root
        for p in parts:
            if p not in cur:
                cur[p] = toml_table()
            cur = cur[p]
        for k in sorted(stage_args[stage_id].keys()):
            cur[k] = stage_args[stage_id][k]
    return root


def _writeback_pipeline_to_config(
    *,
    config_path: Path,
    mode: str,
    stages: list[str],
    stage_args: dict[str, dict[str, Any]],
) -> tuple[bool, str]:
    """
    将 UI 中的流水线写回 pipeline.toml（保留尽可能多的注释与格式）。

    说明：
    - stages 是“每个元素一条 Stage 调用字符串”，例如：
        "source.file"
        "token.len_range --min-len 4 --max-len 12"
    """
    try:
        text = config_path.read_text(encoding="utf-8", errors="replace")
    except OSError as exc:
        return False, f"读取配置失败：{exc}"

    try:
        doc = toml_parse(text)
    except Exception as exc:
        return False, f"TOML 解析失败：{exc}"

    if "run" not in doc or "pipeline" not in doc:
        return False, "配置缺失 [run] 或 [pipeline]"

    try:
        doc["run"]["mode"] = mode
        doc["pipeline"]["stages"] = _build_multiline_toml_string_array(stages)
        if stage_args:
            doc["stage_args"] = _build_stage_args_toml_table(stage_args)
        elif "stage_args" in doc:
            del doc["stage_args"]
    except Exception as exc:
        return False, f"更新配置失败：{exc}"

    try:
        out = toml_dumps(doc)
        if not out.endswith("\n"):
            out += "\n"
        config_path.write_text(out, encoding="utf-8")
    except OSError as exc:
        return False, f"写回失败：{exc}"

    return True, "OK"


@dataclass
class AppState:
    root_dir: Path
    config_path: Path
    lock: threading.Lock = field(default_factory=threading.Lock)

    config: Optional[RunConfig] = None
    config_error: Optional[str] = None

    ui_mode: str = MODE_PIPE
    ui_pipeline_lines: list[str] = field(default_factory=list)
    ui_invocations: list[StageInvocation] = field(default_factory=list)
    ui_pipeline_error: Optional[str] = None
    # UI 的结构化参数表：stage_id -> {key: value}
    ui_stage_args: dict[str, dict[str, Any]] = field(default_factory=dict)

    run_paths: Optional[StepRunPaths] = None
    next_step_index: int = 1
    stdin_path: Optional[Path] = None

    running: bool = False
    running_stage_id: Optional[str] = None
    running_pid: Optional[int] = None
    running_mailbox_pid: Optional[int] = None
    running_output_path: Optional[Path] = None

    last_step_result: Optional[dict[str, Any]] = None
    last_step_error: Optional[str] = None


def _reload_config_locked(state: AppState) -> None:
    cfg, msg = load_config(state.config_path)
    if cfg is None:
        state.config = None
        state.config_error = msg
        return

    state.config = cfg
    state.config_error = None

    # 默认：UI 同步配置文件（更直观，减少“配置与 UI 不一致”的困扰）。
    state.ui_mode = cfg.mode
    state.ui_stage_args = {k: dict(v) for k, v in (cfg.stage_args or {}).items()}

    # UI 展示/写回：尽量使用配置文件中的 pipeline.stages 原始字符串（而不是 stage_args 注入后的 argv）。
    raw_lines = list(getattr(cfg, "pipeline_stage_lines", [])) or _invocations_to_lines(cfg.invocations)
    invocations, msg = _parse_pipeline_lines(raw_lines)
    if invocations is None:
        state.ui_invocations = []
        state.ui_pipeline_lines = raw_lines
        state.ui_pipeline_error = msg
    else:
        state.ui_invocations = invocations
        state.ui_pipeline_lines = raw_lines
        state.ui_pipeline_error = None

    # 配置变化会影响运行环境，保守起见重置 run 状态（避免 stdin_path 等状态错配）。
    state.run_paths = None
    state.next_step_index = 1
    state.stdin_path = None
    state.running = False
    state.running_stage_id = None
    state.running_pid = None
    state.running_mailbox_pid = None
    state.running_output_path = None
    state.last_step_result = None
    state.last_step_error = None


def _reset_run_locked(state: AppState) -> tuple[bool, str]:
    if state.running:
        return False, "当前 Stage 仍在运行，无法 reset"
    if state.config is None:
        return False, f"配置未就绪：{state.config_error}"
    if not state.ui_invocations:
        return False, "流水线为空"
    if state.ui_mode not in SUPPORTED_MODES:
        return False, f"不支持的通信方式：{state.ui_mode}"

    paths = prepare_step_run(state.config.outputs_dir)
    state.run_paths = paths
    state.next_step_index = 1
    state.stdin_path = None
    state.last_step_result = None
    state.last_step_error = None
    state.running_stage_id = None
    state.running_pid = None
    state.running_mailbox_pid = None
    state.running_output_path = None
    return True, "OK"


def _start_step_thread(state: AppState) -> tuple[bool, str]:
    if state.running:
        return False, "当前 Stage 仍在运行"
    if state.config is None:
        return False, f"配置未就绪：{state.config_error}"
    if state.run_paths is None:
        ok, msg = _reset_run_locked(state)
        if not ok:
            return False, msg
    assert state.run_paths is not None

    if state.next_step_index < 1 or state.next_step_index > len(state.ui_invocations):
        return False, "流水线已执行完毕（请 reset）"

    inv_inline = state.ui_invocations[state.next_step_index - 1]
    inv = StageInvocation(inv_inline.stage_id, list(inv_inline.argv), inv_inline.enabled)
    if not inv.argv:
        args = state.ui_stage_args.get(inv.stage_id)
        if args:
            try:
                inv.argv = _build_argv_from_stage_args(inv.stage_id, args)
            except ValueError as exc:
                return False, str(exc)
    out_path = make_step_output_path(state.run_paths.steps_dir, state.next_step_index, inv.stage_id)

    state.running = True
    state.running_stage_id = inv.stage_id
    state.running_pid = None
    state.running_mailbox_pid = None
    state.running_output_path = out_path
    state.last_step_result = None
    state.last_step_error = None

    def run() -> None:
        def on_started(stage_id: str, pid: int, _info: Optional[procfs.ProcInfo], mailbox_pid: Optional[int]) -> None:
            with state.lock:
                # 若 reset 导致状态被清空，仍允许 UI 看到这次启动信息；但后续状态以 lock 内字段为准。
                state.running_stage_id = stage_id
                state.running_pid = pid
                state.running_mailbox_pid = mailbox_pid

        result: Optional[StepStageResult]
        msg: str

        with state.lock:
            cfg = state.config
            mode = state.ui_mode
            stdin_path = state.stdin_path
            run_paths = state.run_paths
            step_index = state.next_step_index
        assert cfg is not None
        assert run_paths is not None

        result, msg = run_stage_step(
            step_index=step_index,
            invocation=inv,
            mode=mode,
            input_path=cfg.input_path,
            stdin_path=stdin_path,
            output_path=out_path,
            report_path=run_paths.report_path,
            log_path=run_paths.log_path,
            default_topn=cfg.default_topn,
            preview_lines=cfg.preview_lines,
            on_started=on_started,
            on_running=None,
        )

        with state.lock:
            state.running = False
            if result is None:
                state.last_step_error = msg
                return

            state.last_step_result = {
                "step_index": result.step_index,
                "stage_id": result.stage_id,
                "pid": result.pid,
                "mailbox_pid": result.mailbox_pid,
                "returncode": result.returncode,
                "started_at": result.started_at,
                "finished_at": result.finished_at,
                "duration_seconds": result.finished_at - result.started_at,
                "output_path": str(result.output_path),
                "output_preview": list(result.output_preview),
                "message": msg,
            }

            if result.returncode == 0:
                state.stdin_path = result.output_path
                state.next_step_index += 1
            else:
                state.last_step_error = msg

    t = threading.Thread(target=run, name="web-step-runner", daemon=True)
    t.start()
    return True, "OK"


def create_app(state: AppState) -> Flask:
    app = Flask(__name__)

    @app.get("/")
    def index() -> Response:
        index_path = state.root_dir / "src" / "web" / "index.html"
        try:
            html = index_path.read_text(encoding="utf-8", errors="replace")
        except OSError as exc:
            return Response(f"index.html 读取失败：{exc}\n", status=500, mimetype="text/plain")
        return Response(html, status=200, mimetype="text/html; charset=utf-8")

    @app.get("/api/stage-specs")
    def api_stage_specs():
        specs = get_stage_specs()
        return jsonify(
            {
                "ok": True,
                "specs": {stage_id: _spec_to_dict(spec) for stage_id, spec in specs.items()},
            }
        )

    @app.get("/api/config")
    def api_get_config():
        with state.lock:
            path = state.config_path
        return jsonify({"ok": True, "path": str(path), "text": _read_text(path, max_chars=200_000)})

    @app.put("/api/config")
    def api_put_config():
        payload = request.get_json(silent=True) or {}
        text = payload.get("text")
        if not isinstance(text, str):
            return jsonify({"ok": False, "error": "请求体必须是 JSON，且包含字符串字段 text"}), 400

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return (
                    jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法保存配置"}),
                    409,
                )
            path = state.config_path
        try:
            path.write_text(text, encoding="utf-8")
        except OSError as exc:
            return jsonify({"ok": False, "error": f"写入失败：{exc}"}), 500

        with state.lock:
            _reload_config_locked(state)
            ok = state.config is not None
            err = state.config_error
        return jsonify({"ok": ok, "error": err})

    @app.post("/api/config/writeback")
    def api_writeback_config():
        payload = request.get_json(silent=True) or {}
        mode = payload.get("mode")
        stages = payload.get("stages")
        stage_args = payload.get("stage_args")

        if not isinstance(mode, str):
            return jsonify({"ok": False, "error": "mode 必须是字符串"}), 400
        mode = mode.strip()
        if mode not in SUPPORTED_MODES:
            return jsonify({"ok": False, "error": f"不支持的 mode：{mode}"}), 400

        if not isinstance(stages, list) or not all(isinstance(x, str) for x in stages):
            return jsonify({"ok": False, "error": "stages 必须是字符串数组"}), 400
        cleaned = [x.strip() for x in stages if x.strip()]
        if not cleaned:
            return jsonify({"ok": False, "error": "stages 不能为空"}), 400

        invocations, msg = _parse_pipeline_lines(cleaned)
        if invocations is None:
            return jsonify({"ok": False, "error": f"流水线校验失败：{msg}"}), 400

        cleaned_stage_args: dict[str, dict[str, Any]] = {}
        if stage_args is None:
            with state.lock:
                cleaned_stage_args = {k: dict(v) for k, v in state.ui_stage_args.items()}
        else:
            if not isinstance(stage_args, dict):
                return jsonify({"ok": False, "error": "stage_args 必须是对象（dict）"}), 400
            for stage_id, args in stage_args.items():
                if not isinstance(stage_id, str) or not stage_id.strip():
                    return jsonify({"ok": False, "error": "stage_args 的 key 必须是非空字符串"}), 400
                if args is None:
                    continue
                if not isinstance(args, dict):
                    return jsonify({"ok": False, "error": f"stage_args.{stage_id} 必须是对象（dict）"}), 400
                cleaned_args: dict[str, Any] = {}
                for k, v in args.items():
                    if not isinstance(k, str) or not k.strip():
                        return jsonify({"ok": False, "error": f"stage_args.{stage_id} 存在非法 key"}), 400
                    if v is None:
                        continue
                    cleaned_args[k.strip()] = v
                # 用同一套逻辑校验类型与必要约束（例如 token.len_range 的 min/max）
                try:
                    _build_argv_from_stage_args(stage_id.strip(), cleaned_args)
                except ValueError as exc:
                    return jsonify({"ok": False, "error": str(exc)}), 400
                if cleaned_args:
                    cleaned_stage_args[stage_id.strip()] = cleaned_args

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return (
                    jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法写回配置"}),
                    409,
                )
            config_path = state.config_path

        ok, err = _writeback_pipeline_to_config(
            config_path=config_path,
            mode=mode,
            stages=cleaned,
            stage_args=cleaned_stage_args,
        )
        if not ok:
            return jsonify({"ok": False, "error": err}), 500

        with state.lock:
            _reload_config_locked(state)
        return jsonify({"ok": True})

    @app.get("/api/experiments")
    def api_get_experiments():
        root = state.root_dir
        experiments_dir = (root / "experiments").resolve()

        items: list[dict[str, Any]] = []
        try:
            if experiments_dir.is_dir():
                for p in sorted(experiments_dir.glob("*.toml")):
                    items.append(
                        {
                            "file": p.name,
                            "title": _read_first_comment_title(p),
                        }
                    )
        except OSError:
            items = []

        current_file = ""
        with state.lock:
            config_path = state.config_path
            if not state.running:
                try:
                    current_text = config_path.read_text(encoding="utf-8", errors="replace")
                except OSError:
                    current_text = ""
                for it in items:
                    try:
                        exp_text = (experiments_dir / it["file"]).read_text(encoding="utf-8", errors="replace")
                    except OSError:
                        continue
                    if exp_text == current_text:
                        current_file = it["file"]
                        break

        return jsonify(
            {
                "ok": True,
                "dir": str(experiments_dir),
                "items": items,
                "current_file": current_file,
            }
        )

    @app.post("/api/experiments/apply")
    def api_apply_experiment():
        payload = request.get_json(silent=True) or {}
        file = payload.get("file")
        if not isinstance(file, str) or not file.strip():
            return jsonify({"ok": False, "error": "file 必须是非空字符串"}), 400
        file = file.strip()
        if "/" in file or "\\" in file:
            return jsonify({"ok": False, "error": "file 不允许包含路径分隔符"}), 400
        if not file.endswith(".toml"):
            return jsonify({"ok": False, "error": "仅支持 .toml 配置文件"}), 400

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法切换实验配置"}), 409
            root = state.root_dir
            config_path = state.config_path

        experiments_dir = (root / "experiments").resolve()
        exp_path = (experiments_dir / file).resolve()
        if not _is_within_dir(exp_path, experiments_dir):
            return jsonify({"ok": False, "error": "非法实验配置路径"}), 400
        if not exp_path.is_file():
            return jsonify({"ok": False, "error": f"实验配置不存在：{file}"}), 404

        try:
            text = exp_path.read_text(encoding="utf-8", errors="replace")
        except OSError as exc:
            return jsonify({"ok": False, "error": f"读取实验配置失败：{exc}"}), 500

        try:
            config_path.write_text(text, encoding="utf-8")
        except OSError as exc:
            return jsonify({"ok": False, "error": f"写入 pipeline.toml 失败：{exc}"}), 500

        with state.lock:
            _reload_config_locked(state)
            ok = state.config is not None
            err = state.config_error
        return jsonify({"ok": ok, "error": err})

    @app.get("/api/input")
    def api_get_input():
        with state.lock:
            cfg = state.config
        if cfg is None:
            return jsonify({"ok": False, "error": "配置未就绪，无法读取输入文件"}), 409
        return jsonify(
            {
                "ok": True,
                "path": str(cfg.input_path),
                "text": _read_text(cfg.input_path, max_chars=200_000),
            }
        )

    @app.put("/api/input")
    def api_put_input():
        payload = request.get_json(silent=True) or {}
        text = payload.get("text")
        if not isinstance(text, str):
            return jsonify({"ok": False, "error": "请求体必须是 JSON，且包含字符串字段 text"}), 400

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return (
                    jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法保存输入"}),
                    409,
                )
            cfg = state.config
            root_dir = state.root_dir

        if cfg is None:
            return jsonify({"ok": False, "error": "配置未就绪，无法保存输入"}), 409
        if not _is_within_dir(cfg.input_path, root_dir):
            return jsonify({"ok": False, "error": f"出于安全考虑，禁止写入项目目录外的文件：{cfg.input_path}"}), 403

        try:
            cfg.input_path.write_text(text, encoding="utf-8")
        except OSError as exc:
            return jsonify({"ok": False, "error": f"写入失败：{exc}"}), 500

        return jsonify({"ok": True})

    @app.post("/api/ui/pipeline")
    def api_set_ui_pipeline():
        payload = request.get_json(silent=True) or {}
        lines = payload.get("stages")
        if not isinstance(lines, list) or not all(isinstance(x, str) for x in lines):
            return jsonify({"ok": False, "error": "stages 必须是字符串数组"}), 400

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return (
                    jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法修改流水线"}),
                    409,
                )

        invocations, msg = _parse_pipeline_lines([x.strip() for x in lines if x.strip()])
        if invocations is None:
            with state.lock:
                state.ui_pipeline_error = msg
            return jsonify({"ok": False, "error": msg}), 400

        with state.lock:
            state.ui_invocations = invocations
            state.ui_pipeline_lines = [x.strip() for x in lines if x.strip()]
            state.ui_pipeline_error = None

            # 流水线变化会影响 stdin_path，保守重置。
            state.run_paths = None
            state.next_step_index = 1
            state.stdin_path = None
            state.last_step_result = None
            state.last_step_error = None
            state.running_stage_id = None
            state.running_pid = None
            state.running_mailbox_pid = None
            state.running_output_path = None

        return jsonify({"ok": True})

    @app.get("/api/ui/stage-args")
    def api_get_ui_stage_args():
        with state.lock:
            return jsonify({"ok": True, "stage_args": state.ui_stage_args})

    @app.post("/api/ui/stage-args")
    def api_set_ui_stage_args():
        payload = request.get_json(silent=True) or {}
        stage_id = payload.get("stage_id")
        args = payload.get("args")
        if not isinstance(stage_id, str) or not stage_id.strip():
            return jsonify({"ok": False, "error": "stage_id 必须是非空字符串"}), 400
        sid = stage_id.strip()

        cleaned_args: Optional[dict[str, Any]]
        if args is None:
            cleaned_args = None
        else:
            if not isinstance(args, dict):
                return jsonify({"ok": False, "error": "args 必须是对象（dict）或 null"}), 400
            cleaned_args = {}
            for k, v in args.items():
                if not isinstance(k, str) or not k.strip():
                    return jsonify({"ok": False, "error": f"stage_args.{sid} 存在非法 key"}), 400
                if v is None:
                    continue
                cleaned_args[k.strip()] = v
            try:
                _build_argv_from_stage_args(sid, cleaned_args)
            except ValueError as exc:
                return jsonify({"ok": False, "error": str(exc)}), 400

        with state.lock:
            if state.running:
                stage = state.running_stage_id or "-"
                return (
                    jsonify({"ok": False, "error": f"当前 Stage 仍在运行（{stage}），无法修改参数"}),
                    409,
                )
            if cleaned_args is None or not cleaned_args:
                state.ui_stage_args.pop(sid, None)
            else:
                state.ui_stage_args[sid] = cleaned_args

            # 参数变化会影响输出与 stdin_path，保守重置。
            state.run_paths = None
            state.next_step_index = 1
            state.stdin_path = None
            state.last_step_result = None
            state.last_step_error = None
            state.running_stage_id = None
            state.running_pid = None
            state.running_mailbox_pid = None
            state.running_output_path = None

        return jsonify({"ok": True})

    @app.post("/api/ui/mode")
    def api_set_ui_mode():
        payload = request.get_json(silent=True) or {}
        mode = payload.get("mode")
        if not isinstance(mode, str):
            return jsonify({"ok": False, "error": "mode 必须是字符串"}), 400
        mode = mode.strip()
        if mode not in SUPPORTED_MODES:
            return jsonify({"ok": False, "error": f"不支持的 mode：{mode}"}), 400

        with state.lock:
            if state.running:
                return jsonify({"ok": False, "error": "当前 Stage 仍在运行，无法切换 mode"}), 409
            state.ui_mode = mode
            # 通信方式变化会影响运行环境，保守重置。
            state.run_paths = None
            state.next_step_index = 1
            state.stdin_path = None
            state.last_step_result = None
            state.last_step_error = None
            state.running_stage_id = None
            state.running_pid = None
            state.running_mailbox_pid = None
            state.running_output_path = None

        return jsonify({"ok": True})

    @app.post("/api/run/reset")
    def api_run_reset():
        with state.lock:
            ok, msg = _reset_run_locked(state)
        code = 200 if ok else 409
        return jsonify({"ok": ok, "error": None if ok else msg}), code

    @app.post("/api/run/step")
    def api_run_step():
        with state.lock:
            ok, msg = _start_step_thread(state)
        code = 200 if ok else 409
        return jsonify({"ok": ok, "error": None if ok else msg}), code

    @app.post("/api/run/signal")
    def api_run_signal():
        payload = request.get_json(silent=True) or {}
        target = payload.get("target")
        sig_name = payload.get("sig")

        if target not in ("stage", "mailbox"):
            return jsonify({"ok": False, "error": "target 必须是 stage 或 mailbox"}), 400
        if sig_name not in ("STOP", "CONT", "TERM", "KILL"):
            return jsonify({"ok": False, "error": "sig 必须是 STOP/CONT/TERM/KILL"}), 400

        with state.lock:
            pid = state.running_pid if target == "stage" else state.running_mailbox_pid

        if pid is None:
            return jsonify({"ok": False, "error": f"当前没有可控制的 {target} 进程"}), 409

        sig_map = {
            "STOP": signal.SIGSTOP,
            "CONT": signal.SIGCONT,
            "TERM": signal.SIGTERM,
            "KILL": signal.SIGKILL,
        }
        try:
            os.kill(pid, sig_map[sig_name])
        except ProcessLookupError:
            return jsonify({"ok": False, "error": "进程不存在（可能已退出）"}), 409
        except PermissionError as exc:
            return jsonify({"ok": False, "error": f"发送信号失败：{exc}"}), 500
        return jsonify({"ok": True})

    @app.get("/api/status")
    def api_status():
        specs = get_stage_specs()

        with state.lock:
            cfg = state.config
            config_error = state.config_error
            ui_mode = state.ui_mode
            ui_pipeline_error = state.ui_pipeline_error
            invocations = list(state.ui_invocations)
            ui_stage_args = {k: dict(v) for k, v in state.ui_stage_args.items()}
            run_paths = state.run_paths
            next_step_index = state.next_step_index
            stdin_path = state.stdin_path

            running = state.running
            running_stage_id = state.running_stage_id
            running_pid = state.running_pid
            running_mailbox_pid = state.running_mailbox_pid
            running_output_path = state.running_output_path

            last_step_result = state.last_step_result
            last_step_error = state.last_step_error

        server_info = _proc_to_dict(procfs.read_proc_info(os.getpid()))
        stage_info = _proc_to_dict(procfs.read_proc_info(running_pid)) if running_pid is not None else {"available": False}
        mailbox_info = (
            _proc_to_dict(procfs.read_proc_info(running_mailbox_pid))
            if running_mailbox_pid is not None
            else {"available": False}
        )

        input_path_str = ""
        if cfg is not None:
            input_path_str = str(cfg.input_path)
        output_path_str = ""
        path_to_show: Optional[Path] = None
        if running_output_path is not None:
            path_to_show = running_output_path
        elif last_step_result is not None:
            try:
                path_to_show = Path(last_step_result.get("output_path", ""))
            except Exception:
                path_to_show = None

        if path_to_show is not None and str(path_to_show):
            output_path_str = str(path_to_show)

        finished = (not running) and (next_step_index > len(invocations)) and bool(invocations)

        return jsonify(
            {
                "ok": True,
                "config": {
                    "path": str(state.config_path),
                    "ok": cfg is not None,
                    "error": config_error,
                    "input_path": input_path_str,
                    "outputs_dir": str(cfg.outputs_dir) if cfg is not None else "",
                    "default_topn": cfg.default_topn if cfg is not None else None,
                    "preview_lines": cfg.preview_lines if cfg is not None else None,
                    "clear_screen_each_step": cfg.clear_screen_each_step if cfg is not None else None,
                },
                "ui": {
                    "mode": ui_mode,
                    "pipeline_error": ui_pipeline_error,
                    "pipeline": [_invocation_to_dict(x, specs=specs) for x in invocations],
                    "stage_args": ui_stage_args,
                },
                "run": {
                    "paths": {
                        "run_id": run_paths.run_id if run_paths is not None else "",
                        "steps_dir": str(run_paths.steps_dir) if run_paths is not None else "",
                        "report_path": str(run_paths.report_path) if run_paths is not None else "",
                        "log_path": str(run_paths.log_path) if run_paths is not None else "",
                    },
                    "next_step_index": next_step_index,
                    "total_steps": len(invocations),
                    "stdin_path": str(stdin_path) if stdin_path is not None else "",
                    "running": running,
                    "running_stage_id": running_stage_id or "",
                    "running_pid": running_pid,
                    "running_mailbox_pid": running_mailbox_pid,
                    "running_output_path": str(running_output_path) if running_output_path is not None else "",
                    "finished": finished,
                    "last_step_result": last_step_result,
                    "last_step_error": last_step_error,
                },
                "proc": {
                    "server": server_info,
                    "stage": stage_info,
                    "mailbox": mailbox_info,
                },
                "data": {
                    "input_path": input_path_str,
                    "output_path": output_path_str,
                },
            }
        )

    @app.get("/api/content")
    def api_content():
        with state.lock:
            run_paths = state.run_paths
            running_output_path = state.running_output_path
            last_step_result = state.last_step_result

        log_tail = ""
        report_excerpt = ""
        log_path_str = ""
        report_path_str = ""
        if run_paths is not None:
            log_path_str = str(run_paths.log_path)
            report_path_str = str(run_paths.report_path)
            log_tail = _tail_text(run_paths.log_path, max_bytes=20_000)
            report_excerpt = _read_text(run_paths.report_path, max_chars=20_000)

        output_excerpt = ""
        output_path_str = ""
        path_to_show: Optional[Path] = None
        if running_output_path is not None:
            path_to_show = running_output_path
        elif last_step_result is not None:
            try:
                path_to_show = Path(last_step_result.get("output_path", ""))
            except Exception:
                path_to_show = None

        if path_to_show is not None and str(path_to_show):
            output_path_str = str(path_to_show)
            output_excerpt = _read_text(path_to_show, max_chars=40_000)

        return jsonify(
            {
                "ok": True,
                "output_path": output_path_str,
                "output_excerpt": output_excerpt,
                "log_path": log_path_str,
                "log_tail": log_tail,
                "report_path": report_path_str,
                "report_excerpt": report_excerpt,
            }
        )

    return app


def main() -> int:
    root = _project_root()
    state = AppState(
        root_dir=root,
        config_path=(root / "pipeline.toml").resolve(),
    )
    with state.lock:
        _reload_config_locked(state)

    app = create_app(state)
    # threaded=True：允许 UI 轮询状态的同时触发后台 step（不阻塞整个服务）
    app.run(host="127.0.0.1", port=8000, debug=False, threaded=True)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
