//! Service and ServiceFactory implementation. Specialized wrapper over bizinikiwi service.

// std
use std::{sync::Arc, time::Duration};

use pezcumulus_client_cli::CollatorOptions;
// Pezcumulus Imports
#[cfg(not(feature = "tanssi"))]
use pezcumulus_client_collator::service::CollatorService;
use pezcumulus_client_consensus_common::TeyrChainBlockImport as TTeyrChainBlockImport;
#[cfg(not(feature = "tanssi"))]
use pezcumulus_client_consensus_proposer::Proposer;
use pezcumulus_client_service::{
    build_network, build_relay_chain_interface, prepare_node_config, start_relay_chain_tasks,
    BuildNetworkParams, CollatorSybilResistance, DARecoveryProfile, TeyrChainHostFunctions,
    StartRelayChainTasksParams,
};
#[cfg(not(feature = "tanssi"))]
use pezcumulus_primitives_core::relay_chain::CollatorPair;
#[cfg(feature = "async-backing")]
use pezcumulus_primitives_core::relay_chain::ValidationCode;
use pezcumulus_primitives_core::ParaId;
#[cfg(not(feature = "tanssi"))]
use pezcumulus_relay_chain_interface::OverseerHandle;
use pezcumulus_relay_chain_interface::RelayChainInterface;
// Bizinikiwi Imports
use pezframe_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE;
// Local Runtime Types
use generic_runtime_template::{
    apis::RuntimeApi,
    opaque::{Block, Hash},
};
use pezsc_client_api::Backend;
use pezsc_consensus::ImportQueue;
use pezsc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY};
use pezsc_network::NetworkBlock;
use pezsc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager};
#[cfg(not(feature = "tanssi"))]
use pezsc_telemetry::TelemetryHandle;
use pezsc_telemetry::{Telemetry, TelemetryWorker, TelemetryWorkerHandle};
use pezsc_transaction_pool_api::OffchainTransactionPoolFactory;
#[cfg(not(feature = "tanssi"))]
use pezsp_keystore::KeystorePtr;
#[cfg(not(feature = "tanssi"))]
use bizinikiwi_prometheus_endpoint::Registry;

type TeyrChainExecutor = WasmExecutor<TeyrChainHostFunctions>;

type TeyrChainClient = TFullClient<Block, RuntimeApi, TeyrChainExecutor>;

type TeyrChainBackend = TFullBackend<Block>;

type TeyrChainBlockImport = TTeyrChainBlockImport<Block, Arc<TeyrChainClient>, TeyrChainBackend>;

/// Assembly of PartialComponents (enough to run chain ops subcommands)
pub type Service = PartialComponents<
    TeyrChainClient,
    TeyrChainBackend,
    (),
    pezsc_consensus::DefaultImportQueue<Block>,
    pezsc_transaction_pool::TransactionPoolHandle<Block, TeyrChainClient>,
    (TeyrChainBlockImport, Option<Telemetry>, Option<TelemetryWorkerHandle>),
>;

/// Starts a `ServiceBuilder` for a full service.
///
/// Use this macro if you don't actually need the full service, but just the builder in order to
/// be able to perform chain operations.
pub fn new_partial(config: &Configuration) -> Result<Service, pezsc_service::Error> {
    let telemetry = config
        .telemetry_endpoints
        .clone()
        .filter(|x| !x.is_empty())
        .map(|endpoints| -> Result<_, pezsc_telemetry::Error> {
            let worker = TelemetryWorker::new(16)?;
            let telemetry = worker.handle().new_telemetry(endpoints);
            Ok((worker, telemetry))
        })
        .transpose()?;

    let heap_pages = config
        .executor
        .default_heap_pages
        .map_or(DEFAULT_HEAP_ALLOC_STRATEGY, |h| HeapAllocStrategy::Static { extra_pages: h as _ });

    let executor = TeyrChainExecutor::builder()
        .with_execution_method(config.executor.wasm_method)
        .with_onchain_heap_alloc_strategy(heap_pages)
        .with_offchain_heap_alloc_strategy(heap_pages)
        .with_max_runtime_instances(config.executor.max_runtime_instances)
        .with_runtime_cache_size(config.executor.runtime_cache_size)
        .build();

    let (client, backend, keystore_container, task_manager) =
        pezsc_service::new_full_parts_record_import::<Block, RuntimeApi, _>(
            config,
            telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()),
            executor,
            true,
        )?;
    let client = Arc::new(client);

    let telemetry_worker_handle = telemetry.as_ref().map(|(worker, _)| worker.handle());

    let telemetry = telemetry.map(|(worker, telemetry)| {
        task_manager.spawn_handle().spawn("telemetry", None, worker.run());
        telemetry
    });

    let transaction_pool = Arc::from(
        pezsc_transaction_pool::Builder::new(
            task_manager.spawn_essential_handle(),
            client.clone(),
            config.role.is_authority().into(),
        )
        .with_options(config.transaction_pool.clone())
        .with_prometheus(config.prometheus_registry())
        .build(),
    );

    #[cfg(feature = "tanssi")]
    let (block_import, import_queue) =
        import_queue(config, client.clone(), backend.clone(), &task_manager);
    #[cfg(not(feature = "tanssi"))]
    let (block_import, import_queue) = {
        let block_import = TeyrChainBlockImport::new(client.clone(), backend.clone());
        (
            block_import.clone(),
            build_import_queue(
                client.clone(),
                block_import,
                config,
                telemetry.as_ref().map(|telemetry| telemetry.handle()),
                &task_manager,
            )?,
        )
    };

    Ok(PartialComponents {
        backend,
        client,
        import_queue,
        keystore_container,
        task_manager,
        transaction_pool,
        select_chain: (),
        other: (block_import, telemetry, telemetry_worker_handle),
    })
}

