use crate::inspect::smp::common::SmpSaveTaggedCollectionHeaderProbe;
use crate::inspect::smp::world::*;

pub(in crate::inspect::smp) fn derive_selection_only_company_roster_from_save_world_probe(
    probe: &SmpSaveWorldSelectionContextProbe,
    header_probe: Option<&SmpSaveTaggedCollectionHeaderProbe>,
) -> Option<SmpLoadedCompanyRoster> {
    Some(SmpLoadedCompanyRoster {
        source_kind: format!("{}-company-selection-only", probe.source_kind),
        semantic_family: "scenario-selected-company-context".to_string(),
        observed_entry_count: header_probe
            .map(|probe| probe.live_record_count as usize)
            .unwrap_or(0),
        selected_company_id: Some(probe.selected_company_id),
        entries: Vec::new(),
    })
}

pub(in crate::inspect::smp) fn derive_selection_only_chairman_profile_table_from_save_world_probe(
    probe: &SmpSaveWorldSelectionContextProbe,
    header_probe: Option<&SmpSaveTaggedCollectionHeaderProbe>,
) -> Option<SmpLoadedChairmanProfileTable> {
    Some(SmpLoadedChairmanProfileTable {
        source_kind: format!("{}-chairman-selection-only", probe.source_kind),
        semantic_family: "scenario-selected-chairman-context".to_string(),
        observed_entry_count: header_probe
            .map(|probe| probe.live_record_count as usize)
            .unwrap_or(0),
        selected_chairman_profile_id: Some(probe.selected_chairman_profile_id),
        entries: Vec::new(),
    })
}

pub(in crate::inspect::smp) fn build_save_world_selection_role_analysis(
    probe: &SmpSaveWorldSelectionContextProbe,
) -> SmpSaveWorldSelectionRoleAnalysis {
    let chairman_slots = probe
        .chairman_slot_selectors
        .iter()
        .copied()
        .zip(probe.chairman_role_gate_bytes.iter().copied())
        .enumerate()
        .map(|(slot_index, (selector_byte, role_gate_byte))| {
            SmpSaveWorldSelectionRoleAnalysisEntry {
                slot_index,
                selector_byte,
                selector_byte_hex: format!("0x{selector_byte:02x}"),
                role_gate_byte,
                role_gate_byte_hex: format!("0x{role_gate_byte:02x}"),
            }
        })
        .collect();

    SmpSaveWorldSelectionRoleAnalysis {
        selected_company_id: probe.selected_company_id,
        selected_chairman_profile_id: probe.selected_chairman_profile_id,
        campaign_override_flag: probe.campaign_override_flag,
        campaign_override_flag_hex: probe.campaign_override_flag_hex.clone(),
        chairman_slots,
    }
}
