use std::fs::{self, File};
use std::io::Write;
use std::time::Instant;
use tempfile::TempDir;

use fast_clean::{run, Cli};

/// =======================
/// 压测参数区（可自行调整）
/// =======================
const FILE_COUNT: usize = 200_000;   // 文件总数
const SUB_DIRS: usize = 200;         // 子目录数量
const FILE_SIZE: usize = 4096;       // 每个文件大小（字节）
const RUNS: usize = 3;               // 测试轮数
/// =======================

fn create_test_files(dir: &std::path::Path) {
    let files_per_dir = FILE_COUNT / SUB_DIRS;

    println!("Creating directory tree...");
    for d in 0..SUB_DIRS {
        let subdir = dir.join(format!("dir_{}", d));
        fs::create_dir(&subdir).unwrap();

        for i in 0..files_per_dir {
            let file_path = subdir.join(format!("test_{}.log", i));
            let mut file = File::create(file_path).unwrap();

            // 写入固定大小数据
            let content = vec![0u8; FILE_SIZE];
            file.write_all(&content).unwrap();
        }
    }
    println!("File creation completed.");
}

fn count_remaining_files(dir: &std::path::Path) -> usize {
    walkdir::WalkDir::new(dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .count()
}

#[test]
fn extreme_stress_test() {
    println!("=================================");
    println!("Extreme Stress Test Starting");
    println!("Total Files      : {}", FILE_COUNT);
    println!("Sub Directories  : {}", SUB_DIRS);
    println!("File Size        : {} bytes", FILE_SIZE);
    println!("Runs             : {}", RUNS);
    println!("=================================");

    let mut total_time = 0.0;

    for run_idx in 0..RUNS {
        println!("\n========== Run {} ==========", run_idx + 1);

        // 1️⃣ 创建临时目录
        let temp_dir = TempDir::new().unwrap();
        let dir_path = temp_dir.path();

        // 2️⃣ 生成大量文件
        create_test_files(dir_path);

        // 3️⃣ 构造 CLI 参数（删除所有 .log）
        let cli = Cli {
            dir: dir_path.to_str().unwrap().to_string(),
            filter_dir: None,
            size: None,
            day: None,
            file_ext: Some(vec!["log".to_string()]),
            is_skip_dir: false,
            is_test: true
        };

        // 4️⃣ 计时开始
        let start = Instant::now();
        run(&cli).unwrap();
        let duration = start.elapsed();

        let remaining = count_remaining_files(dir_path);

        println!("Time elapsed     : {:?}", duration);
        println!(
            "Average per file : {:.6} ms",
            duration.as_secs_f64() * 1000.0 / FILE_COUNT as f64
        );
        println!("Remaining files  : {}", remaining);

        total_time += duration.as_secs_f64();
    }

    println!("\n=================================");
    println!(
        "Average over {} runs: {:.3} ms",
        RUNS,
        total_time * 1000.0 / RUNS as f64
    );
    println!("=================================");
}