/// Start a node with the given teyrchain `Configuration` and relay chain `Configuration`.
///
/// This is the actual implementation that is abstract over the executor and the runtime api.
#[pezsc_tracing::logging::prefix_logs_with("TeyrChain")]
async fn start_node_impl(
    teyrchain_config: Configuration,
    pezkuwi_config: Configuration,
    collator_options: CollatorOptions,
    para_id: ParaId,
    hwbench: Option<pezsc_sysinfo::HwBench>,
) -> pezsc_service::error::Result<(TaskManager, Arc<TeyrChainClient>)> {
    let teyrchain_config = prepare_node_config(teyrchain_config);

    let params = new_partial(&teyrchain_config)?;
    #[cfg(not(feature = "tanssi"))]
    let (block_import, mut telemetry, telemetry_worker_handle) = params.other;
    #[cfg(feature = "tanssi")]
    let (_, mut telemetry, telemetry_worker_handle) = params.other;
    let net_config = pezsc_network::config::FullNetworkConfiguration::<
        _,
        _,
        pezsc_network::NetworkWorker<Block, Hash>,
    >::new(
        &teyrchain_config.network,
        teyrchain_config.prometheus_config.as_ref().map(|cfg| cfg.registry.clone()),
    );

    let client = params.client.clone();
    let backend = params.backend.clone();
    let mut task_manager = params.task_manager;

    let relay_chain_interface = build_relay_chain_interface(
        pezkuwi_config,
        &teyrchain_config,
        telemetry_worker_handle,
        &mut task_manager,
        collator_options.clone(),
        hwbench.clone(),
    )
    .await
    .map_err(|e| pezsc_service::Error::Application(Box::new(e) as Box<_>))?;

    #[cfg(not(feature = "tanssi"))]
    let (relay_chain_interface, collator_key) = relay_chain_interface;
    #[cfg(feature = "tanssi")]
    let (relay_chain_interface, _) = relay_chain_interface;

    let validator = teyrchain_config.role.is_authority();
    #[cfg(not(feature = "tanssi"))]
    let prometheus_registry = teyrchain_config.prometheus_registry().cloned();
    let transaction_pool = params.transaction_pool.clone();
    let import_queue_service = params.import_queue.service();

    let (network, system_rpc_tx, tx_handler_controller, sync_service) =
        build_network(BuildNetworkParams {
            teyrchain_config: &teyrchain_config,
            net_config,
            client: client.clone(),
            transaction_pool: transaction_pool.clone(),
            para_id,
            spawn_handle: task_manager.spawn_handle(),
            relay_chain_interface: relay_chain_interface.clone(),
            import_queue: params.import_queue,
            sybil_resistance_level: CollatorSybilResistance::Resistant, // because of Aura
        })
        .await?;

    if teyrchain_config.offchain_worker.enabled {
        use futures::FutureExt;
        let offchain_workers =
            pezsc_offchain::OffchainWorkers::new(pezsc_offchain::OffchainWorkerOptions {
                runtime_api_provider: client.clone(),
                is_validator: teyrchain_config.role.is_authority(),
                keystore: Some(params.keystore_container.keystore()),
                offchain_db: backend.offchain_storage(),
                transaction_pool: Some(OffchainTransactionPoolFactory::new(
                    transaction_pool.clone(),
                )),
                network_provider: Arc::new(network.clone()),
                enable_http_requests: false,
                custom_extensions: |_| vec![],
            })?;

        task_manager.spawn_handle().spawn(
            "offchain-workers-runner",
            "offchain-work",
            offchain_workers.run(client.clone(), task_manager.spawn_handle()).boxed(),
        );
    }

    let rpc_builder = {
        let client = client.clone();
        let transaction_pool = transaction_pool.clone();

        Box::new(move |_| {
            let deps =
                crate::rpc::FullDeps { client: client.clone(), pool: transaction_pool.clone() };

            crate::rpc::create_full(deps).map_err(Into::into)
        })
    };

    pezsc_service::spawn_tasks(pezsc_service::SpawnTasksParams {
        rpc_builder,
        client: client.clone(),
        transaction_pool: transaction_pool.clone(),
        task_manager: &mut task_manager,
        config: teyrchain_config,
        keystore: params.keystore_container.keystore(),
        #[cfg(not(feature = "async-backing"))]
        backend,
        #[cfg(feature = "async-backing")]
        backend: backend.clone(),
        network: network.clone(),
        sync_service: sync_service.clone(),
        system_rpc_tx,
        tx_handler_controller,
        telemetry: telemetry.as_mut(),
    })?;

    if let Some(hwbench) = hwbench {
        pezsc_sysinfo::print_hwbench(&hwbench);
        // Here you can check whether the hardware meets your chains' requirements. Putting a link
        // in there and swapping out the requirements for your own are probably a good idea. The
        // requirements for a para-chain are dictated by its relay-chain.
        match SUBSTRATE_REFERENCE_HARDWARE.check_hardware(&hwbench, false) {
            Err(err) if validator => {
                log::warn!(
                    "⚠️  The hardware does not meet the minimal requirements {} for role \
                     'Authority'.",
                    err
                );
            }
            _ => {}
        }

        if let Some(ref mut telemetry) = telemetry {
            let telemetry_handle = telemetry.handle();
            task_manager.spawn_handle().spawn(
                "telemetry_hwbench",
                None,
                pezsc_sysinfo::initialize_hwbench_telemetry(telemetry_handle, hwbench),
            );
        }
    }

    let announce_block = {
        let sync_service = sync_service.clone();
        Arc::new(move |hash, data| sync_service.announce_block(hash, data))
    };

    let relay_chain_slot_duration = Duration::from_secs(6);

    let overseer_handle = relay_chain_interface
        .overseer_handle()
        .map_err(|e| pezsc_service::Error::Application(Box::new(e)))?;

    start_relay_chain_tasks(StartRelayChainTasksParams {
        client: client.clone(),
        announce_block: announce_block.clone(),
        para_id,
        relay_chain_interface: relay_chain_interface.clone(),
        task_manager: &mut task_manager,
        da_recovery_profile: if validator {
            DARecoveryProfile::Collator
        } else {
            DARecoveryProfile::FullNode
        },
        import_queue: import_queue_service,
        relay_chain_slot_duration,
        recovery_handle: Box::new(overseer_handle.clone()),
        sync_service: sync_service.clone(),
    })?;

    #[cfg(not(feature = "tanssi"))]
    if validator {
        start_consensus(
            client.clone(),
            #[cfg(feature = "async-backing")]
            backend.clone(),
            block_import,
            prometheus_registry.as_ref(),
            telemetry.as_ref().map(|t| t.handle()),
            &task_manager,
            relay_chain_interface.clone(),
            transaction_pool,
            params.keystore_container.keystore(),
            relay_chain_slot_duration,
            para_id,
            collator_key.expect("Command line arguments do not allow this. qed"),
            overseer_handle,
            announce_block,
        )?;
    }

    Ok((task_manager, client))
}

