# 用法：
#   本文件是库模块，不直接运行。
#   父进程入口：python "src/main.py"
#
# 说明：
#   - 读取并解析项目根目录的 TOML 配置文件（默认：pipeline.toml）。
#   - 所有“可配置项”（流水线、通信方式、输入输出等）统一从配置文件读取。
#   - 解析后会做链路合法性校验（数据类型兼容/Stage 是否存在等），避免运行时才失败。

from __future__ import annotations

import shlex
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional

import tomllib

from pipeline_runner import SUPPORTED_MODES, StageInvocation, validate_chain


@dataclass(frozen=True)
class RunConfig:
    config_path: Path
    input_path: Path
    mode: str
    outputs_dir: Path
    default_topn: int
    preview_lines: int
    clear_screen_each_step: bool
    # pipeline.stages 原始字符串（用于 UI 展示/写回；不保证包含 stage_args 注入后的参数）
    pipeline_stage_lines: list[str]
    # stage_args：从配置文件读取的结构化参数表（stage_id -> {key: value}）
    stage_args: dict[str, dict[str, Any]]
    invocations: list[StageInvocation]


def _format_config_error(config_path: Path, message: str) -> str:
    return f"配置错误：{config_path}：{message}"


def _require_dict(obj: Any, path: str) -> dict[str, Any]:
    if obj is None:
        raise ValueError(f"{path} 缺失")
    if not isinstance(obj, dict):
        raise ValueError(f"{path} 必须是 table（对象）")
    return obj


def _require_str(obj: Any, path: str) -> str:
    if obj is None:
        raise ValueError(f"{path} 缺失")
    if not isinstance(obj, str) or not obj.strip():
        raise ValueError(f"{path} 必须是非空字符串")
    return obj.strip()


def _require_int(obj: Any, path: str) -> int:
    if obj is None:
        raise ValueError(f"{path} 缺失")
    # TOML 中 bool 是 int 的子类，这里要排除。
    if isinstance(obj, bool) or not isinstance(obj, int):
        raise ValueError(f"{path} 必须是整数")
    return int(obj)


def _require_bool(obj: Any, path: str) -> bool:
    if obj is None:
        raise ValueError(f"{path} 缺失")
    if not isinstance(obj, bool):
        raise ValueError(f"{path} 必须是布尔值（true/false）")
    return bool(obj)


def _require_list_of_str(obj: Any, path: str) -> list[str]:
    if obj is None:
        raise ValueError(f"{path} 缺失")
    if not isinstance(obj, list):
        raise ValueError(f"{path} 必须是数组（list）")
    out: list[str] = []
    for i, item in enumerate(obj):
        if not isinstance(item, str) or not item.strip():
            raise ValueError(f"{path}[{i}] 必须是非空字符串")
        out.append(item.strip())
    return out


def _flatten_stage_args_tree(tree: dict[str, Any]) -> dict[str, dict[str, Any]]:
    """
    将 stage_args 的嵌套 table 展平为 {stage_id: args_dict}。

    允许两种写法：
    - [stage_args.token.len_range]  # 推荐（与 stage_id 的点号层级一致）
    - [stage_args]
      "token.len_range" = { min_len = 3, max_len = 12 }  # 也可
    """

    out: dict[str, dict[str, Any]] = {}

    def walk(prefix: str, node: Any) -> None:
        if not isinstance(node, dict):
            raise ValueError("stage_args 必须由 table 组成")

        # 若子节点全是 dict，认为是“分组节点”，继续向下。
        if node and all(isinstance(v, dict) for v in node.values()):
            for k, v in node.items():
                if not isinstance(k, str) or not k.strip():
                    raise ValueError("stage_args 的 key 必须是非空字符串")
                walk(prefix + k.strip() + ".", v)
            return

        # 否则视为“某个 stage_id 的参数表”（叶子节点）。
        stage_id = prefix[:-1] if prefix.endswith(".") else prefix
        if not stage_id:
            raise ValueError("stage_args 需要至少一层 stage_id，例如 [stage_args.token.len_range]")
        out[stage_id] = node

    for key, value in tree.items():
        if not isinstance(key, str) or not key.strip():
            raise ValueError("stage_args 的 key 必须是非空字符串")
        walk(key.strip() + ".", value)

    return out


def _build_argv_from_stage_args(stage_id: str, args: dict[str, Any]) -> list[str]:
    """
    将结构化参数 {min_len: 3, max_len: 12} 转成 CLI argv：["--min-len","3","--max-len","12"]。
    """

    argv: list[str] = []

    def flag_of(key: str) -> str:
        return "--" + key.replace("_", "-")

    # stage 特定校验（KISS：只做当前明确需要的 token.len_range）
    if stage_id == "token.len_range":
        min_raw = args.get("min_len")
        max_raw = args.get("max_len")
        if min_raw is not None:
            if isinstance(min_raw, bool) or not isinstance(min_raw, int):
                raise ValueError("stage_args.token.len_range.min_len 必须是整数")
            if min_raw < 0:
                raise ValueError("stage_args.token.len_range.min_len 不能为负数")
        if max_raw is not None:
            if isinstance(max_raw, bool) or not isinstance(max_raw, int):
                raise ValueError("stage_args.token.len_range.max_len 必须是整数")
            if max_raw < 0:
                raise ValueError("stage_args.token.len_range.max_len 不能为负数")
        if isinstance(min_raw, int) and isinstance(max_raw, int) and min_raw > max_raw:
            raise ValueError("stage_args.token.len_range.min_len 不能大于 max_len")

    for key in sorted(args.keys()):
        value = args[key]
        if not isinstance(key, str) or not key.strip():
            raise ValueError(f"stage_args.{stage_id} 存在非法 key")
        k = key.strip()
        if value is None:
            continue
        if isinstance(value, bool):
            # 约定：bool=True 表示启用该 flag；False 视为不传（保持简单、可预期）。
            if value:
                argv.append(flag_of(k))
            continue
        if isinstance(value, int) and not isinstance(value, bool):
            argv.extend([flag_of(k), str(value)])
            continue
        if isinstance(value, float):
            argv.extend([flag_of(k), str(value)])
            continue
        if isinstance(value, str):
            argv.extend([flag_of(k), value])
            continue
        raise ValueError(
            f"stage_args.{stage_id}.{k} 类型不支持：{type(value).__name__}（仅支持 int/float/bool/str）"
        )

    return argv


