//! C2-Directed Assignment for bootstrap phase
//!
//! Implements Command & Control (C2) directed cell formation where C2 explicitly
//! assigns nodes to cells based on operational requirements.
//!
//! # Architecture
//!
//! Unlike autonomous geographic self-organization (E3.1), C2-directed assignment
//! provides top-down cell formation with explicit authority and validation:
//!
//! ## Assignment Flow
//!
//! 1. **C2 Issues Assignment**: C2 broadcasts `CellAssignment` messages
//! 2. **Node Receives**: Nodes observe assignments via the sync backend
//! 3. **Validation**: Node validates assignment (exists, not full, authorized)
//! 4. **Execution**: Node joins cell and updates state
//! 5. **Confirmation**: Assignment status tracked in distributed state
//!
//! ## Message Format
//!
//! ```json
//! {
//!   "assignment_id": "assign_123",
//!   "cell_id": "cell_alpha",
//!   "node_ids": ["node_1", "node_2", "node_3"],
//!   "issued_by": "c2_controller_1",
//!   "timestamp": 1698765432,
//!   "priority": "high"
//! }
//! ```
//!
//! ## Use Cases
//!
//! - **Pre-planned missions**: Assign nodes based on pre-mission planning
//! - **Capability requirements**: Form cells with specific capability mixes
//! - **Command override**: Override autonomous formation when needed
//! - **Emergency reconstitution**: Rebuild cells after casualties/failures

use crate::models::CellStateExt;
use crate::storage::CellStore;
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info, instrument, warn};

/// Assignment priority levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AssignmentPriority {
    /// Low priority - can be deferred
    Low,
    /// Normal priority - standard assignment
    #[default]
    Normal,
    /// High priority - process immediately
    High,
    /// Critical priority - override existing assignments
    Critical,
}

/// Assignment status tracking
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AssignmentStatus {
    /// Assignment issued but not yet processed
    Pending,
    /// Assignment accepted and in progress
    InProgress,
    /// Assignment completed successfully
    Completed,
    /// Assignment failed validation or execution
    Failed { reason: String },
}

/// Cell assignment message from C2
///
/// This message is broadcast via the sync backend and contains explicit node-to-cell
/// assignments. Nodes observe these messages and execute them if valid.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellAssignment {
    /// Unique identifier for this assignment
    pub assignment_id: String,
    /// Target cell ID
    pub cell_id: String,
    /// List of node IDs to assign to this cell
    pub node_ids: Vec<String>,
    /// C2 authority issuing the assignment
    pub issued_by: String,
    /// Unix timestamp when assignment was issued
    pub timestamp: u64,
    /// Assignment priority
    pub priority: AssignmentPriority,
    /// Current status of the assignment
    pub status: AssignmentStatus,
    /// Optional operational context or reason
    pub context: Option<String>,
}

impl CellAssignment {
    /// Create a new cell assignment
    pub fn new(
        assignment_id: String,
        cell_id: String,
        node_ids: Vec<String>,
        issued_by: String,
        priority: AssignmentPriority,
    ) -> Self {
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            assignment_id,
            cell_id,
            node_ids,
            issued_by,
            timestamp,
            priority,
            status: AssignmentStatus::Pending,
            context: None,
        }
    }

    /// Add operational context to the assignment
    pub fn with_context(mut self, context: String) -> Self {
        self.context = Some(context);
        self
    }

    /// Check if assignment includes a specific node
    pub fn includes_node(&self, node_id: &str) -> bool {
        self.node_ids.iter().any(|id| id == node_id)
    }

    /// Mark assignment as in progress
    pub fn mark_in_progress(&mut self) {
        self.status = AssignmentStatus::InProgress;
    }

    /// Mark assignment as completed
    pub fn mark_completed(&mut self) {
        self.status = AssignmentStatus::Completed;
    }

    /// Mark assignment as failed
    pub fn mark_failed(&mut self, reason: String) {
        self.status = AssignmentStatus::Failed { reason };
    }

    /// Check if assignment is still active (pending or in progress)
    pub fn is_active(&self) -> bool {
        matches!(
            self.status,
            AssignmentStatus::Pending | AssignmentStatus::InProgress
        )
    }
}

/// Assignment validation result
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationResult {
    /// Assignment is valid and can be executed
    Valid,
    /// Cell does not exist
    CellNotFound,
    /// Cell is full and cannot accept more members
    CellFull,
    /// Node is already in another cell
    NodeAlreadyAssigned { current_cell: String },
    /// Assignment is from unauthorized source
    Unauthorized,
    /// Assignment has expired
    Expired,
    /// Other validation error
    Invalid { reason: String },
}

