Documentation
use {
    super::*,
    axum::extract::{Path, State},
    http_server::{
        self, common_routes,
        error::{OptionExt, ServerError, ServerResult},
        templates::{
            OrderHtml, PoolHtml, ProxyHtml, ReviewHtml, RouterHtml, UserHtml, UsersHtml,
            render_page,
        },
    },
};

pub use {
    http_server::{BitcoinStatus, SystemStatus},
    pool::PoolStatus,
    proxy::ProxyStatus,
    router::{OrderDetail, OrderRequest, OrderResponse, OrderSummary, RouterStatus, WalletInfo},
    users::{SessionDetail, UserDetail, UserSummary, WorkerDetail},
};

pub mod pool;
pub mod proxy;
pub mod router;
pub mod users;

mod pagination;

pub(crate) use pagination::{CountResponse, effective_limit, page_response};

fn decode_query_component(value: &str) -> ServerResult<String> {
    let value = value.replace('+', " ");
    urlencoding::decode(&value)
        .map(|value| value.into_owned())
        .map_err(|err| ServerError::BadRequest(format!("invalid query encoding: {err}")))
}

pub(crate) fn parse_query_pairs(raw: Option<&str>) -> ServerResult<Vec<(String, String)>> {
    let Some(raw) = raw else {
        return Ok(Vec::new());
    };

    raw.split('&')
        .filter(|pair| !pair.is_empty())
        .map(|pair| {
            let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
            Ok((decode_query_component(key)?, decode_query_component(value)?))
        })
        .collect()
}

