#!/usr/bin/env python3
"""两个最小 AI Agent 对同一 LoomDB 盒子并发操作的集成测试。

设计
----
不依赖任何外部 LLM。两个 agent 通过**规则引擎**决策（deterministic），
但真实地起两个 Python thread，每个 thread 独立持有一份 LoomBox + bridge 子进程，
模拟真实多 Agent 对同一盒子的并发读写。

场景：修复构建失败 ——
  - Planner agent: 分析故障 → 写出任务状态 + 决策 + 依赖事实
  - Executor agent: 执行修复 → 写出观测 + 产物 + 新增事实
  - 最终 merge 并验证 LoomDB 的 CRDT 收敛

运行
----
    cd /root/moonbitLoomDB
    moon build cmd/bridge --target native --release  # 先编译 native bridge
    python3 scripts/two_agent_test.py

pytest 运行
-----------
    python3 -m pytest scripts/two_agent_test.py -v -s
"""

from __future__ import annotations

import json
import os
import shutil
import sys
import threading
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / "platform" / "sdk" / "python"))

from loomdb import LoomBox, LoomError  # noqa: E402

ROOT = REPO / ".loombox_two_agent"
TASK = "two-agent-fix-build"
BASE_TASK = "two-agent-fix-build-base"


# ============================================================================
# Agent 定义（纯规则引擎，deterministic，无需外部 LLM）
# ============================================================================


@dataclass
class AgentAction:
    """一条 Agent 要执行的 LoomDB 操作。"""

    kind: str  # "set" | "fact" | "observe" | "decide" | "artifact" | "merge"
    payload: dict[str, Any]
    note: str  # 日志友好的动作描述


class MinimalAgent:
    """一个最小 AI Agent：拿到 base 盒 → fork 独立 task → 执行计划 → 结束。"""

    def __init__(
        self,
        name: str,
        agent_id: str,
        plan: list[AgentAction],
        root: Path,
    ) -> None:
        self.name = name
        self.agent_id = agent_id
        self.plan = plan
        self.root = root
        self.box: LoomBox | None = None
        self.task_id = f"{BASE_TASK}-{name}"  # 独立 task_id，merge 时会 rewrite
        self.log: list[str] = []
        self.exception: Exception | None = None
        self._lock = threading.Lock()

    def say(self, msg: str) -> None:
        with self._lock:
            self.log.append(msg)

    def run(self, base_events_jsonl: str) -> None:
        """Agent 主循环：fork → 执行 plan → 结束。"""
        try:
            self.say(f"[start] thread={threading.current_thread().name}")

            # 1. fork：把 base 的事件（task_id=BASE_TASK）rewrite 到自己的 task_id
            #    这里通过 import_events_jsonl + 目标 task_id 让 bridge 内部自动 rewrite
            box = LoomBox.create(self.task_id, agent=self.agent_id, root=self.root)
            # 在 Python SDK 层没有直接 import_events 方法，用 merge 自己的空盒 来导入 base
            # 改用更直接的方式：用 LoomBox 的 store.save_events 保存 base events 到自己的事件文件
            box.store.save_events(self.task_id, base_events_jsonl)
            # 然后 merge_to_box 让 rewrite 生效（bridge 侧的 import_events_jsonl 会自动 rewrite）
            # 这里 box 的 events 文件是 base 的原始内容（task_id=BASE_TASK），
            # 需要触发一次 bridge 调用让 rewrite 发生。最直接：调一次 state_hash 会走 events op
            _ = box.state_hash()
            # 实际上我们直接让 bridge 的 import 路径接管：重新 open + merge 自己（noop）
            self.box = box
            self.say(f"[fork] task_id={self.task_id} state_hash={box.state_hash()[:24]}…")

            # 2. 依次执行 plan
            for action in self.plan:
                self.say(f"[act] {action.note}")
                self._execute(action)
                # 故意加点延迟制造 Lamport 时钟交错
                time.sleep(0.01)

            self.say(f"[done] total_events={self.box.state_hash()[:24]}…")

        except Exception as exc:  # noqa: BLE001
            self.exception = exc
            self.say(f"[ERR] {exc!r}")

    def _execute(self, action: AgentAction) -> None:
        assert self.box is not None
        box = self.box
        match action.kind:
            case "set":
                box.set(action.payload["field"], action.payload["value"])
            case "fact":
                box.fact(
                    action.payload["subject"],
                    action.payload["predicate"],
                    action.payload["value"],
                    source=self.agent_id,
                )
            case "observe":
                box.observe(
                    action.payload["tool"],
                    action.payload["status"],
                    action.payload["summary"],
                )
            case "decide":
                box.decide(
                    action.payload["question"],
                    action.payload["choice"],
                    action.payload["rationale"],
                )
            case "artifact":
                box.artifact(
                    action.payload["name"],
                    action.payload["uri"],
                    action.payload["content_hash"],
                )
            case _:
                raise ValueError(f"unknown action kind: {action.kind}")


