use jam_std_common::{hash_raw, Node, NodeError};
use jam_types::{AnyHash, Hash, SegmentBytes, SegmentTreeRoot};

/// Fetches a single page from the DA.
pub async fn fetch_page(
	node: &dyn Node,
	root: SegmentTreeRoot,
	index: u16,
	expected_hash: Hash,
) -> Result<SegmentBytes, NodeError> {
	log::trace!("Fetching page from segment {root}, index {index}");
	let segment = node
		.fetch_segments(root, vec![index])
		.await?
		.pop()
		.ok_or_else(|| NodeError::Other(format!("No segments for segment-root {root}")))?;
	let actual_hash = hash_raw(segment.as_ref());
	if expected_hash != actual_hash {
		log::debug!(
			"Hash mismatch for page from segment {root}, index {index}: \
			expected {} vs. actual {}",
			AnyHash(expected_hash),
			AnyHash(actual_hash)
		);
		return Err(NodeError::Other(format!(
			"Segment hash mismatch for segment-root {root}, index {index}"
		)));
	}
	Ok(segment)
}
