use crate::inspect::smp::bundle::SmpContainerProfile;
use crate::inspect::smp::catalog::offsets::world::{
    RT3_SAVE_WORLD_BLOCK_CHUNK_TAG, RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_MIRROR_RELATIVE_OFFSET,
    RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_PRIMARY_RELATIVE_OFFSETS, RT3_SAVE_WORLD_BLOCK_LEN,
    RT3_SAVE_WORLD_BLOCK_NEXT_CHUNK_TAG,
};
use crate::inspect::smp::common::{find_u32_le_offsets, read_u32_at};
use crate::inspect::smp::world::{SmpSaveWorldEconomicTuningProbe, build_save_dword_candidate};

pub(in crate::inspect::smp) fn parse_save_world_economic_tuning_probe(
    bytes: &[u8],
    file_extension_hint: Option<&str>,
    container_profile: Option<&SmpContainerProfile>,
) -> Option<SmpSaveWorldEconomicTuningProbe> {
    if file_extension_hint != Some("gms") {
        return None;
    }
    let profile = container_profile?;
    let supported = matches!(
        profile.profile_family.as_str(),
        "rt3-classic-save-container-v1"
            | "rt3-105-save-container-v1"
            | "rt3-105-scenario-save-container-v1"
            | "rt3-105-alt-save-container-v1"
    );
    if !supported {
        return None;
    }

    for chunk_tag_offset in find_u32_le_offsets(bytes, RT3_SAVE_WORLD_BLOCK_CHUNK_TAG) {
        let payload_offset = chunk_tag_offset + 4;
        let next_chunk_tag_offset = payload_offset.checked_add(RT3_SAVE_WORLD_BLOCK_LEN)?;
        if read_u32_at(bytes, next_chunk_tag_offset) != Some(RT3_SAVE_WORLD_BLOCK_NEXT_CHUNK_TAG) {
            continue;
        }
        let mirror_lane = build_save_dword_candidate(
            bytes,
            payload_offset,
            "economic_tuning_mirror_lane_0",
            RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_MIRROR_RELATIVE_OFFSET,
        )?;
        let tuning_lanes = RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_PRIMARY_RELATIVE_OFFSETS
            .iter()
            .enumerate()
            .map(|(lane_index, relative_offset)| {
                build_save_dword_candidate(
                    bytes,
                    payload_offset,
                    &format!("economic_tuning_lane_{lane_index}"),
                    *relative_offset,
                )
            })
            .collect::<Option<Vec<_>>>()?;
        return Some(SmpSaveWorldEconomicTuningProbe {
            profile_family: profile.profile_family.clone(),
            source_kind: "save-direct-world-block".to_string(),
            semantic_family: "scenario-save-world-economic-tuning".to_string(),
            chunk_tag_offset,
            payload_offset,
            payload_len: RT3_SAVE_WORLD_BLOCK_LEN,
            payload_len_hex: format!("0x{:x}", RT3_SAVE_WORLD_BLOCK_LEN),
            mirror_lane,
            tuning_lanes,
            evidence: vec![
                format!(
                    "chunk tag 0x32c8 at 0x{chunk_tag_offset:x} matches the fixed [world+0x04] save block"
                ),
                format!(
                    "next chunk tag 0x32c9 appears at 0x{next_chunk_tag_offset:x}, matching the documented 0x4f2c payload span"
                ),
                format!(
                    "mirror lane uses payload +0x{:x} ([world+0x0bde])",
                    RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_MIRROR_RELATIVE_OFFSET
                ),
                format!(
                    "primary tuning lanes use payload offsets {} matching the documented [world+0x0be2..+0x0bf6] float block",
                    RT3_SAVE_WORLD_BLOCK_ECONOMIC_TUNING_PRIMARY_RELATIVE_OFFSETS
                        .iter()
                        .map(|offset| format!("0x{offset:x}"))
                        .collect::<Vec<_>>()
                        .join(", ")
                ),
                "Current atlas evidence keeps this fixed six-float world tuning band separate from the issue-0x37 investor-confidence lane."
                    .to_string(),
            ],
        });
    }

    None
}
