//! Elevator state and configuration component.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;

use super::units::{Accel, Speed, Weight};
use crate::door::{DoorCommand, DoorState};
use crate::entity::EntityId;

/// Maximum number of manual door commands queued per elevator.
///
/// Beyond this cap, the oldest entry is dropped (after adjacent-duplicate
/// collapsing). Prevents runaway growth if a game submits commands faster
/// than the sim can apply them.
pub const DOOR_COMMAND_QUEUE_CAP: usize = 16;

/// Direction an elevator's indicator lamps are signalling.
///
/// On a [`LineKind::Linear`](crate::components::LineKind::Linear) shaft this
/// is derived from the pair of `going_up` / `going_down` flags on
/// [`Elevator`]. `Either` corresponds to both lamps lit — the car is idle
/// and will accept riders heading either way; `Up` / `Down` correspond to
/// an actively committed direction.
///
/// On a [`LineKind::Loop`](crate::components::LineKind::Loop) the
/// `Up`/`Down`/`Either` distinction is meaningless (every car serves every
/// stop forward through the loop), so Loop cars report
/// [`Direction::Forward`] instead. HUD/metrics consumers should
/// pattern-match exhaustively on the enum (it is `#[non_exhaustive]`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Direction {
    /// Car will serve upward trips only.
    Up,
    /// Car will serve downward trips only.
    Down,
    /// Car will serve either direction (idle).
    Either,
    /// Car is travelling forward around a one-way loop. Loop topologies
    /// have no "up"/"down" axis, so neither lamp is meaningful — this
    /// variant is the honest replacement for `Either` on Loop cars.
    /// Linear cars never report this variant.
    Forward,
}

impl std::fmt::Display for Direction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Up => write!(f, "Up"),
            Self::Down => write!(f, "Down"),
            Self::Either => write!(f, "Either"),
            Self::Forward => write!(f, "Forward"),
        }
    }
}

/// Operational phase of an elevator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ElevatorPhase {
    /// Parked with no pending requests.
    Idle,
    /// Travelling toward a specific stop in response to a dispatch
    /// assignment (carrying or about to pick up riders).
    MovingToStop(EntityId),
    /// Travelling toward a stop for repositioning — no rider service
    /// obligation, will transition directly to [`Idle`] on arrival
    /// without opening doors. Distinct from [`MovingToStop`] so that
    /// downstream code (dispatch, UI, metrics) can treat opportunistic
    /// moves differently from scheduled trips.
    ///
    /// [`MovingToStop`]: Self::MovingToStop
    /// [`Idle`]: Self::Idle
    Repositioning(EntityId),
    /// Doors are currently opening.
    DoorOpening,
    /// Doors open; riders may board or exit.
    Loading,
    /// Doors are currently closing.
    DoorClosing,
    /// Stopped at a floor (doors closed, awaiting dispatch).
    Stopped,
}

impl ElevatorPhase {
    /// Whether the elevator is currently travelling (in either a dispatched
    /// or a repositioning move).
    #[must_use]
    pub const fn is_moving(&self) -> bool {
        matches!(self, Self::MovingToStop(_) | Self::Repositioning(_))
    }

    /// The target stop of a moving elevator, if any.
    ///
    /// Returns `Some(stop)` for both [`MovingToStop`] and [`Repositioning`]
    /// variants; `None` otherwise.
    ///
    /// [`MovingToStop`]: Self::MovingToStop
    /// [`Repositioning`]: Self::Repositioning
    #[must_use]
    pub const fn moving_target(&self) -> Option<EntityId> {
        match self {
            Self::MovingToStop(s) | Self::Repositioning(s) => Some(*s),
            _ => None,
        }
    }
}

impl std::fmt::Display for ElevatorPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Idle => write!(f, "Idle"),
            Self::MovingToStop(id) => write!(f, "MovingToStop({id:?})"),
            Self::Repositioning(id) => write!(f, "Repositioning({id:?})"),
            Self::DoorOpening => write!(f, "DoorOpening"),
            Self::Loading => write!(f, "Loading"),
            Self::DoorClosing => write!(f, "DoorClosing"),
            Self::Stopped => write!(f, "Stopped"),
        }
    }
}

