use crate::error::{AuditError, Result};
use crate::ignore::IgnoreFilter;
use crate::rules::{DynamicRule, Finding, RuleEngine};
use std::fs;
use std::path::Path;

/// Common configuration shared by all scanners.
///
/// This struct provides a unified way to manage RuleEngine settings,
/// ignore filters, and common file operations across different scanner implementations.
pub struct ScannerConfig {
    engine: RuleEngine,
    ignore_filter: Option<IgnoreFilter>,
    skip_comments: bool,
}

impl ScannerConfig {
    /// Creates a new ScannerConfig with default settings.
    pub fn new() -> Self {
        Self {
            engine: RuleEngine::new(),
            ignore_filter: None,
            skip_comments: false,
        }
    }

    /// Enables or disables comment skipping during scanning.
    pub fn with_skip_comments(mut self, skip: bool) -> Self {
        self.skip_comments = skip;
        self.engine = RuleEngine::new().with_skip_comments(skip);
        self
    }

    /// Sets an ignore filter for file filtering.
    pub fn with_ignore_filter(mut self, filter: IgnoreFilter) -> Self {
        self.ignore_filter = Some(filter);
        self
    }

    /// Adds dynamic rules loaded from custom YAML files.
    pub fn with_dynamic_rules(mut self, rules: Vec<DynamicRule>) -> Self {
        self.engine = self.engine.with_dynamic_rules(rules);
        self
    }

    /// Returns whether the given path should be ignored.
    pub fn is_ignored(&self, path: &Path) -> bool {
        self.ignore_filter
            .as_ref()
            .is_some_and(|f| f.is_ignored(path))
    }

    /// Reads a file and returns its content as a string.
    pub fn read_file(&self, path: &Path) -> Result<String> {
        fs::read_to_string(path).map_err(|e| AuditError::ReadError {
            path: path.display().to_string(),
            source: e,
        })
    }

    /// Checks the content against all rules and returns findings.
    pub fn check_content(&self, content: &str, file_path: &str) -> Vec<Finding> {
        self.engine.check_content(content, file_path)
    }

    /// Checks YAML frontmatter for specific rules (e.g., OP-001).
    pub fn check_frontmatter(&self, frontmatter: &str, file_path: &str) -> Vec<Finding> {
        self.engine.check_frontmatter(frontmatter, file_path)
    }

    /// Returns whether skip_comments is enabled.
    pub fn skip_comments(&self) -> bool {
        self.skip_comments
    }

    /// Returns a reference to the underlying RuleEngine.
    pub fn engine(&self) -> &RuleEngine {
        &self.engine
    }
}

impl Default for ScannerConfig {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_new_config() {
        let config = ScannerConfig::new();
        assert!(!config.skip_comments());
    }

    #[test]
    fn test_with_skip_comments() {
        let config = ScannerConfig::new().with_skip_comments(true);
        assert!(config.skip_comments());
    }

    #[test]
    fn test_default_config() {
        let config = ScannerConfig::default();
        assert!(!config.skip_comments());
    }

    #[test]
    fn test_is_ignored_without_filter() {
        let config = ScannerConfig::new();
        assert!(!config.is_ignored(Path::new("test.rs")));
    }

    #[test]
    fn test_read_file_success() {
        let dir = TempDir::new().unwrap();
        let file_path = dir.path().join("test.txt");
        fs::write(&file_path, "test content").unwrap();

        let config = ScannerConfig::new();
        let content = config.read_file(&file_path).unwrap();
        assert_eq!(content, "test content");
    }

    #[test]
    fn test_read_file_not_found() {
        let config = ScannerConfig::new();
        let result = config.read_file(Path::new("/nonexistent/file.txt"));
        assert!(result.is_err());
    }

    #[test]
    fn test_check_content_detects_sudo() {
        let config = ScannerConfig::new();
        let findings = config.check_content("sudo rm -rf /", "test.sh");
        assert!(findings.iter().any(|f| f.id == "PE-001"));
    }

    #[test]
    fn test_check_content_skip_comments() {
        let config = ScannerConfig::new().with_skip_comments(true);
        let findings = config.check_content("# sudo rm -rf /", "test.sh");
        assert!(findings.iter().all(|f| f.id != "PE-001"));
    }

    #[test]
    fn test_check_frontmatter_wildcard() {
        let config = ScannerConfig::new();
        let findings = config.check_frontmatter("allowed-tools: *", "SKILL.md");
        assert!(findings.iter().any(|f| f.id == "OP-001"));
    }

    #[test]
    fn test_engine_accessor() {
        let config = ScannerConfig::new();
        let _engine = config.engine();
    }
}
