use std::{fmt::Debug, future::Future, panic, pin::Pin};

use log::{error, info};
use serde::{de::DeserializeOwned, Serialize};
use tokio::sync::mpsc::{Receiver, Sender};

use crate::message_queue::{MessageQueue, MessageQueueBuilder};

use super::consumer::consume;
use super::dispatcher::TaskDispatcher;
use crate::task::{Task, TaskRequest};

struct ExecutionNode;

// Responsible for maintaining the consumers and the task dispatcher
impl ExecutionNode {
    /// Creates a new execution node
    pub async fn spawn(
        task_consumers: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
        n_workers: u32,
        message_queue: MessageQueue,
        task_request_rx: Receiver<TaskRequest>,
    ) {
        // Spin up the consumers (these are the threads that convert messages into tasks)
        // The consumers will then place deserialized tasks into the task channel for the dispatcher to pick up
        info!("Starting execution node...");
        for consumer_closure in task_consumers {
            info!("Spawning consumer...");
            tokio::spawn(consumer_closure);
        }

        // Spin up the dispatcher (this is the thread that dispatches tasks to workers)
        // The dispatcher will then place the dispatched tasks into the worker channel for the workers to pick up
        info!("Spawning dispatcher...");
        TaskDispatcher::start(n_workers, task_request_rx, message_queue).await;
    }
}

pub struct ExecutionNodeBuilder {
    // These are the consumers that will be spawned
    task_consumers: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,

    // This is the number of worker threads that will be spawned
    n_workers: u32,

    // This is the channel that the consumers will use to place tasks into the dispatcher
    task_request_tx: Sender<TaskRequest>,

    // This is the channel that the dispatcher will use to receive tasks from the consumers
    task_request_rx: Receiver<TaskRequest>,

    // These are how we attach to the message queue (The individual consumers will get their own subscription ID for getting new tasks)
    gcp_project_id: String,
    execution_updates_topic_id: String,
}

// Builder pattern for the execution node
impl ExecutionNodeBuilder {
    /// Creates a new ExecutionNodeBuilder
    pub async fn new(n_workers: u32, project_id: &str, execution_updates_topic_id: &str) -> Self {
        // Set a panic hook so panic! in threads exits the main thread as well
        let orig_hook = panic::take_hook();
        panic::set_hook(Box::new(move |panic_info| {
            orig_hook(panic_info);
            std::process::exit(1);
        }));

        // Create the task transfer channel
        let (task_request_tx, task_request_rx) =
            tokio::sync::mpsc::channel::<TaskRequest>(n_workers as usize * 2);

        // Return the builder
        Self {
            task_consumers: Vec::new(),
            n_workers,
            task_request_tx,
            task_request_rx,
            gcp_project_id: project_id.to_string(),
            execution_updates_topic_id: execution_updates_topic_id.to_string(),
        }
    }

    /// Adds a consumer to the ExecutionNodeBuilder
    pub async fn with_consumer<T>(mut self, subscription_id: &str) -> Self
    where
        T: DeserializeOwned + Serialize + Send + Sync + Debug + Clone + Task + 'static,
    {
        // Every consumer gets its own message queue client solely for subscribing to messages from the designated channel (No ability to push updates)
        let consumer_message_queue = match MessageQueueBuilder::new()
            .with_project_id(&self.gcp_project_id)
            .with_incoming_executions_subscription_id(subscription_id)
            .build()
            .await
        {
            Ok(queue) => queue,
            Err(e) => {
                error!("Error creating message queue: {:?}", e);
                std::process::exit(1);
            }
        };

        // Create the consumer and add it to the list of consumers
        self.task_consumers.push(Box::pin(consume::<T>(
            consumer_message_queue,
            self.task_request_tx.clone(),
        )));

        self
    }

    /// Builds the ExecutionNode
    pub async fn build(self) {
        // Pull out the fields from the builder
        let Self {
            task_consumers,
            n_workers,
            task_request_rx,
            ..
        } = self;

        // The dispatcher itself gets a MessageQueue that is used solely for pushing task execution updates
        let dispatcher_message_queue = match MessageQueueBuilder::new()
            .with_project_id(&self.gcp_project_id)
            .with_execution_updates_topic_id(&self.execution_updates_topic_id)
            .build()
            .await
        {
            Ok(queue) => queue,
            Err(e) => {
                error!("Error creating message queue: {:?}", e);
                std::process::exit(1);
            }
        };

        // Spawn the execution node with the fields from the builder
        ExecutionNode::spawn(
            task_consumers,
            n_workers,
            dispatcher_message_queue,
            task_request_rx,
        )
        .await;
    }
}
