#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
临时脚本：删除 association 相关的方法
"""

# 需要删除的方法列表（方法名）
METHODS_TO_REMOVE = [
    '_is_classification',
    '_navigate_to_node',
    '_recursive_search',
    '_search_classification_path',
    'stage2_find_associations',
    '_find_associations',
    '_find_intra_dimension_associations',
    '_collect_classification_info',
    'stage3_filter_high_similarity_matches',
    '_collect_scope_from_associations',
    '_collect_stage2_scope',
    '_find_features_by_path',
]

def find_method_bounds(lines, method_name):
    """
    查找方法的起始和结束行号

    Returns:
        (start_line, end_line) 或 None
    """
    start_line = None
    indent_level = None

    # 查找方法开始
    for i, line in enumerate(lines):
        if f'def {method_name}(' in line:
            start_line = i
            # 获取方法的缩进级别
            indent_level = len(line) - len(line.lstrip())
            break

    if start_line is None:
        return None

    # 查找方法结束（下一个同级或更外层的def/class，或遇到注释分隔符）
    for i in range(start_line + 1, len(lines)):
        line = lines[i]
        stripped = line.lstrip()

        # 空行跳过
        if not stripped:
            continue

        current_indent = len(line) - len(line.lstrip())

        # 遇到 # ========== 注释分隔符
        if stripped.startswith('# =========='):
            return (start_line, i)

        # 遇到同级或更外层的def/class
        if current_indent <= indent_level and (stripped.startswith('def ') or stripped.startswith('class ')):
            return (start_line, i)

    # 如果到文件末尾都没找到
    return (start_line, len(lines))


def main():
    input_file = 'enhanced_search_v2.py'
    output_file = 'enhanced_search_v2_cleaned.py'

    # 读取文件
    with open(input_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    # 收集所有要删除的行范围
    ranges_to_remove = []

    for method_name in METHODS_TO_REMOVE:
        result = find_method_bounds(lines, method_name)
        if result:
            ranges_to_remove.append(result)
            print(f"找到方法 {method_name}: 行 {result[0]+1} - {result[1]+1}")
        else:
            print(f"未找到方法 {method_name}")

    # 按起始行排序（倒序）
    ranges_to_remove.sort(reverse=True)

    # 删除方法（从后往前删）
    for start, end in ranges_to_remove:
        print(f"删除行 {start+1} - {end}")
        del lines[start:end]

    # 写入新文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.writelines(lines)

    print(f"\n✓ 已生成清理后的文件: {output_file}")
    print(f"原文件行数: {len(open(input_file).readlines())}")
    print(f"新文件行数: {len(lines)}")


if __name__ == '__main__':
    main()