fn parse_usize_query_param(name: &str, value: &str) -> ServerResult<usize> {
    value
        .parse()
        .map_err(|err| ServerError::BadRequest(format!("invalid {name} `{value}`: {err}")))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MiningStats {
    pub hashrate_1m: HashRate,
    pub hashrate_5m: HashRate,
    pub hashrate_15m: HashRate,
    pub hashrate_1hr: HashRate,
    pub hashrate_6hr: HashRate,
    pub hashrate_1d: HashRate,
    pub hashrate_7d: HashRate,
    pub sps_1m: f64,
    pub sps_5m: f64,
    pub sps_15m: f64,
    pub sps_1hr: f64,
    pub accepted_shares: u64,
    pub rejected_shares: u64,
    pub accepted_work: HashWork,
    pub rejected_work: HashWork,
    pub delivered_hash_days: HashDays,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
}

impl MiningStats {
    pub(crate) fn from_stats(stats: &Stats, now: Instant) -> Self {
        Self {
            hashrate_1m: stats.hashrate_1m(now),
            hashrate_5m: stats.hashrate_5m(now),
            hashrate_15m: stats.hashrate_15m(now),
            hashrate_1hr: stats.hashrate_1hr(now),
            hashrate_6hr: stats.hashrate_6hr(now),
            hashrate_1d: stats.hashrate_1d(now),
            hashrate_7d: stats.hashrate_7d(now),
            sps_1m: stats.sps_1m(now),
            sps_5m: stats.sps_5m(now),
            sps_15m: stats.sps_15m(now),
            sps_1hr: stats.sps_1hr(now),
            accepted_shares: stats.accepted_shares,
            rejected_shares: stats.rejected_shares,
            accepted_work: stats.accepted_work,
            rejected_work: stats.rejected_work,
            delivered_hash_days: stats.delivered_work().to_hash_days(),
            best_share: stats.best_share,
            last_share: stats.last_share_epoch_secs(now),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownstreamTotals {
    pub users: usize,
    pub workers: usize,
    pub accepted_shares: u64,
    pub rejected_shares: u64,
    pub accepted_work: HashWork,
    pub rejected_work: HashWork,
    pub delivered_hash_days: HashDays,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
}

impl DownstreamTotals {
    pub(crate) fn from_stats(users: usize, workers: usize, stats: &Stats, now: Instant) -> Self {
        Self {
            users,
            workers,
            accepted_shares: stats.accepted_shares,
            rejected_shares: stats.rejected_shares,
            accepted_work: stats.accepted_work,
            rejected_work: stats.rejected_work,
            delivered_hash_days: stats.delivered_work().to_hash_days(),
            best_share: stats.best_share,
            last_share: stats.last_share_epoch_secs(now),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpstreamTotals {
    pub users: usize,
    pub orders: usize,
    pub accepted_shares: u64,
    pub rejected_shares: u64,
    pub accepted_work: HashWork,
    pub rejected_work: HashWork,
    pub delivered_hash_days: HashDays,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Connects1h {
    pub total: usize,
    pub sessions: usize,
    pub probes: usize,
    pub rejects: usize,
    pub pending: usize,
}

impl Connects1h {
    pub(crate) fn from_downstream(connects: DownstreamConnects) -> Self {
        Self {
            total: connects.connects_1h,
            sessions: connects.sessions_1h,
            probes: connects.probes_1h,
            rejects: connects.routing_rejects_1h,
            pending: connects.pending_1h,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Disconnects1h {
    pub total: usize,
    pub client: usize,
    pub server: usize,
    pub trim: usize,
    pub rejects: usize,
}

impl Disconnects1h {
    pub(crate) fn from_downstream(connects: DownstreamConnects) -> Self {
        Self {
            total: connects.disconnects_1h,
            client: connects.client_1h,
            server: connects.server_1h,
            trim: connects.trim_1h,
            rejects: connects.reject_1h,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DownstreamStats {
    pub users: usize,
    pub workers: usize,
    pub sessions: usize,
    pub idle: usize,
    pub disconnected: usize,
    pub connects_1h: Connects1h,
    pub disconnects_1h: Disconnects1h,
    pub hashrate_1m: HashRate,
    pub hashrate_5m: HashRate,
    pub hashrate_15m: HashRate,
    pub hashrate_1hr: HashRate,
    pub hashrate_6hr: HashRate,
    pub hashrate_1d: HashRate,
    pub hashrate_7d: HashRate,
    pub sps_1m: f64,
    pub sps_5m: f64,
    pub sps_15m: f64,
    pub sps_1hr: f64,
    pub accepted_shares: u64,
    pub rejected_shares: u64,
    pub accepted_work: HashWork,
    pub rejected_work: HashWork,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
    pub totals: DownstreamTotals,
}

impl DownstreamStats {
    pub(crate) fn from_metatron(metatron: &Metatron, now: Instant) -> Self {
        let downstream = metatron.downstream(now);
        let traffic = &downstream.traffic;
        let connects = metatron.connections().downstream();

        Self {
            users: downstream.users,
            workers: downstream.workers,
            sessions: downstream.sessions,
            idle: downstream.idle,
            disconnected: metatron.total_disconnected(),
            connects_1h: Connects1h::from_downstream(connects),
            disconnects_1h: Disconnects1h::from_downstream(connects),
            hashrate_1m: traffic.hashrate_1m(now),
            hashrate_5m: traffic.hashrate_5m(now),
            hashrate_15m: traffic.hashrate_15m(now),
            hashrate_1hr: traffic.hashrate_1hr(now),
            hashrate_6hr: traffic.hashrate_6hr(now),
            hashrate_1d: traffic.hashrate_1d(now),
            hashrate_7d: traffic.hashrate_7d(now),
            sps_1m: traffic.sps_1m(now),
            sps_5m: traffic.sps_5m(now),
            sps_15m: traffic.sps_15m(now),
            sps_1hr: traffic.sps_1hr(now),
            accepted_shares: traffic.accepted_shares,
            rejected_shares: traffic.rejected_shares,
            accepted_work: traffic.accepted_work,
            rejected_work: traffic.rejected_work,
            best_share: traffic.best_share,
            last_share: traffic.last_share_epoch_secs(now),
            totals: DownstreamTotals::from_stats(
                metatron.total_users(),
                downstream.total_workers,
                &downstream.total,
                now,
            ),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpstreamStats {
    pub users: usize,
    pub workers: usize,
    pub orders: usize,
    pub pending: usize,
    pub disconnected: usize,
    pub disconnects_1h: usize,
    pub hashrate_1m: HashRate,
    pub hashrate_5m: HashRate,
    pub hashrate_15m: HashRate,
    pub hashrate_1hr: HashRate,
    pub hashrate_6hr: HashRate,
    pub hashrate_1d: HashRate,
    pub hashrate_7d: HashRate,
    pub sps_1m: f64,
    pub sps_5m: f64,
    pub sps_15m: f64,
    pub sps_1hr: f64,
    pub accepted_shares: u64,
    pub rejected_shares: u64,
    pub accepted_work: HashWork,
    pub rejected_work: HashWork,
    pub best_share: Option<Difficulty>,
    pub last_share: Option<u64>,
    pub totals: UpstreamTotals,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpstreamInfo {
    pub endpoint: String,
    pub upstream_address: Option<SocketAddr>,
    pub connected: bool,
    pub ping_ms: u128,
    pub difficulty: Difficulty,
    pub username: Username,
    pub enonce1: Extranonce,
    pub enonce2_size: usize,
    pub version_mask: Option<Version>,
}

impl UpstreamInfo {
    pub(crate) fn from_upstream(upstream: &Upstream) -> Self {
        Self {
            endpoint: upstream.endpoint().to_string(),
            upstream_address: upstream.upstream_address(),
            connected: upstream.is_connected(),
            ping_ms: upstream.ping_ms(),
            difficulty: upstream.difficulty(),
            username: upstream.username().clone(),
            enonce1: upstream.enonce1().clone(),
            enonce2_size: upstream.enonce2_size(),
            version_mask: upstream.version_mask(),
        }
    }
}