use std::time::SystemTime;

use std::sync::{Arc, Mutex};
use std::time::Duration;

use crate::videos::VideoItem;

/// Entries older than this are considered stale and dropped.
const ENTRY_TTL: Duration = Duration::from_secs(60 * 60);
/// How often the background task scans the cache for stale entries.
const CLEANUP_INTERVAL: Duration = Duration::from_secs(60 * 60);

#[derive(Clone)]
pub struct VideoCache {
    cache: Arc<Mutex<std::collections::HashMap<String, (SystemTime, Vec<VideoItem>)>>>, // url -> time+Items
    max_size: usize,
}
impl VideoCache {
    pub fn new() -> Self {
        VideoCache {
            cache: Arc::new(Mutex::new(std::collections::HashMap::new())),
            max_size: 100,
        }
    }

    pub fn max_size(&mut self, size: usize) -> &mut Self {
        self.max_size = size;
        self
    }

    pub fn get(&self, key: &str) -> Option<(SystemTime, Vec<VideoItem>)> {
        let cache = self.cache.lock().ok()?;
        cache.get(key).cloned()
    }

    pub fn insert(&self, key: String, value: Vec<VideoItem>) {
        if let Ok(mut cache) = self.cache.lock() {
            if cache.len() >= self.max_size {
                // Simple eviction policy: remove a random entry
                if let Some(first_key) = cache.keys().next().cloned() {
                    cache.remove(&first_key);
                }
            }
            cache.insert(key.clone(), (SystemTime::now(), value.clone()));
        }
    }

    pub fn remove(&self, key: &str) {
        if let Ok(mut cache) = self.cache.lock() {
            cache.remove(key);
        }
    }

    #[allow(dead_code)]
    pub fn entries(&self) -> Option<Vec<(String, (SystemTime, Vec<VideoItem>))>> {
        if let Ok(cache) = self.cache.lock() {
            // Return a cloned vector of the cache entries
            return Some(cache.iter().map(|(k, v)| (k.clone(), v.clone())).collect());
        }
        None
    }

    /// Number of entries currently held.
    pub fn len(&self) -> usize {
        self.cache.lock().map(|c| c.len()).unwrap_or(0)
    }

    /// Drop every entry older than [`ENTRY_TTL`]. Returns how many were removed.
    pub fn prune_expired(&self) -> usize {
        let mut removed = 0;
        if let Ok(mut cache) = self.cache.lock() {
            cache.retain(|_key, (time, _items)| match time.elapsed() {
                // Keep entries within the TTL; drop the rest.
                Ok(elapsed) => {
                    let keep = elapsed <= ENTRY_TTL;
                    if !keep {
                        removed += 1;
                    }
                    keep
                }
                // Clock went backwards: keep the entry rather than guessing.
                Err(_) => true,
            });
        }
        removed
    }

    /// Spawn a background task that prunes stale entries once per hour for the
    /// lifetime of the process.
    pub fn spawn_hourly_cleanup(&self) {
        let cache = self.clone();
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(CLEANUP_INTERVAL);
            // The first tick fires immediately; consume it so the cache isn't
            // scanned the instant the server starts.
            interval.tick().await;
            loop {
                interval.tick().await;
                let removed = cache.prune_expired();
                let remaining = cache.len();
                // Referenced unconditionally so the bindings aren't flagged as
                // unused when `flow_debug!` compiles to nothing (debug off).
                let _ = (removed, remaining);
                crate::flow_debug!(
                    "video cache cleanup removed={} remaining={}",
                    removed,
                    remaining
                );
            }
        });
    }

    #[allow(dead_code)]
    pub async fn check(&self) -> Result<(), Box<dyn std::error::Error>> {
        self.prune_expired();
        Ok(())
    }
}
