#!/usr/bin/env python3
"""
搜索WecomTeam在GitHub上的仓库
"""

import subprocess
import json
import os
import sys

def search_github_repos():
    """搜索GitHub仓库"""
    print("搜索WecomTeam在GitHub上的仓库...")
    
    # 尝试使用GitHub API搜索
    search_commands = [
        # 尝试curl访问GitHub API
        "curl -s 'https://api.github.com/orgs/WecomTeam/repos' 2>/dev/null || echo 'API访问失败'",
        # 尝试搜索wecom-cli相关
        "curl -s 'https://api.github.com/search/repositories?q=wecom-cli+org:WecomTeam' 2>/dev/null || echo '搜索失败'",
        # 尝试搜索wecom openclaw相关
        "curl -s 'https://api.github.com/search/repositories?q=wecom+openclaw+org:WecomTeam' 2>/dev/null || echo '搜索失败'",
    ]
    
    results = []
    for cmd in search_commands:
        try:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=10)
            if result.stdout and "API访问失败" not in result.stdout and "搜索失败" not in result.stdout:
                try:
                    data = json.loads(result.stdout)
                    results.append(data)
                except json.JSONDecodeError:
                    pass
        except:
            pass
    
    return results

def analyze_existing_plugin():
    """分析现有插件结构"""
    print("\n分析现有wecom插件结构...")
    
    plugin_dir = "/root/.openclaw/extensions/wecom-openclaw-plugin"
    
    if os.path.exists(plugin_dir):
        print(f"插件目录: {plugin_dir}")
        
        # 列出主要文件
        for root, dirs, files in os.walk(plugin_dir):
            level = root.replace(plugin_dir, '').count(os.sep)
            indent = ' ' * 2 * level
            print(f"{indent}{os.path.basename(root)}/")
            subindent = ' ' * 2 * (level + 1)
            for file in files[:10]:  # 只显示前10个文件
                if file.endswith(('.js', '.json', '.md')):
                    print(f"{subindent}{file}")
        
        # 检查package.json
        package_json = os.path.join(plugin_dir, "package.json")
        if os.path.exists(package_json):
            with open(package_json, 'r') as f:
                try:
                    pkg = json.load(f)
                    print(f"\n插件信息:")
                    print(f"  名称: {pkg.get('name')}")
                    print(f"  版本: {pkg.get('version')}")
                    print(f"  描述: {pkg.get('description', '')[:100]}...")
                    
                    # 检查依赖
                    if 'dependencies' in pkg:
                        print(f"\n主要依赖:")
                        for dep in list(pkg['dependencies'].keys())[:5]:
                            print(f"  - {dep}")
                    
                    # 检查scripts
                    if 'scripts' in pkg:
                        print(f"\n可用命令:")
                        for script, cmd in pkg['scripts'].items():
                            print(f"  {script}: {cmd[:50]}...")
                            
                except json.JSONDecodeError as e:
                    print(f"解析package.json失败: {e}")
    else:
        print("插件目录不存在")

def check_mcp_tools():
    """检查MCP工具配置"""
    print("\n检查MCP工具配置...")
    
    # 查看skills目录
    skills_dir = "/root/.openclaw/extensions/wecom-openclaw-plugin/skills"
    if os.path.exists(skills_dir):
        skills = os.listdir(skills_dir)
        print(f"发现 {len(skills)} 个技能:")
        for skill in sorted(skills):
            skill_path = os.path.join(skills_dir, skill)
            if os.path.isdir(skill_path):
                # 检查SKILL.md
                skill_md = os.path.join(skill_path, "SKILL.md")
                if os.path.exists(skill_md):
                    with open(skill_md, 'r') as f:
                        first_line = f.readline().strip()
                        print(f"  - {skill}: {first_line[:50]}...")
                else:
                    print(f"  - {skill}: (无SKILL.md)")
    
    # 检查是否有MCP配置
    mcp_configs = []
    for root, dirs, files in os.walk("/root/.openclaw/extensions/wecom-openclaw-plugin"):
        for file in files:
            if 'mcp' in file.lower() or file.endswith('.mcp.json'):
                mcp_configs.append(os.path.join(root, file))
    
    if mcp_configs:
        print(f"\n发现MCP配置文件:")
        for config in mcp_configs:
            print(f"  - {config}")
    else:
        print("\n未发现MCP配置文件")

def suggest_next_steps():
    """建议下一步行动"""
    print("\n" + "="*60)
    print("建议下一步行动")
    print("="*60)
    
    print("""
1. ✅ 已安装的组件:
   - @wecom/wecom-openclaw-plugin (现有插件)
   - @wecom/wecom-openclaw-cli (CLI管理工具)

2. 🔍 需要获取的组件:
   - wecom-cli (命令行工具，可能包含完整的MCP Skills)
   
3. 🚀 建议操作:
   
   a) 通过npm搜索更多wecom相关包:
      npm search wecom
      
   b) 查看现有插件的GitHub仓库获取线索:
      https://github.com/WecomTeam/wecom-openclaw-plugin
      
   c) 检查现有插件是否已包含MCP Skills:
      - 查看skills目录下的wecom-smartsheet-data等技能
      - 检查是否有MCP Server实现
      
   d) 如果无法直接获取wecom-cli，考虑:
      - 基于现有插件扩展MCP功能
      - 使用企业微信官方API自行实现
      - 联系WecomTeam获取wecom-cli源码
      
4. 💡 替代方案:
   当前已部署的双插件架构（模拟版）可以正常工作。
   可以先用模拟数据测试业务流程，同时寻找真实wecom-cli。
   """)

def main():
    print("="*60)
    print("WeCom CLI源码搜索工具")
    print("="*60)
    
    # 搜索GitHub仓库
    github_results = search_github_repos()
    
    if github_results:
        print("GitHub搜索结果:")
        for result in github_results:
            if isinstance(result, list):
                for repo in result[:5]:  # 只显示前5个
                    if isinstance(repo, dict):
                        print(f"  - {repo.get('name')}: {repo.get('description', '')[:50]}...")
            elif isinstance(result, dict) and 'items' in result:
                for repo in result['items'][:5]:
                    print(f"  - {repo.get('name')}: {repo.get('description', '')[:50]}...")
    else:
        print("GitHub搜索失败或网络受限")
    
    # 分析现有插件
    analyze_existing_plugin()
    
    # 检查MCP工具
    check_mcp_tools()
    
    # 建议下一步
    suggest_next_steps()

if __name__ == "__main__":
    main()