/// Component for an elevator entity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "the indicator-lamp triple (going_up, going_down, going_forward) plus repositioning are independently observable signals; collapsing them into an enum would lose the ability to express idle (both up and down lamps lit) and forces hosts that read individual lamps to round-trip through enum match arms"
)]
pub struct Elevator {
    /// Current operational phase.
    pub(crate) phase: ElevatorPhase,
    /// Door finite-state machine.
    pub(crate) door: DoorState,
    /// Maximum travel speed (distance/tick).
    pub(crate) max_speed: Speed,
    /// Acceleration rate (distance/tick^2).
    pub(crate) acceleration: Accel,
    /// Deceleration rate (distance/tick^2).
    pub(crate) deceleration: Accel,
    /// Maximum weight the car can carry.
    pub(crate) weight_capacity: Weight,
    /// Total weight of riders currently aboard.
    pub(crate) current_load: Weight,
    /// Entity IDs of riders currently aboard.
    pub(crate) riders: Vec<EntityId>,
    /// Stop entity the car is heading toward, if any.
    pub(crate) target_stop: Option<EntityId>,
    /// Ticks for a door open/close transition.
    pub(crate) door_transition_ticks: u32,
    /// Ticks the door stays fully open.
    pub(crate) door_open_ticks: u32,
    /// Line entity this car belongs to.
    #[serde(alias = "group")]
    pub(crate) line: EntityId,
    /// Whether this elevator is currently repositioning (not serving a dispatch).
    #[serde(default)]
    pub(crate) repositioning: bool,
    /// Stop entity IDs this elevator cannot serve (access restriction).
    #[serde(default)]
    pub(crate) restricted_stops: HashSet<EntityId>,
    /// Speed multiplier for Inspection mode (0.0..1.0).
    #[serde(default = "default_inspection_speed_factor")]
    pub(crate) inspection_speed_factor: f64,
    /// Up-direction indicator lamp: whether this car will serve upward trips.
    ///
    /// Auto-managed by the dispatch phase: set true when heading up (or idle),
    /// false while actively committed to a downward trip. Affects boarding:
    /// a rider whose next leg goes up will not board a car with `going_up=false`.
    ///
    /// On a [`LineKind::Loop`](crate::components::LineKind::Loop) this lamp
    /// has no meaning — `going_forward` is consulted instead.
    #[serde(default = "default_true")]
    pub(crate) going_up: bool,
    /// Down-direction indicator lamp: whether this car will serve downward trips.
    ///
    /// Auto-managed by the dispatch phase: set true when heading down (or idle),
    /// false while actively committed to an upward trip. Affects boarding:
    /// a rider whose next leg goes down will not board a car with `going_down=false`.
    ///
    /// On a [`LineKind::Loop`](crate::components::LineKind::Loop) this lamp
    /// has no meaning — `going_forward` is consulted instead.
    #[serde(default = "default_true")]
    pub(crate) going_down: bool,
    /// Forward-direction indicator lamp for closed-loop topologies.
    ///
    /// On a [`LineKind::Loop`](crate::components::LineKind::Loop) line, the
    /// `Up`/`Down` lamp pair is meaningless; this lamp signals "actively
    /// patrolling forward around the loop". Linear cars always have
    /// `going_forward = false`. Loop cars are kickstarted in the dispatch
    /// phase and have it flipped to `true` once they begin patrol; the
    /// door-FSM continuation keeps it set across each subsequent stop.
    /// Defaults to `false` so existing snapshots and Linear cars are
    /// unaffected.
    #[serde(default)]
    pub(crate) going_forward: bool,
    /// Count of rounded-floor transitions (passing-floors + arrivals).
    /// Useful as a scoring axis for efficiency — fewer moves per delivery
    /// means less wasted travel.
    #[serde(default)]
    pub(crate) move_count: u64,
    /// Pending manual door-control commands. Processed at the start of the
    /// doors phase; commands that aren't yet valid remain queued.
    #[serde(default)]
    pub(crate) door_command_queue: Vec<DoorCommand>,
    /// Target velocity commanded by the game while in
    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
    ///
    /// `None` means no command is active — the car coasts to a stop using
    /// `deceleration`. Read the current target via
    /// [`Elevator::manual_target_velocity`].
    #[serde(default)]
    pub(crate) manual_target_velocity: Option<f64>,
    /// Load-ratio threshold (0..=1) above which this car ignores new
    /// upward hall calls. Modeled on Otis Elevonic 411's full-load
    /// bypass (patent US5490580A). `None` disables the bypass — the
    /// default for backwards compatibility.
    ///
    /// Aboard riders still get delivered regardless; the threshold
    /// affects *pickup* decisions only.
    #[serde(default)]
    pub(crate) bypass_load_up_pct: Option<f64>,
    /// Load-ratio threshold for downward-direction pickups. Typically
    /// set lower than `bypass_load_up_pct` because down-peak riders
    /// accumulate more gradually and a half-full car has less incentive
    /// to skip the next stop. `None` disables the bypass.
    #[serde(default)]
    pub(crate) bypass_load_down_pct: Option<f64>,
    /// Per-elevator home stop. When `Some(stop)`, the reposition phase
    /// hard-pins this car to that stop: any time the car is idle and
    /// off-position, it is routed home regardless of the group's
    /// reposition strategy. Useful for express cars assigned to a
    /// dedicated lobby or service cars that should park in a
    /// loading bay between requests. `None` (the default) leaves
    /// reposition decisions entirely to the group strategy.
    #[serde(default)]
    pub(crate) home_stop: Option<EntityId>,
}

