use crate::gen::conditions::{parse_spends, SpendBundleConditions};
use crate::gen::validation_error::ValidationErr;
use crate::generator_rom::{COST_PER_BYTE, GENERATOR_ROM};
use clvmr::allocator::Allocator;
use clvmr::chia_dialect::ChiaDialect;
use clvmr::reduction::Reduction;
use clvmr::run_program::run_program;
use clvmr::serde::node_from_bytes;
pub fn run_block_generator<GenBuf: AsRef<[u8]>>(
a: &mut Allocator,
program: &[u8],
block_refs: &[GenBuf],
max_cost: u64,
flags: u32,
) -> Result<SpendBundleConditions, ValidationErr> {
let byte_cost = program.len() as u64 * COST_PER_BYTE;
let generator_rom = node_from_bytes(a, &GENERATOR_ROM)?;
let program = node_from_bytes(a, program)?;
let mut args = a.null();
for g in block_refs.iter().rev() {
let ref_gen = a.new_atom(g.as_ref())?;
args = a.new_pair(ref_gen, args)?;
}
args = a.new_pair(args, a.null())?;
let args = a.new_pair(args, a.null())?;
let args = a.new_pair(program, args)?;
let dialect = ChiaDialect::new(flags);
let Reduction(clvm_cost, generator_output) =
run_program(a, &dialect, generator_rom, args, max_cost - byte_cost)?;
let mut result = parse_spends(a, generator_output, max_cost - clvm_cost - byte_cost, flags)?;
result.cost += clvm_cost + byte_cost;
Ok(result)
}