/// C2-Directed Assignment Manager
///
/// Processes C2-issued cell assignments and manages assignment lifecycle.
pub struct DirectedAssignmentManager<B: crate::sync::DataSyncBackend> {
    /// Cell storage
    store: CellStore<B>,
    /// Active assignments being tracked
    assignments: HashMap<String, CellAssignment>,
    /// Node ID of this node
    my_node_id: String,
    /// Assignment timeout (seconds)
    assignment_timeout: u64,
}

impl<B: crate::sync::DataSyncBackend> DirectedAssignmentManager<B> {
    /// Create a new directed assignment manager
    pub fn new(store: CellStore<B>, my_node_id: String) -> Self {
        Self {
            store,
            assignments: HashMap::new(),
            my_node_id,
            assignment_timeout: 300, // 5 minutes default
        }
    }

    /// Set assignment timeout
    pub fn with_timeout(mut self, timeout_secs: u64) -> Self {
        self.assignment_timeout = timeout_secs;
        self
    }

    /// Process a received cell assignment
    #[instrument(skip(self, assignment))]
    pub async fn process_assignment(&mut self, assignment: CellAssignment) -> Result<()> {
        info!(
            "Processing assignment {} for cell {}",
            assignment.assignment_id, assignment.cell_id
        );

        // Check if this assignment applies to us
        if !assignment.includes_node(&self.my_node_id) {
            debug!(
                "Assignment {} does not include node {}",
                assignment.assignment_id, self.my_node_id
            );
            return Ok(());
        }

        // Validate the assignment
        let validation = self.validate_assignment(&assignment).await?;
        if validation != ValidationResult::Valid {
            warn!(
                "Assignment {} failed validation: {:?}",
                assignment.assignment_id, validation
            );
            return Err(Error::InvalidTransition {
                from: "Pending assignment".to_string(),
                to: "Executed assignment".to_string(),
                reason: format!("Assignment validation failed: {:?}", validation),
            });
        }

        // Store assignment
        self.assignments
            .insert(assignment.assignment_id.clone(), assignment.clone());

        // Execute the assignment
        self.execute_assignment(assignment).await?;

        Ok(())
    }

    /// Validate a cell assignment
    #[instrument(skip(self, assignment))]
    async fn validate_assignment(&self, assignment: &CellAssignment) -> Result<ValidationResult> {
        debug!("Validating assignment {}", assignment.assignment_id);

        // Check if assignment has expired
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        if current_time.saturating_sub(assignment.timestamp) > self.assignment_timeout {
            return Ok(ValidationResult::Expired);
        }

        // Check if cell exists
        let cell = self.store.get_cell(&assignment.cell_id).await?;
        if cell.is_none() {
            return Ok(ValidationResult::CellNotFound);
        }

        let cell = cell.unwrap();

        // Check if cell can accept new members
        if cell.is_full() {
            return Ok(ValidationResult::CellFull);
        }

        // Check if node is already in a cell
        if let Some(current_cell) = self.get_current_cell(&self.my_node_id).await? {
            if current_cell != assignment.cell_id {
                return Ok(ValidationResult::NodeAlreadyAssigned {
                    current_cell: current_cell.clone(),
                });
            }
        }

        Ok(ValidationResult::Valid)
    }

    /// Execute a validated assignment
    #[instrument(skip(self, assignment))]
    async fn execute_assignment(&mut self, mut assignment: CellAssignment) -> Result<()> {
        info!(
            "Executing assignment {} - joining cell {}",
            assignment.assignment_id, assignment.cell_id
        );

        assignment.mark_in_progress();

        // Add node to cell
        self.store
            .add_member(&assignment.cell_id, self.my_node_id.clone())
            .await?;

        assignment.mark_completed();
        self.assignments
            .insert(assignment.assignment_id.clone(), assignment.clone());

        info!(
            "Assignment {} completed successfully",
            assignment.assignment_id
        );

        Ok(())
    }

    /// Get the current cell for a node
    async fn get_current_cell(&self, node_id: &str) -> Result<Option<String>> {
        let valid_cells = self.store.get_valid_cells().await?;

        for cell in valid_cells {
            if cell.is_member(node_id) {
                return Ok(cell.config.as_ref().map(|c| c.id.clone()));
            }
        }

        Ok(None)
    }

    /// Get assignment by ID
    pub fn get_assignment(&self, assignment_id: &str) -> Option<&CellAssignment> {
        self.assignments.get(assignment_id)
    }

    /// Get all active assignments
    pub fn active_assignments(&self) -> Vec<&CellAssignment> {
        self.assignments
            .values()
            .filter(|a| a.is_active())
            .collect()
    }

    /// Clean up expired assignments
    pub fn cleanup_expired(&mut self) {
        let current_time = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        self.assignments.retain(|_, assignment| {
            current_time.saturating_sub(assignment.timestamp) <= self.assignment_timeout
        });
    }
}
