mod error;
mod handle_id;
mod process;
mod process_handler;
mod shutdown_config;

#[cfg(test)]
mod tests;

use std::{collections::BTreeMap, sync::Arc};

use tokio::sync::Mutex;
use tracing::{debug, info, warn};

pub use error::{BoxError, Error, ProcessFailure, ProcessFailureKind, ProcessResult};
pub use handle_id::HandleID;
pub use process::{Process, ProcessBuilder, ProcessState};
pub use process_handler::ProcessHandler;
pub use shutdown_config::ShutdownConfig;

/// Re-export tokio watch receiver for state subscriptions
pub use tokio::sync::watch::Receiver as StateReceiver;

#[derive(Clone)]
pub struct ProcessManager {
    inner: Arc<Mutex<Inner>>,
}

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

impl ProcessManager {
    pub fn new() -> Self {
        debug!("creating process manager");
        Self {
            inner: Arc::new(Mutex::new(Inner::default())),
        }
    }

    pub async fn add_process(&self, process: Process) -> HandleID {
        let handle_id = process.handle_id().clone();
        info!(%handle_id, "adding process to manager");
        self.inner.lock().await.add_process(process);
        handle_id
    }

    pub async fn start_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.start_process(handle_id).await
    }

    pub async fn restart_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.restart_process(handle_id).await
    }

    pub async fn stop_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.stop_process(handle_id).await
    }

    pub async fn kill_process(&self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        self.inner.lock().await.kill_process(handle_id).await
    }

    /// Returns the current state of a process, or None if the process doesn't exist
    pub async fn get_process_state(&self, handle_id: &HandleID) -> Option<ProcessState> {
        self.inner.lock().await.get_process_state(handle_id)
    }

    /// Returns a receiver that can be used to watch for state changes of a process.
    ///
    /// Returns None if the process doesn't exist.
    ///
    /// This is useful for building reconcilers that need to react to state changes.
    pub async fn subscribe_process_state(
        &self,
        handle_id: &HandleID,
    ) -> Option<StateReceiver<ProcessState>> {
        self.inner.lock().await.subscribe_process_state(handle_id)
    }

    /// Returns the state of all processes managed by this manager
    pub async fn get_all_process_states(&self) -> Vec<(HandleID, ProcessState)> {
        self.inner.lock().await.get_all_process_states()
    }

    /// Returns a list of all process handle IDs
    pub async fn list_processes(&self) -> Vec<HandleID> {
        self.inner.lock().await.list_processes()
    }

    /// Returns a list of processes that are in the errored state
    pub async fn get_errored_processes(&self) -> Vec<HandleID> {
        self.inner
            .lock()
            .await
            .get_processes_in_state(ProcessState::Errored)
    }

    /// Returns a list of processes that are stopped
    pub async fn get_stopped_processes(&self) -> Vec<HandleID> {
        self.inner
            .lock()
            .await
            .get_processes_in_state(ProcessState::Stopped)
    }

    /// Returns a list of processes that are currently running
    pub async fn get_running_processes(&self) -> Vec<HandleID> {
        self.inner
            .lock()
            .await
            .get_processes_in_state(ProcessState::Running)
    }
}

#[derive(Default)]
struct Inner {
    handles: BTreeMap<HandleID, Process>,
}

impl Inner {
    fn add_process(&mut self, process: Process) {
        self.handles.insert(process.handle_id().clone(), process);
    }

    async fn start_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.start().await?;

        Ok(None)
    }

    async fn restart_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.restart().await?;

        Ok(None)
    }

    async fn stop_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.stop().await?;

        Ok(None)
    }

    async fn kill_process(&mut self, handle_id: &HandleID) -> Result<Option<()>, Error> {
        let Some(handle) = self.handles.get_mut(handle_id) else {
            warn!(%handle_id, "process not found");
            return Ok(None);
        };

        handle.kill().await?;

        Ok(None)
    }

    fn get_process_state(&self, handle_id: &HandleID) -> Option<ProcessState> {
        self.handles.get(handle_id).map(|p| p.state())
    }

    fn subscribe_process_state(
        &self,
        handle_id: &HandleID,
    ) -> Option<tokio::sync::watch::Receiver<ProcessState>> {
        self.handles.get(handle_id).map(|p| p.subscribe_state())
    }

    fn get_all_process_states(&self) -> Vec<(HandleID, ProcessState)> {
        self.handles
            .iter()
            .map(|(id, p)| (id.clone(), p.state()))
            .collect()
    }

    fn list_processes(&self) -> Vec<HandleID> {
        self.handles.keys().cloned().collect()
    }

    fn get_processes_in_state(&self, state: ProcessState) -> Vec<HandleID> {
        self.handles
            .iter()
            .filter(|(_, p)| p.state() == state)
            .map(|(id, _)| id.clone())
            .collect()
    }
}
