# 可在此自定义工具
# tools/custom_tools.py
import sys
from pathlib import Path
from typing import Optional, Dict, Any

if __package__ in (None, ""):
    sys.path.insert(0, str(Path(__file__).parent.parent.parent))
    from .atomic_tools import AtomicTools
else:
    from .atomic_tools import AtomicTools


class CustomTools(AtomicTools):
    """自定义工具扩展"""

    async def analyze_code(self, file_path: str) -> Dict[str, Any]:
        """code analysis工具"""
        # 读取文件
        result = await self.read_file(file_path)
        if not result.get("success"):
            return result

        code = result["content"]

        # executecode analysis
        analysis_code = f"""
import ast
import json

code = '''{code}'''

def analyze_python_code(code_str):
    try:
        tree = ast.parse(code_str)

        analysis = {
            "functions": [],
            "classes": [],
            "imports": [],
            "complexity": 0
        }

        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                analysis["functions"].append(node.name)
            elif isinstance(node, ast.ClassDef):
                analysis["classes"].append(node.name)
            elif isinstance(node, ast.Import):
                for n in node.names:
                    analysis["imports"].append(n.name)
            elif isinstance(node, ast.ImportFrom):
                analysis["imports"].append(f"{{node.module}}.*")

        return analysis
    except Exception as e:
        return {{"error": str(e)}}

result = analyze_python_code(code)
print(json.dumps(result, indent=2))
"""

        # execute分析 - 使 with run_shellexecutePython代码
        return await self.run_shell(f"python3 -c {repr(analysis_code)}")