def load_config(config_path: Path) -> tuple[Optional[RunConfig], str]:
    """
    读取并解析配置文件。
    返回 (RunConfig|None, message)；失败时 RunConfig 为 None。
    """
    try:
        with config_path.open("rb") as f:
            data = tomllib.load(f)
    except FileNotFoundError:
        return None, _format_config_error(config_path, "文件不存在")
    except tomllib.TOMLDecodeError as exc:
        return None, _format_config_error(config_path, f"TOML 解析失败：{exc}")
    except OSError as exc:
        return None, _format_config_error(config_path, f"读取失败：{exc}")

    try:
        input_table = _require_dict(data.get("input"), "[input]")
        run_table = _require_dict(data.get("run"), "[run]")
        pipeline_table = _require_dict(data.get("pipeline"), "[pipeline]")

        input_path_raw = _require_str(input_table.get("path"), "input.path")
        mode = _require_str(run_table.get("mode"), "run.mode")
        outputs_dir_raw = _require_str(run_table.get("outputs_dir"), "run.outputs_dir")
        default_topn = _require_int(run_table.get("default_topn"), "run.default_topn")
        preview_lines_raw = run_table.get("preview_lines")
        clear_screen_raw = run_table.get("clear_screen_each_step")
        stage_lines = _require_list_of_str(pipeline_table.get("stages"), "pipeline.stages")
        stage_args_raw = data.get("stage_args")

        if mode not in SUPPORTED_MODES:
            return None, _format_config_error(
                config_path,
                f"run.mode 不支持：{mode}（可选：{', '.join(SUPPORTED_MODES)}）",
            )
        if default_topn < 0:
            return None, _format_config_error(config_path, "run.default_topn 不能为负数")

        preview_lines = 10
        if preview_lines_raw is not None:
            preview_lines = _require_int(preview_lines_raw, "run.preview_lines")
        if preview_lines <= 0:
            return None, _format_config_error(config_path, "run.preview_lines 必须大于 0")

        clear_screen_each_step = False
        if clear_screen_raw is not None:
            clear_screen_each_step = _require_bool(clear_screen_raw, "run.clear_screen_each_step")

        base_dir = config_path.parent
        input_path = (base_dir / input_path_raw).resolve()
        outputs_dir = (base_dir / outputs_dir_raw).resolve()

        if not input_path.exists():
            return None, _format_config_error(
                config_path,
                f"input.path 文件不存在：{input_path_raw}（解析后：{input_path}）",
            )
        if not input_path.is_file():
            return None, _format_config_error(
                config_path,
                f"input.path 必须是文件：{input_path_raw}（解析后：{input_path}）",
            )
        if outputs_dir.exists() and not outputs_dir.is_dir():
            return None, _format_config_error(
                config_path,
                f"run.outputs_dir 必须是目录：{outputs_dir_raw}（解析后：{outputs_dir}）",
            )

        stage_args: dict[str, dict[str, Any]] = {}
        if stage_args_raw is not None:
            stage_args_table = _require_dict(stage_args_raw, "[stage_args]")
            stage_args = _flatten_stage_args_tree(stage_args_table)

        invocations: list[StageInvocation] = []
        for i, line in enumerate(stage_lines):
            try:
                parts = shlex.split(line)
            except ValueError as exc:
                return None, _format_config_error(config_path, f"pipeline.stages[{i}] 参数解析失败：{exc}")
            if not parts:
                return None, _format_config_error(config_path, f"pipeline.stages[{i}] 为空")
            stage_id = parts[0]
            argv = parts[1:]
            if not argv and stage_id in stage_args:
                argv = _build_argv_from_stage_args(stage_id, stage_args[stage_id])
            invocations.append(StageInvocation(stage_id=stage_id, argv=list(argv), enabled=True))

        ok, msg = validate_chain(invocations)
        if not ok:
            return None, _format_config_error(config_path, f"流水线校验失败：{msg}")

        return (
            RunConfig(
                config_path=config_path.resolve(),
                input_path=input_path,
                mode=mode,
                outputs_dir=outputs_dir,
                default_topn=default_topn,
                preview_lines=preview_lines,
                clear_screen_each_step=clear_screen_each_step,
                pipeline_stage_lines=list(stage_lines),
                stage_args=stage_args,
                invocations=invocations,
            ),
            "OK",
        )
    except ValueError as exc:
        return None, _format_config_error(config_path, str(exc))
