use super::super::import_outcome::conditions_provide_company_context;
use super::actions::lowered_record_decoded_actions;
use super::conditions::lowered_record_decoded_conditions;
use super::effects::smp_runtime_effects_to_runtime_effects;
use crate::documents::RuntimeImportContext;
use crate::event::records::{RuntimeEventRecord, RuntimeEventRecordTemplate};
use crate::inspect::smp::events::SmpLoadedPackedEventRecordSummary;

pub(crate) fn smp_packed_record_to_runtime_event_record(
    record: &SmpLoadedPackedEventRecordSummary,
    runtime_context: &RuntimeImportContext,
) -> Option<Result<RuntimeEventRecord, String>> {
    if record.decode_status == "unsupported_framing" {
        return None;
    }
    if record.payload_family == "real_packed_v1" && record.compact_control.is_none() {
        return None;
    }

    let lowered_conditions = match lowered_record_decoded_conditions(record, runtime_context) {
        Ok(conditions) => conditions,
        Err(_) => return None,
    };
    let lowered_effects = match lowered_record_decoded_actions(record, runtime_context) {
        Ok(effects) => effects,
        Err(_) => return None,
    };
    let effects = match smp_runtime_effects_to_runtime_effects(
        &lowered_effects,
        runtime_context,
        conditions_provide_company_context(&lowered_conditions),
        false,
    ) {
        Ok(effects) => effects,
        Err(_) => return None,
    };

    Some((|| {
        let trigger_kind = record.trigger_kind.ok_or_else(|| {
            format!(
                "packed event record {} is missing trigger_kind",
                record.live_entry_id
            )
        })?;
        let active = record.active.unwrap_or(true);
        let marks_collection_dirty = record.marks_collection_dirty.unwrap_or(false);
        let one_shot = record.one_shot.unwrap_or(false);
        Ok(RuntimeEventRecordTemplate {
            record_id: record.live_entry_id,
            trigger_kind,
            active,
            marks_collection_dirty,
            one_shot,
            conditions: lowered_conditions,
            effects,
        }
        .into_runtime_record())
    })())
}

pub(crate) fn smp_runtime_record_template_to_runtime(
    record: &RuntimeEventRecordTemplate,
    runtime_context: &RuntimeImportContext,
    allow_condition_true_company: bool,
    allow_condition_true_player: bool,
) -> Result<RuntimeEventRecordTemplate, String> {
    Ok(RuntimeEventRecordTemplate {
        record_id: record.record_id,
        trigger_kind: record.trigger_kind,
        active: record.active,
        marks_collection_dirty: record.marks_collection_dirty,
        one_shot: record.one_shot,
        conditions: record.conditions.clone(),
        effects: smp_runtime_effects_to_runtime_effects(
            &record.effects,
            runtime_context,
            allow_condition_true_company,
            allow_condition_true_player,
        )?,
    })
}
