//! AI navigation system.
//!
//! Handles AI movement and pathfinding using the existing movement system.
//! NPCs use the same movement components as the player but are driven by
//! AI decisions rather than player input.

use bevy::prelude::*;

use crate::gameplay::movement::components::MoveTarget;
use crate::gameplay::ai::{AiConfig, AiState, BehaviorState};

/// Component for AI-controlled navigation.
#[derive(Component, Debug, Clone)]
pub struct AiNavigation {
    /// Current movement target (world position)
    pub movement_target: Option<Vec3>,
    /// Distance threshold to consider target reached
    pub arrival_distance: f32,
    /// Whether we're currently moving toward target
    pub is_moving: bool,
    /// Preferred speed (as fraction of max speed)
    pub speed_factor: f32,
}

impl Default for AiNavigation {
    fn default() -> Self {
        Self {
            movement_target: None,
            arrival_distance: 10.0,
            is_moving: false,
            speed_factor: 0.8,
        }
    }
}

/// Assign a movement target to an AI entity.
///
/// This function adds or updates the MoveTarget component for an NPC
/// and updates the AiNavigation component accordingly.
pub fn assign_movement_target(
    commands: &mut Commands,
    entity: Entity,
    target: Vec3,
    arrival_distance: f32,
    speed_factor: f32,
) {
    commands.entity(entity).insert(MoveTarget(target));
    commands.entity(entity).insert(AiNavigation {
        movement_target: Some(target),
        arrival_distance,
        is_moving: true,
        speed_factor,
    });
}

/// Clear movement target for an AI entity.
pub fn clear_movement_target(commands: &mut Commands, entity: Entity) {
    commands.entity(entity).remove::<MoveTarget>();
    commands.entity(entity).insert(AiNavigation {
        movement_target: None,
        arrival_distance: 10.0,
        is_moving: false,
        speed_factor: 0.8,
    });
}

/// Update AI navigation based on current behavior state.
///
/// This system runs every frame and updates movement targets based on
/// the NPC's current behavior state and state-specific data.
pub fn update_ai_navigation(
    mut commands: Commands,
    ai_config: Res<AiConfig>,
    mut ai_query: Query<(
        Entity,
        &mut AiState,
        &mut AiNavigation,
        &Transform,
    )>,
) {
    for (entity, mut ai_state, mut navigation, transform) in ai_query.iter_mut() {
        // Check if we've arrived at our current target
        if let Some(target) = navigation.movement_target {
            let distance_to_target = transform.translation.distance(target);
            if distance_to_target < navigation.arrival_distance {
                // We've arrived - clear the movement target
                navigation.is_moving = false;
                navigation.movement_target = None;
                commands.entity(entity).remove::<MoveTarget>();
            }
        }

        // Update navigation based on behavior state
        match ai_state.behavior {
            BehaviorState::Idle => {
                // No movement in idle state
                if navigation.is_moving {
                    clear_movement_target(&mut commands, entity);
                }
            }
            BehaviorState::Flee => {
                // Flee movement is handled by flee behavior system
                // Just update speed factor for emergency
                navigation.speed_factor = 1.2; // 120% speed when fleeing
            }
            BehaviorState::Combat => {
                // Combat maintains distance to target
                navigation.speed_factor = 0.9; // 90% speed in combat
            }
            BehaviorState::Patrol | BehaviorState::Trading => {
                // Normal movement speed
                navigation.speed_factor = 0.7; // 70% speed for routine operations
            }
            BehaviorState::Mining => {
                // No movement while mining - we stay at the belt
                navigation.speed_factor = 0.0;
            }
        }
    }
}