#[cfg(feature = "tanssi")]
pub fn import_queue(
    teyrchain_config: &Configuration,
    client: Arc<TeyrChainClient>,
    backend: Arc<TeyrChainBackend>,
    task_manager: &TaskManager,
) -> (TeyrChainBlockImport, pezsc_consensus::BasicQueue<Block>) {
    // The nimbus import queue ONLY checks the signature correctness
    // Any other checks corresponding to the author-correctness should be done
    // in the runtime
    let block_import = TeyrChainBlockImport::new(client.clone(), backend);

    let import_queue = nimbus_consensus::import_queue(
        client,
        block_import.clone(),
        move |_, _| async move {
            let time = pezsp_timestamp::InherentDataProvider::from_system_time();

            Ok((time,))
        },
        &task_manager.spawn_essential_handle(),
        teyrchain_config.prometheus_registry(),
        false,
    )
    .expect("function never fails");

    (block_import, import_queue)
}

/// Build the import queue for the teyrchain runtime.
#[cfg(not(feature = "tanssi"))]
fn build_import_queue(
    client: Arc<TeyrChainClient>,
    block_import: TeyrChainBlockImport,
    config: &Configuration,
    telemetry: Option<TelemetryHandle>,
    task_manager: &TaskManager,
) -> Result<pezsc_consensus::DefaultImportQueue<Block>, pezsc_service::Error> {
    Ok(pezcumulus_client_consensus_aura::equivocation_import_queue::fully_verifying_import_queue::<
        pezsp_consensus_aura::sr25519::AuthorityPair,
        _,
        _,
        _,
        _,
    >(
        client,
        block_import,
        move |_, _| async move {
            let timestamp = pezsp_timestamp::InherentDataProvider::from_system_time();
            Ok(timestamp)
        },
        &task_manager.spawn_essential_handle(),
        config.prometheus_registry(),
        telemetry,
    ))
}