def planner_plan() -> list[AgentAction]:
    """Planner 的工作：先写任务状态，再分析故障，然后记录决策。"""
    return [
        AgentAction("set", {"field": "status", "value": "analyzing"},
                    "set status=analyzing"),
        AgentAction("set", {"field": "owner", "value": "agent:planner"},
                    "claim ownership"),
        AgentAction("fact", {"subject": "build", "predicate": "tool", "value": "npm"},
                    "note build tool = npm"),
        AgentAction("fact", {"subject": "build", "predicate": "fail_reason", "value": "missing .npmrc"},
                    "record failure reason"),
        AgentAction("decide", {"question": "how to fix build",
                               "choice": "add .npmrc registry config",
                               "rationale": "CI 环境 registry 指向需要显式配置"},
                    "record fix decision"),
        AgentAction("set", {"field": "status", "value": "blocked"},
                    "set status=blocked (waiting for executor)"),
    ]


def executor_plan() -> list[AgentAction]:
    """Executor 的工作：拉任务 → 写观测 → 写产物 → 更新状态。"""
    return [
        AgentAction("observe", {"tool": "ci", "status": "fail",
                                "summary": "Exit code 127: npm not found"},
                    "observe ci failure"),
        AgentAction("observe", {"tool": "install", "status": "pass",
                                "summary": "npm install ok after PATH fix"},
                    "observe install pass"),
        AgentAction("artifact", {"name": ".npmrc", "uri": ".npmrc",
                                 "content_hash": "sha256:9f3a"},
                    "add artifact: .npmrc"),
        AgentAction("fact", {"subject": "env", "predicate": "node_path", "value": "/usr/local/bin/npm"},
                    "record node path fix"),
        AgentAction("set", {"field": "status", "value": "in_progress"},
                    "set status=in_progress"),
        AgentAction("set", {"field": "status", "value": "done"},
                    "set status=done (final)"),
    ]


# ============================================================================
# 测试断言工具
# ============================================================================


class AssertFailed(AssertionError):
    def __init__(self, msg: str) -> None:
        super().__init__(msg)


def check(cond: bool, msg: str) -> None:
    if not cond:
        raise AssertFailed(msg)


def find_field(fields: list[dict[str, Any]], name: str) -> str | None:
    for field in fields:
        if field.get("field") == name:
            return field.get("value")
    return None


def find_fact(facts: list[dict[str, Any]], subj: str, pred: str) -> str | None:
    for fact in facts:
        if fact.get("subject") == subj and fact.get("predicate") == pred:
            return fact.get("object")
    return None


# ============================================================================
# 主测试入口
# ============================================================================


