#!/usr/bin/env python3
"""
Integration test for the real-time scan feature.

Constructs two mock sessions:
1. A normal conversation that should not trigger deep analysis.
2. A problematic conversation that should be caught by the qwen scan.

Because the scan calls the real local qwen model, this test may take
several seconds and requires the model endpoint to be reachable.
"""

import sys
import os
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from brain import Brain


def test_normal_conversation():
    print("\n== Test 1: normal conversation should not trigger deep analysis ==")
    brain = Brain("config.yaml")
    # Use a very short cooldown so the test does not wait long.
    brain.config["copilot"]["real_time_scan"]["cooldown_seconds"] = 0.5
    brain.config["copilot"]["trigger_cooldown_seconds"] = 0.5

    brain.feed_user_input("你好，今天天气怎么样？\n")
    brain.feed_kimi_output("你好！我无法获取实时天气，建议你查看天气应用。\n")

    # Give the background scan a moment to complete.
    time.sleep(2)
    print("History:")
    for msg in brain.history:
        print(f"  [{msg['role']}] {msg['content'][:60]}...")


def test_problematic_conversation():
    print("\n== Test 2: problematic code should be caught by scan ==")
    brain = Brain("config.yaml")
    brain.config["copilot"]["real_time_scan"]["cooldown_seconds"] = 0.5
    brain.config["copilot"]["trigger_cooldown_seconds"] = 0.5

    brain.feed_user_input("帮我写一个读取 config.yaml 的 Python 函数\n")
    # Kimi gives brittle advice.
    brain.feed_kimi_output("你可以直接用 open('config.yaml').read()，简单高效。\n")

    # Give the scan + potential deep analysis time to complete.
    time.sleep(8)
    print("History:")
    for msg in brain.history:
        print(f"  [{msg['role']}] {msg['content'][:60]}...")


def main():
    print("== Real-time scan integration test ==")
    print("This test calls the real local qwen model. It may take ~15 seconds.\n")

    test_normal_conversation()
    test_problematic_conversation()

    print("\n== Test complete ==")
    print("Check kimi-copilot.log for scan results and trigger details.")


if __name__ == "__main__":
    main()
