import os
import sys
import pyperclip

def is_python_file(path=None, content=None):
    """检查是否为 Python 文件或内容"""
    if path:
        return path.lower().endswith('.py')
    if content:
        return 'import ' in content or 'def ' in content or 'class ' in content
    return False

def read_and_prepare_file(path=None):
    # 定义桌面路径和固定文件名
    desktop = os.path.join(os.path.expanduser("~"), "Desktop")
    temp_file_path = os.path.join(desktop, "temp.py")
    
    # 如果 temp.py 已存在，删除它（下次运行前清理）
    if os.path.exists(temp_file_path):
        try:
            os.remove(temp_file_path)
            #print(f"已删除旧的 {temp_file_path}")
        except Exception as e:
            #print(f"删除旧文件 {temp_file_path} 失败: {e}")
            return None
    
    content = None
    if path and is_python_file(path):
        try:
            with open(path, 'r', encoding='utf-8') as f:
                content = f.read()
        except Exception as e:
            print(f"读取文件 {path} 失败: {e}")
            return None
    else:
        try:
            import pyperclip
            content = pyperclip.paste()
            if not is_python_file(content=content):
                print("剪贴板内容无效，未检测到 import 语句")
                return None
        except ImportError:
            print("未安装 pyperclip，无法读取剪贴板")
            return None
        except Exception as e:
            print(f"读取剪贴板失败: {e}")
            return None
    
    if not content:
        print("请提供有效的文件路径或剪贴板内容")
        return None
    
   # 写入到桌面上的 temp.py，统一换行符，使用 utf-8 编码
    try:
        content = content.replace('\r\n', '\n').replace('\n', os.linesep)
        with open(temp_file_path, 'w', encoding='utf-8', newline='') as f:
            f.write(content)
        print(temp_file_path)
        return temp_file_path
    except Exception as e:
        print(f"写入文件 {temp_file_path} 失败: {e}")
        return None

# 示例调用逻辑
def call_function_by_name(func_name):
    functions = {"read_and_prepare_file": read_and_prepare_file}
    if func_name in functions:
        # 如果有路径参数，从 sys.argv 获取
        args = sys.argv[2:] if len(sys.argv) > 2 else []
        return functions[func_name](*args)
    else:
        # print(f"未知函数: {func_name}")
        return None

if __name__ == "__main__":
    if len(sys.argv) > 1:
        call_function_by_name(sys.argv[1])
    else:
        print("请提供函数名")