use anyhow::Result;
use std::path::Path;
use tokio::time;
use tracing::{info, warn};

pub struct WatcherConfig {
    pub directories: Vec<String>,
    pub poll_interval_ms: u64,
}

impl Default for WatcherConfig {
    fn default() -> Self {
        // Default to SFTP demo directory if not specified
        let default_dir = std::env::var("MOMENTRY_SFTP_ROOT")
            .unwrap_or_else(|_| "/Users/accusys/momentry/var/sftpgo/data/demo/".to_string());

        Self {
            directories: vec![default_dir],
            poll_interval_ms: 60000, // 60 seconds polling interval
        }
    }
}

/// Starts the file watcher in the background.
/// Scans directories for video files (auto-registration disabled).
pub async fn run_watcher() -> Result<()> {
    let config = WatcherConfig::default();
    let dirs = config.directories.clone();

    if dirs.is_empty() {
        warn!("No directories configured for watching.");
        return Err(anyhow::anyhow!("No watch directories"));
    }

    info!("Starting Video File Watcher (auto-registration disabled)...");
    info!("Watch directories: {:?}", dirs);

    // Spawn background task for monitoring only (no auto-registration)
    tokio::spawn(async move {
        let mut interval = time::interval(time::Duration::from_millis(config.poll_interval_ms));

        loop {
            interval.tick().await;
            scan_videos(&dirs).await;
        }
    });

    Ok(())
}

async fn scan_videos(directories: &[String]) {
    // Allowed extensions list
    let allowed_extensions = vec!["mp4", "mov", "mkv"];

    for dir in directories {
        let path = Path::new(dir);
        if !path.exists() {
            warn!("Directory does not exist, skipping: {}", dir);
            continue;
        }

        if let Ok(entries) = std::fs::read_dir(path) {
            let video_count = entries
                .flatten()
                .filter(|entry| {
                    let file_path = entry.path();
                    if file_path.is_dir() {
                        if let Some(name) = file_path.file_name().and_then(|n| n.to_str()) {
                            if name.starts_with('.') {
                                return false;
                            }
                        }
                    }
                    if !file_path.is_file() {
                        return false;
                    }
                    if let Some(ext) = file_path.extension().and_then(|e| e.to_str()) {
                        allowed_extensions.contains(&ext.to_lowercase().as_str())
                    } else {
                        false
                    }
                })
                .count();

            if video_count > 0 {
                info!(
                    "Found {} video files in {} (use API to register)",
                    video_count, dir
                );
            }
        }
    }
}
