/*
    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::book::Book;
use glam::{IVec2, Vec2, Vec3};
use helpers::deser::*;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    sync::LazyLock,
};

pub use glam;

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;
}

pub const KEEPALIVE_INTERVAL: f32 = 1.;

#[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, Default)]
pub struct MapMetadata {
    pub name: String,
    pub display_name: String,
    pub players: usize,
    pub difficulty: i32,
    pub hand_count: usize,
    pub demand_items: Vec<String>,
}

#[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)]
pub struct Serverdata {
    pub name: String,
    pub motd: Option<String>,
    pub maps: Vec<MapMetadata>,
    pub bot_algos: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Gamedata {
    pub metadata: MapMetadata,
    pub item_names: Vec<String>,
    pub tile_names: Vec<String>,
    pub tile_collide: HashSet<TileIndex>,
    #[serde(deserialize_with = "deser_tile_index_map")]
    pub tile_placeable_items: BTreeMap<TileIndex, HashSet<ItemIndex>>,
    pub tile_placeable_any: HashSet<TileIndex>,
    pub tile_interactable_empty: HashSet<TileIndex>,
    pub tile_avoid_pathfinding: HashSet<TileIndex>,
    pub recipes: Vec<Recipe>,
    pub demands: Vec<Demand>,
    pub hand_count: usize,
    pub flags: GamedataFlags,
}

#[rustfmt::skip]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GamedataFlags {
    #[serde(default)] pub disable_unknown_orders: bool,
}

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

#[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,
        target: Option<ItemLocation>,
    },
    Communicate {
        player: PlayerID,
        message: Option<Message>,
        timeout: Option<f32>,
        pin: Option<bool>,
    },
    Idle {
        paused: bool,
    },
    Keepalive,
    Ready,

    InitiateVote {
        player: PlayerID,
        subject: VoteSubject,
    },
    CastVote {
        player: PlayerID,
        agree: bool,
    },

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

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

    /// For internal use only (customers)
    #[serde(skip)]
    ApplyScore(Score),

    /// For internal use only (customers)
    #[serde(skip)]
    Effect {
        effect: Effect,
        location: ItemLocation,
    },

    /// Used internally and only used when built with debug_events
    #[serde(skip)]
    Debug(DebugEvent),
}

#[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,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PlayerClass {
    Chef,
    Bot,
    Customer,
    Tram,
}

#[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),
}

pub fn version() -> PacketC {
    PacketC::Version {
        major: VERSION.0,
        minor: VERSION.1,
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum PacketC {
    Version {
        minor: u32,
        major: u32,
    },
    Joined {
        id: PlayerID,
    },
    ServerData(Box<Serverdata>),
    GameData(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,
        #[serde(skip_serializing_if = "is_false")]
        sync: bool,
    },
    Pause {
        state: bool,
    },
    MoveItem {
        from: ItemLocation,
        to: ItemLocation,
    },
    SetItem {
        location: ItemLocation,
        item: Option<ItemIndex>,
    },
    ClearProgress {
        item: ItemLocation,
    },
    SetProgress {
        players: BTreeSet<PlayerID>,
        item: ItemLocation,
        position: f32,
        speed: f32,
        warn: bool,
    },
    UpdateMap {
        changes: Vec<(IVec2, Vec<TileIndex>)>,
    },
    Communicate {
        player: PlayerID,
        message: Option<Message>,
        timeout: Option<MessageTimeout>,
    },
    Effect {
        #[serde(flatten)]
        effect: Effect,
        location: ItemLocation,
    },
    ServerMessage {
        message: Message,
        error: bool,
    },
    ServerHint {
        position: Option<IVec2>,
        message: Option<Message>,
        player: PlayerID,
    },
    Score(Score),
    SetIngame {
        state: bool,
        lobby: bool,
    },
    Menu(Menu),
    Environment {
        effects: HashSet<String>,
    },
    TutorialEnded {
        player: PlayerID,
        item: ItemIndex,
        success: bool,
    },

    Disconnect {
        reason: Message,
    },
    Redirect {
        uri: Vec<String>,
    },

    VoteStarted {
        initiated_by: PlayerID,
        subject: VoteSubject,
        message: Message,
        timeout: f32,
    },
    VoteUpdated {
        total: usize,
        agree: usize,
        reject: usize,
    },
    VoteEnded {
        result: bool,
    },
    SpectatorCount {
        count: usize,
    },

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

    /// Only used when built with debug_events
    Debug(DebugEvent),
}

fn is_false(x: &bool) -> bool {
    !*x
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case", tag = "action")]
pub enum VoteSubject {
    StartGame { config: GameConfig },
    EndGame,
    RestartGame,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
pub struct GameConfig {
    pub map: String,
    pub hand_count: Option<usize>,
    pub timer: Option<f32>,
    #[serde(default)]
    pub bots: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "effect")]
pub enum Effect {
    Satisfied,
    Angry,
    Points { amount: i64 },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "menu", content = "data")]
pub enum Menu {
    Score(Score),
    Scoreboard(Scoreboard),
    Book(Book),
    MapSelector,
    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: f32,
    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),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DebugEvent {
    pub key: String,
    pub color: Vec3,
    pub display: DebugEventDisplay,
    pub timeout: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "ty")]
pub enum DebugEventDisplay {
    Path { player: PlayerID, points: Vec<Vec2> },
    Label { pos: ItemLocation, text: String },
}