/// Default inspection speed factor (25% of normal speed).
const fn default_inspection_speed_factor() -> f64 {
    0.25
}

/// Default value for direction indicator fields (both lamps on = idle/either direction).
const fn default_true() -> bool {
    true
}

impl Elevator {
    /// Current operational phase.
    #[must_use]
    pub const fn phase(&self) -> ElevatorPhase {
        self.phase
    }

    /// Door finite-state machine.
    #[must_use]
    pub const fn door(&self) -> &DoorState {
        &self.door
    }

    /// Maximum travel speed (distance/tick).
    #[must_use]
    pub const fn max_speed(&self) -> Speed {
        self.max_speed
    }

    /// Acceleration rate (distance/tick^2).
    #[must_use]
    pub const fn acceleration(&self) -> Accel {
        self.acceleration
    }

    /// Deceleration rate (distance/tick^2).
    #[must_use]
    pub const fn deceleration(&self) -> Accel {
        self.deceleration
    }

    /// Maximum weight the car can carry.
    #[must_use]
    pub const fn weight_capacity(&self) -> Weight {
        self.weight_capacity
    }

    /// Total weight of riders currently aboard.
    #[must_use]
    pub const fn current_load(&self) -> Weight {
        self.current_load
    }

    /// Entity IDs of riders currently aboard.
    #[must_use]
    pub fn riders(&self) -> &[EntityId] {
        &self.riders
    }

    /// Stop entity the car is heading toward, if any.
    #[must_use]
    pub const fn target_stop(&self) -> Option<EntityId> {
        self.target_stop
    }

    /// Ticks for a door open/close transition.
    #[must_use]
    pub const fn door_transition_ticks(&self) -> u32 {
        self.door_transition_ticks
    }

    /// Ticks the door stays fully open.
    #[must_use]
    pub const fn door_open_ticks(&self) -> u32 {
        self.door_open_ticks
    }

    /// Line entity this car belongs to.
    #[must_use]
    pub const fn line(&self) -> EntityId {
        self.line
    }

    /// Whether this elevator is currently repositioning (not serving a dispatch).
    #[must_use]
    pub const fn repositioning(&self) -> bool {
        self.repositioning
    }

    /// Stop entity IDs this elevator cannot serve (access restriction).
    #[must_use]
    pub const fn restricted_stops(&self) -> &HashSet<EntityId> {
        &self.restricted_stops
    }

    /// Speed multiplier applied during Inspection mode.
    #[must_use]
    pub const fn inspection_speed_factor(&self) -> f64 {
        self.inspection_speed_factor
    }

    /// Load-ratio threshold above which upward-direction pickups are
    /// skipped (full-load bypass). `None` disables the bypass. See the
    /// field docs on [`Elevator`] for the underlying model.
    #[must_use]
    pub const fn bypass_load_up_pct(&self) -> Option<f64> {
        self.bypass_load_up_pct
    }

