/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2025 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 glam::{IVec2, Vec2};
use serde::{Deserialize, Deserializer, Serialize};
use std::{
    collections::{BTreeMap, HashSet},
    sync::LazyLock,
};

pub use glam;

use crate::book::Book;

pub mod book;
pub mod helpers;
pub mod movement;
pub mod registry;

pub static VERSION: LazyLock<(u32, u32)> = LazyLock::new(|| {
    (
        env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(),
        env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(),
    )
});

#[test]
fn test_version_parse() {
    let _ = *VERSION;
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct PlayerID(#[serde(deserialize_with = "deser_i64")] pub i64);

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct ItemIndex(#[serde(deserialize_with = "deser_usize")] pub usize);
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct TileIndex(#[serde(deserialize_with = "deser_usize")] pub usize);
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct RecipeIndex(#[serde(deserialize_with = "deser_usize")] pub usize);
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(transparent)]
pub struct DemandIndex(#[serde(deserialize_with = "deser_usize")] pub usize);

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct Hand(#[serde(deserialize_with = "deser_usize")] pub usize);

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MapMetadata {
    pub name: String,
    pub players: usize,
    pub difficulty: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Demand {
    pub input: ItemIndex,
    pub output: Option<ItemIndex>,
    pub duration: f32,
    pub points: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[rustfmt::skip]
pub struct Gamedata {
    pub current_map: String,
    pub item_names: Vec<String>,
    pub tile_names: Vec<String>,
    pub tile_walkable: HashSet<TileIndex>,
    pub tile_placeable_items: BTreeMap<TileIndex, HashSet<ItemIndex>>,
    pub tile_interactable_empty: HashSet<TileIndex>,
    pub maps: Vec<(String, MapMetadata)>,
    pub bot_algos: Vec<String>,
    pub recipes: Vec<Recipe>,
    pub demands: Vec<Demand>,
    pub hand_count: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum PacketS {
    Join {
        name: String,
        character: Character,
        #[serde(default = "chef_class")]
        class: PlayerClass,
        #[serde(skip)]
        id: Option<PlayerID>, // used entity bots that cant receive a response
        #[serde(skip)]
        position: Option<Vec2>, // used entity bots that spawn in different locations
    },
    Leave {
        player: PlayerID,
    },
    Movement {
        player: PlayerID,
        dir: Vec2,
        boost: bool,
        pos: Option<Vec2>,
    },
    Interact {
        player: PlayerID,
        hand: Hand,
        #[serde(deserialize_with = "deser_ivec2_opt", default)]
        pos: Option<IVec2>,
    },
    Communicate {
        player: PlayerID,
        message: Option<Message>,
        timeout: Option<f32>,
        pin: Option<bool>,
    },
    Idle {
        paused: bool,
    },
    Ready,

    /// For use in replay sessions only
    ReplayTick {
        dt: f64,
    },

    #[serde(skip)]
    /// For internal use only (customers)
    ReplaceHand {
        player: PlayerID,
        hand: Hand,
        item: Option<ItemIndex>,
    },
    #[serde(skip)]
    /// For internal use only (customers)
    ApplyScore(Score),
    #[serde(skip)]
    /// For internal use only (customers)
    Effect {
        player: PlayerID,
        name: String,
    },
}

#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize)]
pub struct Character {
    #[serde(deserialize_with = "deser_i32", default)]
    pub color: i32,
    #[serde(deserialize_with = "deser_i32", default)]
    pub hairstyle: i32,
    #[serde(deserialize_with = "deser_i32", default)]
    pub headwear: i32,
}

fn chef_class() -> PlayerClass {
    PlayerClass::Chef
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PlayerClass {
    Chef,
    Bot,
    Customer,
    Tram,
}
impl PlayerClass {
    pub fn is_cheflike(&self) -> bool {
        matches!(self, Self::Bot | Self::Chef)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Message {
    Translation { id: String, params: Vec<Message> },
    Text(String),
    Item(ItemIndex),
    Tile(TileIndex),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum PacketC {
    Version {
        minor: u32,
        major: u32,
        supports_bincode: bool,
    },
    Joined {
        id: PlayerID,
    },
    Data {
        data: Box<Gamedata>,
    },
    AddPlayer {
        id: PlayerID,
        position: Vec2,
        class: PlayerClass,
        character: Character,
        name: String,
    },
    RemovePlayer {
        id: PlayerID,
    },
    Movement {
        player: PlayerID,
        pos: Vec2,
        rot: f32,
        dir: Vec2,
        boost: bool,
    },
    Pause {
        state: bool,
    },
    MoveItem {
        from: ItemLocation,
        to: ItemLocation,
    },
    SetItem {
        location: ItemLocation,
        item: Option<ItemIndex>,
    },
    ClearProgress {
        item: ItemLocation,
    },
    SetProgress {
        player: Option<PlayerID>,
        item: ItemLocation,
        position: f32,
        speed: f32,
        warn: bool,
    },
    UpdateMap {
        tile: IVec2,
        kind: Option<TileIndex>,
        neighbors: [Option<TileIndex>; 4],
    },
    FlushMap,
    Communicate {
        player: PlayerID,
        message: Option<Message>,
        timeout: Option<MessageTimeout>,
    },
    Effect {
        name: String,
        player: PlayerID,
    },
    ServerMessage {
        message: Message,
        error: bool,
    },
    ServerHint {
        position: Option<IVec2>,
        message: Option<Message>,
        player: PlayerID,
    },
    Score(Score),
    SetIngame {
        state: bool,
        lobby: bool,
    },
    Menu(Menu),
    MovementSync {
        player: PlayerID,
    },
    Environment {
        effects: HashSet<String>,
    },
    TutorialEnded {
        player: PlayerID,
        item: ItemIndex,
        success: bool,
    },
    Redirect {
        uri: Vec<String>,
    },

    /// For use in replay sessions only
    ReplayStart,
    ReplayStop,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "menu", content = "data")]
pub enum Menu {
    Score(Score),
    Scoreboard(Scoreboard),
    Book(Book),
    AnnounceStart,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
pub struct MessageTimeout {
    pub remaining: f32,
    pub initial: f32,
    pub pinned: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Score {
    pub time_remaining: f64,
    pub stars: u8,
    pub points: i64,
    pub demands_failed: usize,
    pub demands_completed: usize,
    pub players: usize,
    pub active_recipes: usize,
    pub passive_recipes: usize,
    pub instant_recipes: usize,
}

#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub struct Scoreboard {
    pub map: Option<String>,
    pub plays: usize,
    pub best: Vec<ScoreboardEntry>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ScoreboardEntry {
    pub players: Vec<String>,
    pub score: Score,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Recipe {
    Passive {
        speed: f32,
        revert_speed: Option<f32>,
        tile: Option<TileIndex>,
        input: ItemIndex,
        output: Option<ItemIndex>,
        warn: bool,
    },
    Active {
        speed: f32,
        tile: Option<TileIndex>,
        input: ItemIndex,
        outputs: [Option<ItemIndex>; 2],
    },
    Instant {
        tile: Option<TileIndex>,
        inputs: [Option<ItemIndex>; 2],
        outputs: [Option<ItemIndex>; 2],
        points: i64,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ItemLocation {
    Tile(IVec2),
    Player(PlayerID, Hand),
}

fn deser_i64<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
    let x = f64::deserialize(deserializer)?;
    Ok(x.trunc() as i64)
}
fn deser_i32<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i32, D::Error> {
    let x = f64::deserialize(deserializer)?;
    Ok(x.trunc() as i32)
}
fn deser_usize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<usize, D::Error> {
    let x = f64::deserialize(deserializer)?;
    Ok(x.trunc() as usize)
}
fn deser_ivec2_opt<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<IVec2>, D::Error> {
    let x = Option::<Vec2>::deserialize(deserializer)?;
    Ok(x.map(|v| v.as_ivec2()))
}
