#!/usr/bin/env python3
"""
Shell Bot 诊断脚本
用于检测和修复 shell bot 幻觉问题
"""
import sys
import os
from pathlib import Path

# Add project root to path
sys.path.append(str(Path(__file__).parent.parent))

from slack_bot.shell.manager import ShellManager
from slack_bot.context.storage import ContextStorage


def test_shell_session(channel_id: str = "TEST_DIAGNOSTIC") -> None:
    """测试 shell session 是否正常工作"""
    print("🔍 Testing Shell Session...")

    manager = ShellManager()
    session = manager.get_session(channel_id)

    # Test basic command
    result = session.execute("pwd", timeout=2.0)
    print(f"✅ PWD Command: {result[:100]}")

    # Test Desktop listing
    result = session.execute("ls -F ~/Desktop", timeout=2.0)
    print(f"✅ Desktop Listing:\n{result}")

    # Clean up
    manager.close_session(channel_id)
    print("✅ Shell session test passed\n")


def check_context_health(channel_id: str) -> None:
    """检查对话历史健康状况"""
    print(f"🔍 Checking Context Health for {channel_id}...")

    storage = ContextStorage(channel_id)
    context = storage.get_context()

    print(f"📊 Total messages: {len(context)}")

    if len(context) == 0:
        print("✅ Context is clean (empty)\n")
        return

    # Check for suspicious keywords
    suspicious_keywords = ["Cursor.app", "Windsurf.app"]
    found_issues = []

    for i, msg in enumerate(context):
        content = msg.get("content", "")
        for keyword in suspicious_keywords:
            if keyword in content:
                found_issues.append((i, keyword, content[:200]))

    if found_issues:
        print(f"⚠️  Found {len(found_issues)} suspicious messages:")
        for idx, keyword, preview in found_issues:
            print(f"   Message {idx}: Contains '{keyword}'")
            print(f"   Preview: {preview}...")
        print("\n💡 Recommendation: Clear or backup this context")
    else:
        print("✅ No suspicious keywords found\n")


def backup_and_clear_context(channel_id: str) -> None:
    """备份并清空对话历史"""
    from datetime import datetime
    import shutil

    print(f"🔄 Backing up and clearing context for {channel_id}...")

    storage = ContextStorage(channel_id)

    if not storage.file_path.exists():
        print("✅ Context file doesn't exist, nothing to clear\n")
        return

    # Backup
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    backup_path = storage.file_path.parent / f"{channel_id}.backup_{timestamp}.json"

    shutil.copy(storage.file_path, backup_path)
    print(f"✅ Backed up to: {backup_path}")

    # Clear
    storage.clear()
    print(f"✅ Context cleared\n")


def main():
    """主诊断流程"""
    print("=" * 60)
    print("Shell Bot Diagnostic Tool")
    print("=" * 60 + "\n")

    # Test shell session
    test_shell_session()

    # Check production context
    prod_channel = "D0AAG5UKRC2"
    check_context_health(prod_channel)

    # Ask user if they want to clear
    print("=" * 60)
    print("Do you want to backup and clear the context?")
    response = input("Type 'yes' to proceed: ")

    if response.lower() in ['yes', 'y']:
        backup_and_clear_context(prod_channel)
        print("✅ Context has been cleared. Please restart shell bot.")
    else:
        print("ℹ️  Skipping context clear.")

    print("\n" + "=" * 60)
    print("Diagnostic complete!")
    print("=" * 60)


if __name__ == "__main__":
    main()
