#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
文件过滤工具
提供文件过滤功能，跳过未完成的workflow文件
"""

import os
from pathlib import Path
from typing import List, Set


def load_incomplete_files(output_dir: str) -> Set[str]:
    """
    加载未完成文件列表
    
    Args:
        output_dir: 输出目录路径
        
    Returns:
        未完成文件名的集合
    """
    incomplete_files = set()
    incomplete_file_path = Path(output_dir) / "incomplete_files.txt"
    
    if incomplete_file_path.exists():
        try:
            with open(incomplete_file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    filename = line.strip()
                    if filename:
                        incomplete_files.add(filename)
        except Exception as e:
            print(f"警告：读取未完成文件列表时出错: {e}")
    
    return incomplete_files


def filter_complete_files(file_list: List[str], output_dir: str) -> List[str]:
    """
    过滤出完成的文件列表
    
    Args:
        file_list: 原始文件列表
        output_dir: 输出目录路径
        
    Returns:
        过滤后的完成文件列表
    """
    incomplete_files = load_incomplete_files(output_dir)
    
    if not incomplete_files:
        print("未找到不完整文件列表，将处理所有文件")
        return file_list
    
    # 过滤掉不完整的文件
    filtered_files = []
    skipped_count = 0
    
    for filepath in file_list:
        filename = os.path.basename(filepath)
        if filename in incomplete_files:
            skipped_count += 1
        else:
            filtered_files.append(filepath)
    
    if skipped_count > 0:
        print(f"已跳过 {skipped_count} 个未完成的文件")
    
    print(f"将处理 {len(filtered_files)} 个完成的文件")
    return filtered_files


def get_completeness_stats(output_dir: str) -> dict:
    """
    获取完成度统计信息
    
    Args:
        output_dir: 输出目录路径
        
    Returns:
        完成度统计字典
    """
    import json
    
    report_path = Path(output_dir) / "completeness_report.json"
    
    if report_path.exists():
        try:
            with open(report_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            print(f"警告：读取完成度报告时出错: {e}")
    
    return {
        "total_files": 0,
        "complete_files_count": 0,
        "incomplete_files_count": 0,
        "completion_rate": 0.0
    }


def print_filter_summary(output_dir: str) -> None:
    """
    打印过滤汇总信息
    
    Args:
        output_dir: 输出目录路径
    """
    stats = get_completeness_stats(output_dir)
    
    if stats["total_files"] > 0:
        print(f"\n=== 文件过滤汇总 ===")
        print(f"总文件: {stats['total_files']}")
        print(f"完成文件: {stats['complete_files_count']}")
        print(f"未完成文件: {stats['incomplete_files_count']}")
        print(f"完成率: {stats['completion_rate']:.1%}")
        print("=" * 30)