use std::fs;
use std::path::{Path, PathBuf};

fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let entries = fs::read_dir(dir).unwrap();
    for entry in entries {
        let entry = entry.unwrap();
        let path = entry.path();
        if path.is_dir() {
            collect_rs_files(&path, out);
        } else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

#[test]
fn save_cache_state_versioned_has_limited_call_sites() {
    let repo_root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let mut files = Vec::new();
    collect_rs_files(&repo_root.join("src"), &mut files);
    collect_rs_files(&repo_root.join("tests"), &mut files);

    let allowed = [
        repo_root.join("src/rtr/store.rs"),
        repo_root.join("src/rtr/cache/store.rs"),
        repo_root.join("tests/test_store_db.rs"),
        repo_root.join("tests/test_cache.rs"),
        repo_root.join("tests/test_store_boundary.rs"),
    ];

    let mut violations = Vec::new();
    for file in files {
        let content = fs::read_to_string(&file).unwrap();
        if content.contains(".save_cache_state_versioned(") && !allowed.contains(&file) {
            violations.push(file);
        }
    }

    assert!(
        violations.is_empty(),
        "unexpected direct save_cache_state_versioned() call sites: {:?}",
        violations
    );
}
