//! Anti-Debugging Detection Module - Redesigned
//!
//! Detects if the process is being actively debugged
//! Focuses on active debugging, not passive analysis

/// Check if any debugger is attached
#[inline(never)]
pub fn is_debugger_present() -> bool {
    #[cfg(windows)]
    {
        windows_debugger_check()
    }
    
    #[cfg(unix)]
    {
        unix_debugger_check()
    }
    
    #[cfg(not(any(windows, unix)))]
    {
        false
    }
}

/// Windows anti-debug - only active debugging
#[cfg(windows)]
fn windows_debugger_check() -> bool {
    unsafe {
        // IsDebuggerPresent - reliable for active debugging
        if winapi::um::debugapi::IsDebuggerPresent() != 0 {
            return true;
        }
        
        // CheckRemoteDebuggerPresent - detects remote debuggers
        let mut is_debugged: i32 = 0;
        let process = winapi::um::processthreadsapi::GetCurrentProcess();
        if winapi::um::debugapi::CheckRemoteDebuggerPresent(process, &mut is_debugged) != 0 {
            if is_debugged != 0 {
                return true;
            }
        }
    }
    
    false
}

/// Linux/Unix anti-debug - only /proc/self/status check
#[cfg(unix)]
fn unix_debugger_check() -> bool {
    // Check /proc/self/status for TracerPid
    // Non-invasive, works everywhere
    if let Ok(status) = std::fs::read_to_string("/proc/self/status") {
        for line in status.lines() {
            if line.starts_with("TracerPid:") {
                if let Some(pid_str) = line.split_whitespace().nth(1) {
                    if let Ok(pid) = pid_str.parse::<i32>() {
                        if pid != 0 {
                            return true;
                        }
                    }
                }
            }
        }
    }
    false
}

/// Background monitoring thread
pub fn start_background_monitor() {
    std::thread::spawn(|| {
        loop {
            std::thread::sleep(std::time::Duration::from_secs(5));
            
            if is_debugger_present() {
                // Silent exit
                std::process::exit(1);
            }
        }
    });
}
