#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
源码链接生成器
用于在Obsidian笔记中生成AOSP源码的链接
"""

import re
import os
from pathlib import Path

# AOSP源码基础URL
AOSP_BASE_URL = "https://cs.android.com/android/platform/superproject/+/master:"

# 常见源码路径映射
SOURCE_PATH_MAP = {
    "Activity.java": "frameworks/base/core/java/android/app/Activity.java",
    "ActivityManagerService.java": "frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java",
    "ActivityThread.java": "frameworks/base/core/java/android/app/ActivityThread.java",
    "Binder.java": "frameworks/base/core/java/android/os/Binder.java",
    "Handler.java": "frameworks/base/core/java/android/os/Handler.java",
    "Looper.java": "frameworks/base/core/java/android/os/Looper.java",
    "MessageQueue.java": "frameworks/base/core/java/android/os/MessageQueue.java",
    "WindowManagerService.java": "frameworks/base/services/core/java/com/android/server/wm/WindowManagerService.java",
    "PackageManagerService.java": "frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java",
    "SystemServer.java": "frameworks/base/services/java/com/android/server/SystemServer.java",
    "ZygoteInit.java": "frameworks/base/core/java/com/android/internal/os/ZygoteInit.java",
    "Choreographer.java": "frameworks/base/core/java/android/view/Choreographer.java",
    "binder.c": "drivers/android/binder.c",
    "init.cpp": "system/core/init/init.cpp",
}

def generate_source_link(file_name, line_number=None, branch="master"):
    """
    生成源码链接
    
    Args:
        file_name: 源码文件名
        line_number: 行号（可选）
        branch: 分支名，默认master
    
    Returns:
        生成的链接字符串
    """
    # 查找文件路径
    file_path = SOURCE_PATH_MAP.get(file_name)
    
    if not file_path:
        # 如果不在映射中，尝试直接使用文件名
        file_path = file_name
    
    # 构建URL
    url = f"{AOSP_BASE_URL}{file_path}"
    
    if line_number:
        url += f";l={line_number}"
    
    # 生成Markdown链接
    link_text = file_name
    if line_number:
        link_text += f":{line_number}"
    
    return f"[{link_text}]({url})"

def generate_source_code_block(file_name, start_line=None, end_line=None):
    """
    生成源码代码块链接
    
    Args:
        file_name: 源码文件名
        start_line: 起始行号
        end_line: 结束行号
    
    Returns:
        生成的代码块链接
    """
    file_path = SOURCE_PATH_MAP.get(file_name, file_name)
    
    url = f"{AOSP_BASE_URL}{file_path}"
    
    if start_line and end_line:
        url += f";l={start_line}-{end_line}"
    elif start_line:
        url += f";l={start_line}"
    
    link_text = f"{file_name}"
    if start_line and end_line:
        link_text += f" ({start_line}-{end_line})"
    elif start_line:
        link_text += f" ({start_line})"
    
    return f"[{link_text}]({url})"

def parse_note_for_source_links(note_path):
    """
    解析笔记文件，查找源码引用并生成链接
    
    Args:
        note_path: 笔记文件路径
    
    Returns:
        处理后的内容
    """
    with open(note_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 匹配源码引用模式，如：Activity.java:100 或 Activity.java(100-200)
    pattern1 = r'(\w+\.java|\w+\.cpp|\w+\.c):(\d+)'
    pattern2 = r'(\w+\.java|\w+\.cpp|\w+\.c)\((\d+)-(\d+)\)'
    
    def replace_link1(match):
        file_name = match.group(1)
        line_number = int(match.group(2))
        return generate_source_link(file_name, line_number)
    
    def replace_link2(match):
        file_name = match.group(1)
        start_line = int(match.group(2))
        end_line = int(match.group(3))
        return generate_source_code_block(file_name, start_line, end_line)
    
    # 替换匹配的内容
    content = re.sub(pattern1, replace_link1, content)
    content = re.sub(pattern2, replace_link2, content)
    
    return content

def main():
    """主函数"""
    import sys
    
    if len(sys.argv) < 2:
        print("Usage: python 源码链接生成器.py <file_name> [line_number]")
        print("   or: python 源码链接生成器.py <note_path>")
        sys.exit(1)
    
    if sys.argv[1].endswith('.md'):
        # 处理笔记文件
        note_path = sys.argv[1]
        if not os.path.exists(note_path):
            print(f"Error: File not found: {note_path}")
            sys.exit(1)
        
        new_content = parse_note_for_source_links(note_path)
        
        # 输出处理后的内容
        print(new_content)
        
        # 可选：保存到文件
        if len(sys.argv) > 2 and sys.argv[2] == '--save':
            output_path = note_path.replace('.md', '_with_links.md')
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"\nSaved to: {output_path}")
    else:
        # 生成单个链接
        file_name = sys.argv[1]
        line_number = int(sys.argv[2]) if len(sys.argv) > 2 else None
        
        link = generate_source_link(file_name, line_number)
        print(link)

if __name__ == "__main__":
    main()