#[cfg(not(feature = "tanssi"))]
fn start_consensus(
    client: Arc<TeyrChainClient>,
    #[cfg(feature = "async-backing")] backend: Arc<TeyrChainBackend>,
    block_import: TeyrChainBlockImport,
    prometheus_registry: Option<&Registry>,
    telemetry: Option<TelemetryHandle>,
    task_manager: &TaskManager,
    relay_chain_interface: Arc<dyn RelayChainInterface>,
    transaction_pool: Arc<pezsc_transaction_pool::TransactionPoolHandle<Block, TeyrChainClient>>,
    keystore: KeystorePtr,
    relay_chain_slot_duration: Duration,
    para_id: ParaId,
    collator_key: CollatorPair,
    overseer_handle: OverseerHandle,
    announce_block: Arc<dyn Fn(Hash, Option<Vec<u8>>) + Send + Sync>,
) -> Result<(), pezsc_service::Error> {
    #[cfg(not(feature = "async-backing"))]
    use pezcumulus_client_consensus_aura::collators::basic::{self as basic_aura, Params};
    #[cfg(feature = "async-backing")]
    use pezcumulus_client_consensus_aura::collators::lookahead::{self as aura, Params};

    let proposer_factory = pezsc_basic_authorship::ProposerFactory::with_proof_recording(
        task_manager.spawn_handle(),
        client.clone(),
        transaction_pool,
        prometheus_registry,
        telemetry.clone(),
    );

    let proposer = Proposer::new(proposer_factory);

    let collator_service = CollatorService::new(
        client.clone(),
        Arc::new(task_manager.spawn_handle()),
        announce_block,
        client.clone(),
    );

    let params = Params {
        create_inherent_data_providers: move |_, ()| async move { Ok(()) },
        block_import,
        #[cfg(not(feature = "async-backing"))]
        para_client: client,
        #[cfg(feature = "async-backing")]
        para_client: client.clone(),
        #[cfg(feature = "async-backing")]
        para_backend: backend,
        relay_client: relay_chain_interface,
        #[cfg(feature = "async-backing")]
        code_hash_provider: move |block_hash| {
            client.code_at(block_hash).ok().map(ValidationCode).map(|c| c.hash())
        },
        keystore,
        collator_key,
        para_id,
        overseer_handle,
        relay_chain_slot_duration,
        proposer,
        collator_service,
        // Very limited proposal time.
        #[cfg(not(feature = "async-backing"))]
        authoring_duration: Duration::from_millis(500),
        #[cfg(feature = "async-backing")]
        authoring_duration: Duration::from_millis(1500),
        #[cfg(not(feature = "async-backing"))]
        collation_request_receiver: None,
        #[cfg(feature = "async-backing")]
        reinitialize: false,
        #[cfg(feature = "async-backing")]
        max_pov_percentage: None,
    };

    #[cfg(not(feature = "async-backing"))]
    let fut = basic_aura::run::<Block, pezsp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _>(
        params,
    );
    #[cfg(feature = "async-backing")]
    let fut = aura::run::<Block, pezsp_consensus_aura::sr25519::AuthorityPair, _, _, _, _, _, _, _, _>(
        params,
    );
    task_manager.spawn_essential_handle().spawn("aura", None, fut);

    Ok(())
}

/// Start a teyrchain node.
pub async fn start_teyrchain_node(
    teyrchain_config: Configuration,
    pezkuwi_config: Configuration,
    collator_options: CollatorOptions,
    para_id: ParaId,
    hwbench: Option<pezsc_sysinfo::HwBench>,
) -> pezsc_service::error::Result<(TaskManager, Arc<TeyrChainClient>)> {
    start_node_impl(teyrchain_config, pezkuwi_config, collator_options, para_id, hwbench).await
}