    /// Load-ratio threshold above which downward-direction pickups are
    /// skipped. `None` disables the bypass.
    #[must_use]
    pub const fn bypass_load_down_pct(&self) -> Option<f64> {
        self.bypass_load_down_pct
    }

    /// Mutator for the upward full-load bypass threshold.
    pub const fn set_bypass_load_up_pct(&mut self, pct: Option<f64>) {
        self.bypass_load_up_pct = pct;
    }

    /// Mutator for the downward full-load bypass threshold.
    pub const fn set_bypass_load_down_pct(&mut self, pct: Option<f64>) {
        self.bypass_load_down_pct = pct;
    }

    /// Per-elevator hard-pinned home stop. When `Some(stop)`, the
    /// reposition phase routes this car to `stop` whenever it is
    /// idle and off-position, regardless of the group's reposition
    /// strategy. `None` (the default) leaves reposition decisions
    /// entirely to the group strategy.
    #[must_use]
    pub const fn home_stop(&self) -> Option<EntityId> {
        self.home_stop
    }

    /// Whether this car's up-direction indicator lamp is lit.
    ///
    /// A lit up-lamp signals the car will serve upward-travelling riders.
    /// Both lamps lit means the car is idle and will accept either direction.
    #[must_use]
    pub const fn going_up(&self) -> bool {
        self.going_up
    }

    /// Whether this car's down-direction indicator lamp is lit.
    ///
    /// A lit down-lamp signals the car will serve downward-travelling riders.
    /// Both lamps lit means the car is idle and will accept either direction.
    #[must_use]
    pub const fn going_down(&self) -> bool {
        self.going_down
    }

    /// Whether this car's forward-direction indicator lamp is lit.
    ///
    /// Only meaningful on [`LineKind::Loop`](crate::components::LineKind::Loop)
    /// lines. Set true while a Loop car is patrolling forward, false when
    /// pulled out of service. Always false for Linear cars.
    #[must_use]
    pub const fn going_forward(&self) -> bool {
        self.going_forward
    }

    /// Direction this car is currently committed to, derived from the
    /// indicator-lamp triple.
    ///
    /// - [`Direction::Forward`] — `going_forward` is set (Loop cars only)
    /// - [`Direction::Up`] — only `going_up` is set
    /// - [`Direction::Down`] — only `going_down` is set
    /// - [`Direction::Either`] — both up/down lamps lit (car is idle /
    ///   accepting either direction), or neither is set (treated as
    ///   `Either` too, though the dispatch phase normally keeps at least
    ///   one lit)
    ///
    /// Forward dominates the up/down pair so a Loop car never reports a
    /// stale `Up`/`Down`/`Either` value left over from earlier Linear
    /// behaviour.
    #[must_use]
    pub const fn direction(&self) -> Direction {
        if self.going_forward {
            return Direction::Forward;
        }
        match (self.going_up, self.going_down) {
            (true, false) => Direction::Up,
            (false, true) => Direction::Down,
            _ => Direction::Either,
        }
    }

    /// Count of rounded-floor transitions this elevator has made
    /// (both passing-floor crossings and arrivals).
    #[must_use]
    pub const fn move_count(&self) -> u64 {
        self.move_count
    }

    /// Pending manual door-control commands for this elevator.
    ///
    /// Populated by
    /// [`Simulation::open_door`](crate::sim::Simulation::open_door)
    /// and its siblings. Commands are drained at the start of each doors-phase
    /// tick; any that aren't yet valid remain queued.
    #[must_use]
    pub fn door_command_queue(&self) -> &[DoorCommand] {
        &self.door_command_queue
    }

    /// Currently commanded target velocity for
    /// [`ServiceMode::Manual`](crate::components::ServiceMode::Manual).
    ///
    /// Returns `None` if no target is set, meaning the car coasts to a
    /// stop using the configured deceleration. Positive values command
    /// upward travel, negative values command downward travel.
    #[must_use]
    pub const fn manual_target_velocity(&self) -> Option<f64> {
        self.manual_target_velocity
    }
}
