//! AI system for NPC behavior.
//!
//! This module provides a state machine-based AI system for NPC ships
//! and entities. It includes:
//!
//! - **State Machine**: Hierarchical behavior states (Idle, Patrol, Combat, Flee, Mining, Trading)
//! - **Navigation**: Pathfinding and movement using the existing movement system
//! - **Perception**: Event-based detection of player and other entities
//! - **Spawning**: NPC ship spawning based on system security and faction
//! - **Faction AI**: Faction-specific behavior profiles

mod behavior;
mod faction;
mod navigation;
mod perception;
mod spawning;
mod states;

pub use faction::{FactionAiBehavior, FactionAiProfile};
pub use navigation::{AiNavigation, assign_movement_target};
pub use perception::{Perceptible, Perception, PerceptionEvent, update_perception};
pub use spawning::{NpcMetadata, NpcSpawner, spawn_station_traffic, spawn_system_npcs};
pub use states::{
    AiState, AiStateMachine, BehaviorState, CombatState, FleeState,
    MiningState, PatrolState, StateTransition, TradingState,
};
pub use behavior::{execute_patrol, execute_combat, execute_flee, execute_mining, execute_trading};

use bevy::prelude::*;

use crate::state::AppState;

/// Main AI plugin that orchestrates all AI systems.
pub struct AiPlugin;

impl Plugin for AiPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<AiConfig>()
            .init_resource::<AiStateMachine>()
            .add_event::<PerceptionEvent>()
            .add_event::<StateTransition>()
            // AI spawning systems - run when entering in-game state
            .add_systems(OnEnter(AppState::InGame), spawning::spawn_system_npcs)
            // AI update systems - run every frame during gameplay
            .add_systems(
                Update,
                (
                    perception::update_perception,
                    navigation::update_ai_navigation,
                    behavior::update_state_transitions,
                    behavior::execute_patrol,
                    behavior::execute_combat,
                    behavior::execute_flee,
                    behavior::execute_mining,
                    behavior::execute_trading,
                )
                    .chain()
                    .run_if(in_state(AppState::InGame)),
            );
    }
}

/// Configuration resource for AI behavior tuning.
#[derive(Resource, Debug, Clone)]
pub struct AiConfig {
    /// Detection range for perception (in world units)
    pub perception_range: f32,
    /// How often AI updates their decisions (in seconds)
    pub decision_interval: f32,
    /// Range at which NPCs engage in combat
    pub combat_range: f32,
    /// Hull percentage at which NPCs flee
    pub flee_hull_threshold: f32,
    /// Distance considered "safe" when fleeing
    pub safe_flee_distance: f32,
}

impl Default for AiConfig {
    fn default() -> Self {
        Self {
            perception_range: 500.0,
            decision_interval: 0.5,
            combat_range: 200.0,
            flee_hull_threshold: 0.3, // 30% hull
            safe_flee_distance: 800.0,
        }
    }
}
