#!/usr/bin/env python3
"""
Integration test for the Kimi Copilot brain.

Constructs a mock Kimi Code CLI session where Kimi gives bad advice,
triggers the side model, and verifies that the RAG write path works.
"""

import shutil
import sys
import os

# Make sure we import from the project root.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from brain import Brain


def build_mock_session() -> Brain:
    brain = Brain("config.yaml")

    # Simulate a user asking for file reading advice.
    brain.feed_user_input("帮我写一个 Python 函数，读取当前目录下的 config.yaml\n")

    # Simulate Kimi giving a brittle answer.
    brain.feed_kimi_output("你可以直接用 open('config.yaml').read()，简单高效。\n")

    # Simulate the tool output showing that the code failed.
    brain.feed_tool_output(
        "Traceback (most recent call last):\n"
        "  File '<stdin>', line 1, in <module>\n"
        "FileNotFoundError: [Errno 2] No such file or directory: 'config.yaml'\n"
    )

    return brain


def main():
    panel_path = "panel.json"
    backup_path = "panel.json.test_brain_backup"

    # Use a clean panel so existing RAG entries do not deduplicate the test write.
    if os.path.exists(panel_path):
        shutil.move(panel_path, backup_path)
    try:
        print("== Building mock session ==")
        brain = build_mock_session()

        print("\n== Session history ==")
        for msg in brain.history:
            print(f"[{msg['role']}] {msg['content'][:80]}...")

        print("\n== Trigger and side-model invocation happen automatically ==")
        print("If you see RAG write OK above, the loop is closed.\n")

        print("\n== Done ==")
    finally:
        if os.path.exists(backup_path):
            shutil.move(backup_path, panel_path)


if __name__ == "__main__":
    main()
