//! M6b.4 — library must never initialise a global tracing/log subscriber.
//!
//! See `docs/policy/logging.md`. The CLI or embedding application owns
//! that decision.

use std::path::PathBuf;

fn crate_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

fn collect_rs_files(root: &std::path::Path) -> Vec<PathBuf> {
    fn walk(dir: &std::path::Path, out: &mut Vec<PathBuf>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for e in entries.flatten() {
            let p = e.path();
            if p.is_dir() {
                // Skip any vendored target / build artefact dirs.
                if p.file_name()
                    .map(|n| n == "target" || n == "tests")
                    .unwrap_or(false)
                {
                    continue;
                }
                walk(&p, out);
            } else if p.extension().and_then(|s| s.to_str()) == Some("rs") {
                out.push(p);
            }
        }
    }
    let mut v = Vec::new();
    walk(&root.join("src"), &mut v);
    v
}

const FORBIDDEN: &[&str] = &[
    "tracing_subscriber::set_global_default",
    "tracing::subscriber::set_global_default",
    "log::set_logger",
    "log::set_boxed_logger",
    "tracing_subscriber::fmt::init",
    "tracing_subscriber::fmt().init()",
];

#[test]
fn pdfluent_library_does_not_init_a_global_subscriber() {
    let files = collect_rs_files(&crate_root());
    let mut violations = Vec::new();
    for path in &files {
        let Ok(contents) = std::fs::read_to_string(path) else {
            continue;
        };
        for needle in FORBIDDEN {
            if contents.contains(needle) {
                violations.push(format!(
                    "{}: contains forbidden token '{needle}'",
                    path.display()
                ));
            }
        }
    }
    assert!(
        violations.is_empty(),
        "M6b.4 logging policy violated:\n{}",
        violations.join("\n")
    );
}
