/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2026 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use crate::PacketSink;
use hurrycurry_game_core::Game;
#[cfg(feature = "debug_events")]
use hurrycurry_protocol::{DebugEvent, DebugEventDisplay};
use hurrycurry_protocol::{
    PacketS, PlayerID,
    glam::{IVec2, Vec2, ivec2},
};
use log::{debug, trace};
use std::{
    cmp::Ordering,
    collections::{BinaryHeap, HashMap, HashSet},
    time::Instant,
};

#[derive(Debug, Clone)]
pub struct Path {
    segments: Vec<Vec2>,
    seg_time: f32,
    last_dir: Vec2,
    last_boost: bool,
}

impl Path {
    pub const EMPTY: Path = Path {
        seg_time: 0.,
        segments: Vec::new(),
        last_boost: false,
        last_dir: Vec2::ZERO,
    };
    pub fn update(
        &mut self,
        out: &mut PacketSink,
        player: PlayerID,
        position: Vec2,
        dt: f32,
        speed: f32,
        allow_boost: bool,
    ) {
        let dir = speed * self.next_direction(position, dt);
        let boost = allow_boost && self.is_stuck(0.5);
        if dir.distance(self.last_dir) > 0.1 || boost != self.last_boost {
            self.last_dir = dir;
            self.last_boost = boost;
            out.push(PacketS::Movement {
                player,
                dir,
                boost,
                pos: None,
            });
        }
    }
    pub fn next_direction(&mut self, position: Vec2, dt: f32) -> Vec2 {
        if let Some(next) = self.segments.last().copied() {
            trace!("next {next}");
            self.seg_time += dt;
            if next.distance(position) < if self.segments.len() == 1 { 0.1 } else { 0.3 } {
                self.seg_time = 0.;
                self.segments.pop();
            }
            (next - position).normalize_or_zero()
        } else {
            Vec2::ZERO
        }
    }
    pub fn is_done(&self) -> bool {
        self.segments.is_empty()
    }
    pub fn is_stuck(&self, thres: f32) -> bool {
        self.seg_time > thres
    }
    pub fn remaining_segments(&self) -> usize {
        self.segments.len()
    }

    #[cfg(feature = "debug_events")]
    pub fn debug(&self, id: PlayerID) -> DebugEvent {
        use crate::debug_player_color;
        DebugEvent {
            key: format!("path-{id}"),
            color: debug_player_color(id),
            display: DebugEventDisplay::Path {
                player: id,
                points: self.segments.clone(),
            },
            timeout: 0.1,
        }
    }
}

pub fn find_path_to_neighbour(game: &Game, from: IVec2, to: IVec2) -> Option<Path> {
    let mut paths = Vec::new();
    for xo in -1..=1 {
        for yo in -1..=1 {
            let to = to + IVec2::new(xo, yo);
            if game.walkable.contains(&to) {
                paths.extend(find_path(game, from, to))
            }
        }
    }
    paths.into_iter().min_by_key(|p| p.segments.len())
}
pub fn find_path(game: &Game, from: IVec2, to: IVec2) -> Option<Path> {
    #[derive(Debug, PartialEq, Eq)]
    struct Open {
        heuristic: i32,
        pos: IVec2,
        prev_pos: IVec2,
        distance: i32,
    }
    impl PartialOrd for Open {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }
    impl Ord for Open {
        fn cmp(&self, other: &Self) -> Ordering {
            self.heuristic.cmp(&other.heuristic)
        }
    }

    debug!("planning route from {from} to {to}");
    let start = Instant::now();
    let mut visited = HashMap::new();
    let mut open = BinaryHeap::new();
    open.push(Open {
        heuristic: 1,
        pos: from,
        prev_pos: from,
        distance: 0,
    });

    loop {
        let Open {
            pos,
            prev_pos,
            distance,
            ..
        } = open.pop()?;
        if visited.contains_key(&pos) {
            continue;
        }
        visited.insert(pos, prev_pos);
        if pos == to {
            break;
        }
        for dir in [IVec2::NEG_X, IVec2::NEG_Y, IVec2::X, IVec2::Y] {
            let next = pos + dir;
            if game.walkable.contains(&next) {
                let penalty = if game.walkable_preferred.contains(&next) {
                    0
                } else {
                    8
                };
                open.push(Open {
                    heuristic: -(distance + next.distance_squared(to).isqrt()),
                    pos: next,
                    prev_pos: pos,
                    distance: distance + penalty + 1,
                });
            }
        }
    }

    let mut segments = Vec::new();
    let mut c = to;
    loop {
        segments.push(c.as_vec2() + 0.5);
        let cn = visited[&c];
        if cn == c {
            break;
        }
        c = cn
    }

    optimize_path(&game.walkable_preferred, &mut segments);

    debug!(
        "done in {:?} (distance={})",
        start.elapsed(),
        segments.len()
    );
    Some(Path {
        segments,
        seg_time: 0.,
        last_boost: false,
        last_dir: Vec2::ZERO,
    })
}

fn optimize_path(walkable: &HashSet<IVec2>, segments: &mut Vec<Vec2>) {
    while segments.len() >= 3 {
        let mut changed = false;
        for i in 0..segments.len() - 2 {
            let a = segments[i + 0];
            let c = segments[i + 2];
            let b = &mut segments[i + 1];
            let min = a.min(c).as_ivec2();
            let max = a.max(c).as_ivec2();
            let mut clear = true;
            for x in min.x..=max.x {
                for y in min.y..=max.y {
                    clear &= walkable.contains(&ivec2(x, y));
                }
            }
            if clear {
                let new_b = (a + c) * 0.5;
                if b.distance(new_b) > 0.1 {
                    *b = new_b;
                    changed = true;
                }
            }
        }
        if !changed {
            break;
        }
    }
}

#[derive(Debug, Clone)]
pub struct HoldLocation {
    target: Vec2,
    facing: Vec2,
    last_dir: Vec2,
}
impl HoldLocation {
    pub fn new(target: Vec2, facing: Vec2) -> Self {
        Self {
            facing,
            target,
            last_dir: Vec2::ZERO,
        }
    }
    pub fn update(&mut self, out: &mut PacketSink, player: PlayerID, pos: Vec2) {
        let diff = (self.target + 0.5) - pos;
        let dir = match diff.length() {
            x if x < 0.3 => self.facing.clamp_length_max(1.) * 0.4, // TODO rotation not updating
            x if x < 1.0 => diff.normalize() * 0.6,
            _ => diff.normalize(),
        };
        if dir.distance(self.last_dir) > 0.1 {
            self.last_dir = dir;
            out.push(PacketS::Movement {
                player,
                dir,
                boost: false,
                pos: None,
            });
        }
    }
}
