#!/usr/bin/env python3
"""
JRXML 文件收集脚本
从指定目录递归查找所有 .jrxml 文件并复制到项目的 jrxml_source 目录
"""

import os
import shutil

def collect_jrxml_files(source_dir: str, target_dir: str) -> int:
    """
    递归收集所有 .jrxml 文件并复制到目标目录
    
    Args:
        source_dir: 源目录路径
        target_dir: 目标目录路径
    
    Returns:
        复制的文件数量
    """
    os.makedirs(target_dir, exist_ok=True)
    
    copied_count = 0
    skipped_count = 0
    
    print(f"开始扫描目录: {source_dir}")
    print(f"目标目录: {target_dir}")
    print("=" * 60)
    
    for root, dirs, files in os.walk(source_dir):
        for filename in files:
            if filename.lower().endswith('.jrxml'):
                source_path = os.path.join(root, filename)
                target_path = os.path.join(target_dir, filename)
                
                counter = 1
                while os.path.exists(target_path):
                    name, ext = os.path.splitext(filename)
                    target_path = os.path.join(target_dir, f"{name}_{counter}{ext}")
                    counter += 1
                
                try:
                    shutil.copy2(source_path, target_path)
                    copied_count += 1
                    print(f"[OK] {source_path} -> {os.path.basename(target_path)}")
                except Exception as e:
                    skipped_count += 1
                    print(f"[FAIL] {source_path}: {e}")
    
    print("=" * 60)
    print(f"完成！复制了 {copied_count} 个文件，跳过 {skipped_count} 个文件")
    
    return copied_count

if __name__ == "__main__":
    SOURCE_DIR = r"C:\Users\zy187\JaspersoftWorkspace\JasperReportsSamples"
    TARGET_DIR = os.path.join(os.path.dirname(__file__), "jrxml_source")
    
    if not os.path.exists(SOURCE_DIR):
        print(f"错误：源目录不存在 - {SOURCE_DIR}")
        print("请检查路径是否正确")
        exit(1)
    
    collect_jrxml_files(SOURCE_DIR, TARGET_DIR)