use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::Path;
use std::sync::mpsc::channel;
use crate::{UCXLAddress, TemporalAxis};
use std::str::FromStr;

pub struct UCXLWatcher {
    base_path: std::path::PathBuf,
}

impl UCXLWatcher {
    pub fn new<P: AsRef<Path>>(path: P) -> Self {
        Self {
            base_path: path.as_ref().to_path_buf(),
        }
    }

    pub fn watch_loop(&self) -> Result<(), Box<dyn std::error::Error>> {
        let (tx, rx) = channel();

        let mut watcher = RecommendedWatcher::new(tx, Config::default())?;
        watcher.watch(&self.base_path, RecursiveMode::Recursive)?;

        println!("UCXL Watcher started on {:?}", self.base_path);

        for res in rx {
            match res {
                Ok(event) => {
                    for path in event.paths {
                        if let Some(rel_path) = path.strip_prefix(&self.base_path).ok() {
                            let rel_str = rel_path.to_string_lossy();
                            // Attempt a heuristic address mapping: ucxl://system:watcher@local:filesystem/#/path
                            let addr_str = format!("ucxl://system:watcher@local:filesystem/#/{}", rel_str);
                            if let Ok(addr) = UCXLAddress::from_str(&addr_str) {
                                println!("[UCXL EVENT] {:?} -> {}", event.kind, addr);
                            }
                        }
                    }
                }
                Err(e) => println!("watch error: {:?}", e),
            }
        }
        Ok(())
    }
}
