use crate::event::conditions::RuntimeCondition;
use crate::inspect::smp::events::{
    SmpLoadedPackedEventConditionRowSummary, SmpLoadedPackedEventRecordSummary,
};

pub(crate) fn conditions_provide_company_context(conditions: &[RuntimeCondition]) -> bool {
    conditions.iter().any(|condition| {
        matches!(
            condition,
            RuntimeCondition::CompanyNumericThreshold { .. }
                | RuntimeCondition::CompanyVariableThreshold { .. }
                | RuntimeCondition::CompanyTerritoryNumericThreshold { .. }
        )
    })
}

pub(crate) fn record_has_world_state_condition_rows(
    record: &SmpLoadedPackedEventRecordSummary,
) -> bool {
    record
        .decoded_conditions
        .iter()
        .any(runtime_condition_is_world_state)
        || record
            .standalone_condition_rows
            .iter()
            .any(ordinary_condition_row_is_world_state_family)
}

pub(crate) fn runtime_condition_is_world_state(condition: &RuntimeCondition) -> bool {
    matches!(
        condition,
        RuntimeCondition::WorldVariableThreshold { .. }
            | RuntimeCondition::SpecialConditionThreshold { .. }
            | RuntimeCondition::CandidateAvailabilityThreshold { .. }
            | RuntimeCondition::NamedLocomotiveAvailabilityThreshold { .. }
            | RuntimeCondition::NamedLocomotiveCostThreshold { .. }
            | RuntimeCondition::CargoProductionSlotThreshold { .. }
            | RuntimeCondition::CargoProductionTotalThreshold { .. }
            | RuntimeCondition::FactoryProductionTotalThreshold { .. }
            | RuntimeCondition::FarmMineProductionTotalThreshold { .. }
            | RuntimeCondition::OtherCargoProductionTotalThreshold { .. }
            | RuntimeCondition::LimitedTrackBuildingAmountThreshold { .. }
            | RuntimeCondition::TerritoryAccessCostThreshold { .. }
            | RuntimeCondition::EconomicStatusCodeThreshold { .. }
            | RuntimeCondition::WorldFlagEquals { .. }
    )
}

pub(crate) fn ordinary_condition_row_is_world_state_family(
    row: &SmpLoadedPackedEventConditionRowSummary,
) -> bool {
    row.metric.as_deref().is_some_and(|metric| {
        metric.contains("Special Condition")
            || metric.contains("Candidate Availability")
            || metric.contains("Named Locomotive")
            || metric.contains("Cargo Production")
            || metric.contains("Factory Production")
            || metric.contains("Farm/Mine Production")
            || metric.contains("Other Cargo Production")
            || metric.contains("Limited Track Building Amount")
            || metric.contains("Territory Access Cost")
            || metric.contains("Economic Status")
            || metric.contains("World Flag")
    }) || row.semantic_family.as_deref().is_some_and(|family| {
        matches!(
            family,
            "world_state_threshold" | "world_scalar_threshold" | "world_flag_equals"
        )
    })
}
