use anyhow::anyhow;
use jsonrpsee::ws_client::{WsClient, WsClientBuilder};
use url::Url;

#[derive(clap::Args, Debug)]
#[group(skip)]
pub struct CommonArgs {
	/// The URL for the RPC connection.
	#[arg(long, env = "JAM_RPC", default_value_t = String::from("ws://localhost:19800"))]
	pub rpc: String,
}

impl CommonArgs {
	pub fn rpc_url(&self, val_index: u16) -> anyhow::Result<Url> {
		let mut uri = Url::parse(&self.rpc)?;
		if val_index > 0 && uri.port().is_none() {
			return Err(anyhow!("Cannot increment port number for RPC URL without a port"));
		}
		let port = uri.port().and_then(|p| p.checked_add(val_index));
		uri.set_port(port).map_err(|()| anyhow!("Cannot set port number for RPC URL"))?;
		Ok(uri)
	}

	pub async fn connect_rpc(&self, val_index: u16) -> anyhow::Result<WsClient> {
		let uri = self.rpc_url(val_index)?;
		Ok(WsClientBuilder::default()
			.max_request_size(MAX_REQUEST_SIZE)
			.max_response_size(MAX_RESPONSE_SIZE)
			.build(&uri)
			.await?)
	}
}

const MAX_REQUEST_SIZE: u32 = 100 * 1024 * 1024;
const MAX_RESPONSE_SIZE: u32 = 100 * 1024 * 1024;
