use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::PathBuf;
use std::sync::mpsc;

pub struct FileWatcher {
    _watcher: RecommendedWatcher,
    pub receiver: mpsc::Receiver<FileChange>,
}

#[derive(Debug, Clone)]
pub struct FileChange {
    pub path: PathBuf,
    pub kind: ChangeKind,
}

#[derive(Debug, Clone)]
pub enum ChangeKind {
    Created,
    Modified,
    Deleted,
}

impl FileWatcher {
    pub fn new(watch_dir: &PathBuf) -> Result<Self, String> {
        let (tx, rx) = mpsc::channel();

        let mut watcher = RecommendedWatcher::new(
            move |result: Result<Event, notify::Error>| {
                if let Ok(event) = result {
                    let kind = match event.kind {
                        EventKind::Create(_) => Some(ChangeKind::Created),
                        EventKind::Modify(_) => Some(ChangeKind::Modified),
                        EventKind::Remove(_) => Some(ChangeKind::Deleted),
                        _ => None,
                    };
                    if let Some(kind) = kind {
                        for path in event.paths {
                            // Skip hidden files and temp files
                            let name = path.file_name()
                                .and_then(|n| n.to_str())
                                .unwrap_or("");
                            if name.starts_with('.') || name.starts_with('~') || name.ends_with(".tmp") {
                                continue;
                            }
                            let _ = tx.send(FileChange { path, kind: kind.clone() });
                        }
                    }
                }
            },
            Config::default(),
        ).map_err(|e| format!("Watcher-Fehler: {}", e))?;

        watcher.watch(watch_dir.as_ref(), RecursiveMode::Recursive)
            .map_err(|e| format!("Watch-Fehler: {}", e))?;

        Ok(Self { _watcher: watcher, receiver: rx })
    }
}
