/*
    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/>.

*/

pub mod conn_test;
pub mod list;
pub mod lobby;
pub mod register;

use crate::{conn_test::prune_connect_cache_task, list::r_list_options};
use hurrycurry_protocol::registry::Entry;
use list::{generate_html_list, generate_json_list, r_list};
use lobby::lobby_wrapper;
use log::{error, info};
use register::r_register;
use rocket::{Config, fairing::AdHoc, get, http::Header, routes, shield::Shield};
use std::{
    cmp::Reverse,
    collections::HashMap,
    env::var,
    net::{IpAddr, Ipv4Addr, SocketAddr},
    str::FromStr,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::{sync::RwLock, time::interval};

const MAX_SERVERS: usize = 128;

fn main() {
    env_logger::init_from_env("LOG");
    rustls::crypto::ring::default_provider()
        .install_default()
        .unwrap();

    let address = var("BIND_ADDR")
        .map(|a| IpAddr::from_str(&a).unwrap())
        .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST));
    let http_port = var("PORT").map(|p| p.parse().unwrap()).unwrap_or(27033);
    let lobby_port = var("LOBBY_PORT")
        .map(|p| p.parse().unwrap())
        .unwrap_or(27034);
    let lobby_addr = SocketAddr::new(address, lobby_port);

    let registry = Arc::new(RwLock::new(Registry::default()));

    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async move {
            tokio::task::spawn(Registry::update_loop(registry.clone()));
            tokio::task::spawn(prune_connect_cache_task());
            tokio::task::spawn(lobby_wrapper(registry.clone(), lobby_addr));
            rocket::build()
                .configure(Config {
                    address,
                    port: http_port,
                    ..Default::default()
                })
                .attach(Shield::new())
                .manage(registry)
                .attach(AdHoc::on_response("set server header", |_req, res| {
                    res.set_header(Header::new("server", "hurrycurry-registry"));
                    Box::pin(async {})
                }))
                .mount("/", routes![r_index, r_list, r_list_options, r_register])
                .ignite()
                .await
                .unwrap()
                .launch()
                .await
                .unwrap()
        });
}

#[derive(Default)]
struct Registry {
    json_response: Arc<str>,
    html_response: [Arc<str>; 4],
    entries: Vec<Entry>,
    servers: HashMap<u128, InternalEntry>,
}

impl Registry {
    pub async fn update_loop(r: Arc<RwLock<Self>>) {
        let mut interval = interval(Duration::from_secs(
            var("UPDATE_INTERVAL")
                .map(|e| e.parse::<u64>().unwrap())
                .unwrap_or(10),
        ));
        loop {
            interval.tick().await;
            if let Err(e) = r.write().await.update() {
                error!("update failed: {e}")
            }
        }
    }
    pub fn update(&mut self) -> anyhow::Result<()> {
        info!("updating list");
        self.remove_dead();

        let mut list = self
            .servers
            .values()
            .map(|e| Entry {
                name: e.name.clone(),
                address: e.address.keys().cloned().collect(),
                last_game: e.last_game,
                players_online: e.players_online,
                version: e.version,
            })
            .collect::<Vec<_>>();

        list.sort_by_key(|e| Reverse(e.players_online));

        self.json_response = generate_json_list(&list)?;
        self.html_response = generate_html_list(&list)?;
        self.entries = list;

        info!("done. {} servers registered", self.servers.len());
        Ok(())
    }
    pub fn remove_dead(&mut self) {
        self.servers.retain(|_, e| {
            e.address
                .retain(|_, updated| updated.elapsed() < Duration::from_secs(120));
            !e.address.is_empty()
        });
    }
}

#[derive(Debug)]
struct InternalEntry {
    name: String,
    address: HashMap<String, Instant>,
    players_online: usize,
    last_game: i64,
    version: (u32, u32),
}

#[allow(clippy::derivable_impls)]
impl Default for InternalEntry {
    fn default() -> Self {
        Self {
            address: HashMap::new(),
            last_game: 0,
            name: String::new(),
            players_online: 0,
            version: (0, 0),
        }
    }
}

#[get("/")]
fn r_index() -> &'static str {
    "Hurry Curry! Server Registry Service"
}