def run_two_agent_scenario(root: Path) -> dict[str, Any]:
    """起两个 agent，并发执行各自 plan，merge 回来，返回验证结果。"""
    # 0. 清理 + 建 base 盒（两个 agent fork 自这里）
    shutil.rmtree(root, ignore_errors=True)
    base = LoomBox.create(BASE_TASK, agent="agent:base", root=root)
    base.set("status", "pending")
    base.fact("repo", "name", "loombot")
    base_events_jsonl = base.events()
    base_hash = base.state_hash()

    # 1. 起两个 agent 线程
    planner = MinimalAgent("planner", "agent:planner", planner_plan(), root)
    executor = MinimalAgent("executor", "agent:executor", executor_plan(), root)

    t_planner = threading.Thread(
        target=planner.run, args=(base_events_jsonl,), name="Planner", daemon=True
    )
    t_executor = threading.Thread(
        target=executor.run, args=(base_events_jsonl,), name="Executor", daemon=True
    )

    t_planner.start()
    t_executor.start()
    t_planner.join(timeout=30)
    t_executor.join(timeout=30)

    # 2. 检查两个 agent 没抛异常
    check(planner.exception is None, f"planner 抛异常: {planner.exception!r}")
    check(executor.exception is None, f"executor 抛异常: {executor.exception!r}")
    check(planner.box is not None, "planner box 未初始化")
    check(executor.box is not None, "executor box 未初始化")

    assert planner.box is not None
    assert executor.box is not None

    planner_hash_before = planner.box.state_hash()
    executor_hash_before = executor.box.state_hash()
    check(planner_hash_before != executor_hash_before,
          "两个 agent 写完后 state_hash 应该不同（各自演化）")

    # 3. merge executor → planner（跨 taskId）
    merged = planner.box.merge(executor.box)
    merged_hash = merged["stateHash"]
    events_after = merged["events"]

    # 4. 重新打开 planner 盒，确认 merge 落盘生效
    final = LoomBox.open(planner.task_id, agent="agent:planner", root=root)
    final_hash = final.state_hash()
    check(final_hash == merged_hash,
          f"落盘后 state_hash 变了：{final_hash} != {merged_hash}")

    ctx = final.context()

    # 5. 断言集 ---------------------------------------------------------

    # 5.1 基本状态
    check(final.task == planner.task_id,
          f"final task 应该是 planner 的 task_id {planner.task_id}")

    # 5.2 Lamport 裁决：最终 status 应该是 executor 最后写的 "done"（Lamport 时钟更高）
    status_value = ctx.get("status", "")
    check(status_value == "done",
          f"最终 status 应该是 done（executor 最后一次写，时钟最高），实际是 {status_value!r}")

    # 5.3 因果 & 内容：planner 写的决策 + executor 写的观测都应该出现
    decisions = ctx.get("decisions", [])
    observations = ctx.get("observations", [])
    check(len(decisions) >= 1, f"应该至少 1 个 decision，实际 {len(decisions)}")
    check(len(observations) >= 2, f"应该至少 2 个 observation，实际 {len(observations)}")

    # 5.4 fact 合并：planner 写的 build.tool = npm + executor 写的 env.node_path
    facts = ctx.get("facts", [])
    build_tool = find_fact(facts, "build", "tool")
    node_path = find_fact(facts, "env", "node_path")
    check(build_tool == "npm",
          f"build.tool 应该是 npm，实际 {build_tool!r}")
    check(node_path == "/usr/local/bin/npm",
          f"env.node_path 应该是 /usr/local/bin/npm，实际 {node_path!r}")

    # 5.5 artifact 合并
    artifacts = ctx.get("artifacts", [])
    check(len(artifacts) >= 1,
          f"应该至少 1 个 artifact（executor 的 .npmrc），实际 {len(artifacts)}")

    # 5.6 timeline 按 Lamport 有序
    timeline = final.timeline()
    check(len(timeline) >= 10,
          f"merge 后 timeline 应该 >= 10 事件，实际 {len(timeline)}")
    prev_clock = 0
    for entry in timeline:
        clock = entry.get("clock", 0)
        check(clock >= prev_clock,
              f"timeline 时钟乱序：{clock} < {prev_clock}")
        prev_clock = clock

    # 5.7 健康度：merge 后不应该有矛盾
    health = final.health()
    contradictions = health.get("contradictions", 0)
    check(contradictions == 0,
          f"merge 后 contradictions 应该是 0，实际 {contradictions}")

    # 5.8 rewrite_event_for_task 验证：把事件 JSONL 读出来，
    # 确认所有 task kind 事件的 taskId 都等于 planner.task_id
    task_kinds_with_taskId = {"task", "observation", "dep", "undep"}
    seen_violations: list[str] = []
    for line in events_after.splitlines():
        if not line.strip():
            continue
        evt = json.loads(line)
        kind = evt.get("kind", "")
        if kind in task_kinds_with_taskId:
            tid = evt.get("taskId", "")
            if tid and tid != planner.task_id:
                seen_violations.append(
                    f"  id={evt.get('id')} kind={kind} taskId={tid} (expected {planner.task_id})"
                )
        if kind == "policy":
            scope = evt.get("scope", "")
            if scope.startswith("task:") and scope != f"task:{planner.task_id}":
                seen_violations.append(
                    f"  id={evt.get('id')} kind=policy scope={scope} (expected task:{planner.task_id})"
                )
    check(
        not seen_violations,
        "rewrite_event_for_task 未生效:\n" + "\n".join(seen_violations),
    )

    # 5.9 幂等性：同一 executor box 再 merge 一次 → state_hash 不变
    merged2 = final.merge(executor.box)
    check(merged2["stateHash"] == merged_hash,
          f"merge 应该幂等：{merged2['stateHash']} != {merged_hash}")

    return {
        "base_hash": base_hash[:16],
        "planner_hash_before": planner_hash_before[:16],
        "executor_hash_before": executor_hash_before[:16],
        "merged_hash": merged_hash[:16],
        "final_hash": final_hash[:16],
        "timeline_len": len(timeline),
        "contradictions": contradictions,
        "decisions": len(decisions),
        "observations": len(observations),
        "artifacts": len(artifacts),
        "planner_log": planner.log,
        "executor_log": executor.log,
    }


