#!/usr/bin/env python3
"""模拟 OpenCode 在 Windows 上的实际行为（GBK 解码）"""
import json
import subprocess
import sys

def main():
    # 模拟 OpenCode：不指定 encoding，让 Windows 使用默认的 GBK
    proc = subprocess.Popen(
        [sys.executable, "-m", "szyjiyi", "--project-dir", r"D:\Szy_Augmen_Tools\Szy-jiyimemory"],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        text=True,
        # 故意不指定 encoding，让系统使用默认编码（Windows 上是 GBK）
        bufsize=1
    )
    
    try:
        # 1. Initialize
        init_msg = {"jsonrpc": "2.0", "id": 1, "method": "initialize", 
                    "params": {"protocolVersion": "2024-11-05", "capabilities": {}, 
                              "clientInfo": {"name": "opencode", "version": "1.0"}}}
        proc.stdin.write(json.dumps(init_msg) + "\n")
        proc.stdin.flush()
        
        line = proc.stdout.readline()
        resp = json.loads(line)
        print(f"[OK] Initialize: {resp['result']['serverInfo']}")
        
        # 2. List tools (这里会返回包含中文的工具描述)
        tools_msg = {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
        proc.stdin.write(json.dumps(tools_msg) + "\n")
        proc.stdin.flush()
        
        line = proc.stdout.readline()
        resp = json.loads(line)
        tools = resp['result']['tools']
        print(f"[OK] Tools list: {len(tools)} tools loaded")
        
        # 验证中文描述被正确转义
        remember_tool = next(t for t in tools if t['name'] == 'remember')
        desc = remember_tool['description']
        print(f"[OK] Tool description (first 50 chars): {desc[:50]}")
        
        # 3. Call status
        status_msg = {"jsonrpc": "2.0", "id": 3, "method": "tools/call",
                     "params": {"name": "status", "arguments": {}}}
        proc.stdin.write(json.dumps(status_msg) + "\n")
        proc.stdin.flush()
        
        line = proc.stdout.readline()
        resp = json.loads(line)
        print(f"[OK] Status call: success={json.loads(resp['result']['content'][0]['text'])['success']}")
        
        print("\n[SUCCESS] szyjiyi MCP 在 GBK 环境下工作正常！")
        print("          修复方案：使用 ensure_ascii=True 输出纯 ASCII JSON")
        return 0
        
    except UnicodeDecodeError as e:
        print(f"\n[FAIL] 编码错误 - {e}")
        print("       这意味着服务器输出了非 ASCII 字符，但客户端用 GBK 解码失败")
        return 1
    except Exception as e:
        print(f"\n[FAIL] {type(e).__name__}: {e}")
        return 1
    finally:
        proc.terminate()
        proc.wait(timeout=2)

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