# ============================================================================
# 运行 & 输出
# ============================================================================


def pretty_result(result: dict[str, Any]) -> str:
    lines = [
        "┌─ 结果 ─────────────────────────────────────────────────────",
        f"│ base_hash            = {result['base_hash']}",
        f"│ planner(before)      = {result['planner_hash_before']}",
        f"│ executor(before)     = {result['executor_hash_before']}",
        f"│ merged_hash          = {result['merged_hash']}",
        f"│ final_hash           = {result['final_hash']}",
        f"│ timeline events      = {result['timeline_len']}",
        f"│ contradictions       = {result['contradictions']}",
        f"│ decisions            = {result['decisions']}",
        f"│ observations         = {result['observations']}",
        f"│ artifacts            = {result['artifacts']}",
        "├─ Planner 日志 ─────────────────────────────────────────────",
    ]
    for line in result["planner_log"]:
        lines.append(f"│   {line}")
    lines.append("├─ Executor 日志 ────────────────────────────────────────────")
    for line in result["executor_log"]:
        lines.append(f"│   {line}")
    lines.append("└─────────────────────────────────────────────────────────────")
    return "\n".join(lines)


def main() -> int:
    root = ROOT
    print("=" * 64)
    print("  两个最小 AI Agent 对同一 LoomDB 盒子并发操作")
    print("  Planner: 分析故障 → 写决策")
    print("  Executor: 执行修复 → 写观测/产物")
    print("  → merge executor → planner → 验证收敛")
    print("=" * 64)

    try:
        result = run_two_agent_scenario(root)
    except AssertFailed as exc:
        print(f"\n❌ 测试断言失败:\n  {exc}")
        # 即使失败也打印日志帮助定位
        print(pretty_result({
            "base_hash": "?", "planner_hash_before": "?", "executor_hash_before": "?",
            "merged_hash": "?", "final_hash": "?", "timeline_len": "?",
            "contradictions": "?", "decisions": "?", "observations": "?",
            "artifacts": "?", "planner_log": [], "executor_log": [],
        }))
        return 1
    except Exception as exc:  # noqa: BLE001
        print(f"\n💥 测试崩溃: {exc!r}")
        import traceback
        traceback.print_exc()
        return 1

    print("\n" + pretty_result(result))
    print("\n✅ 全部 9 个断言通过！两 Agent 操作 + 跨 taskId merge 收敛正确。")
    return 0


# ============================================================================
# pytest 入口：让这个脚本可以直接 `python3 -m pytest -v -s two_agent_test.py`
# ============================================================================


def test_two_agents_concurrent_merge() -> None:
    """pytest 友好的入口 —— 9 个断言全部通过才算绿。"""
    result = run_two_agent_scenario(ROOT)
    assert result["contradictions"] == 0
    assert result["decisions"] >= 1
    assert result["observations"] >= 2
    assert result["timeline_len"] >= 10
    # 核心：rewrite 后 final_hash == merged_hash（落盘收敛）
    assert result["final_hash"] == result["merged_hash"]
    # 幂等：merged_hash 已在 run_two_agent_scenario 里被验证过（第 5.9 条）


if __name__ == "__main__":
    sys.exit(main())
