use super::assembly::LoadedSaveSliceParts;
use crate::inspect::smp::save_load::*;

pub(super) fn build_loaded_save_slice_notes(
    report: &SmpInspectionReport,
    summary: &SmpSaveLoadSummary,
    parts: &LoadedSaveSliceParts,
) -> Vec<String> {
    let mut notes = summary.notes.clone();

    if let Some(probe) = &report.save_world_selection_context_probe {
        notes.push(format!(
            "Raw save fixed world block exposes selected_company_id={} at file offset 0x{:x}.",
            probe.selected_company_id, probe.selected_company_id_offset
        ));
        notes.push(format!(
            "Raw save fixed world block exposes selected_chairman_profile_id={} at file offset 0x{:x}.",
            probe.selected_chairman_profile_id, probe.selected_chairman_profile_id_offset
        ));
        notes.push(format!(
            "Raw save fixed world block also exposes {} chairman slot selector bytes at file offset 0x{:x} and campaign_override_flag={} at file offset 0x{:x}.",
            probe.chairman_slot_selectors.len(),
            probe.chairman_slot_selector_offset,
            probe.campaign_override_flag,
            probe.campaign_override_flag_offset
        ));
        if report.save_company_roster_probe.is_none()
            || report.save_chairman_profile_table_probe.is_none()
        {
            notes.push(
                "Raw save inspection still does not reconstruct every company_roster or chairman_profile_table scalar lane; the grounded package-save path prefers direct-record reconstruction where it can and falls back to selection/header-only context otherwise."
                    .to_string(),
            );
        }
    }
    if let Some(probe) = &report.save_world_issue_37_probe {
        notes.push(format!(
            "Raw save fixed world block also exposes the grounded issue-0x37 pair: value={} at file offset 0x{:x} and companion multiplier {:.6} at file offset 0x{:x}.",
            probe.issue_value_lane.value_i32,
            probe.payload_offset + probe.issue_value_lane.relative_offset,
            probe.multiplier_lane.value_f32,
            probe.payload_offset + probe.multiplier_lane.relative_offset
        ));
    }
    if let Some(probe) = &report.save_world_economic_tuning_probe {
        notes.push(format!(
            "Raw save fixed world block also exposes the six-lane economic tuning float band at file offset 0x{:x} (mirror lane at 0x{:x}).",
            probe.tuning_lanes
                .first()
                .map(|lane| probe.payload_offset + lane.relative_offset)
                .unwrap_or(probe.payload_offset),
            probe.payload_offset + probe.mirror_lane.relative_offset
        ));
        notes.push(
            "Current atlas evidence treats that fixed six-float world tuning band as the editor economic-cost family, not as the company-governance issue table behind investor confidence."
                .to_string(),
        );
    }
    if let Some(probe) = &report.save_company_collection_header_probe {
        notes.push(format!(
            "Raw save tagged company header reports live_record_count={} and live_id_bound={} at file offsets 0x{:x}/0x{:x}/0x{:x}.",
            probe.live_record_count,
            probe.live_id_bound,
            probe.metadata_tag_offset,
            probe.records_tag_offset,
            probe.close_tag_offset
        ));
    }
    if let Some(probe) = &report.save_chairman_profile_collection_header_probe {
        notes.push(format!(
            "Raw save tagged chairman/profile header reports live_record_count={} and live_id_bound={} at file offsets 0x{:x}/0x{:x}/0x{:x}.",
            probe.live_record_count,
            probe.live_id_bound,
            probe.metadata_tag_offset,
            probe.records_tag_offset,
            probe.close_tag_offset
        ));
    }
    if let Some(probe) = &report.save_train_collection_header_probe {
        notes.push(format!(
            "Raw save tagged train header reports live_record_count={} and live_id_bound={} with direct_record_stride=0x{:x} at file offsets 0x{:x}/0x{:x}/0x{:x}.",
            probe.live_record_count,
            probe.live_id_bound,
            probe.direct_record_stride,
            probe.metadata_tag_offset,
            probe.records_tag_offset,
            probe.close_tag_offset
        ));
    }
    if let Some(probe) = &report.save_train_collection_directory_probe {
        notes.push(format!(
            "Raw save tagged train metadata also exposes a live-entry directory with {} entries rooted at metadata dword {} (head={:?}, tail={:?}).",
            probe.entries.len(),
            probe.directory_root_dword_index,
            probe.chain_head_live_entry_id,
            probe.chain_tail_live_entry_id
        ));
    }
    if let Some(probe) = &report.save_region_collection_header_probe {
        notes.push(format!(
            "Raw save tagged region header reports live_record_count={} and live_id_bound={} with serialized stride hint 0x{:x} at file offsets 0x{:x}/0x{:x}/0x{:x}.",
            probe.live_record_count,
            probe.live_id_bound,
            probe.direct_record_stride,
            probe.metadata_tag_offset,
            probe.records_tag_offset,
            probe.close_tag_offset
        ));
    }
    if let Some(probe) = &report.save_region_record_triplet_probe {
        notes.push(format!(
            "Raw save tagged region records also expose {} repeated 0x55f1/0x55f2/0x55f3 triplets in the records span; first name={:?}, first policy lanes=({:.3}, {:.3}, {:.3}), trailing_word={}, first profile collection count={:?}, first profile collection trailing_padding_len={:?}.",
            probe.record_count,
            probe.entries.first().map(|entry| entry.name.as_str()),
            probe.entries
                .first()
                .map(|entry| entry.policy_leading_f32_0)
                .unwrap_or_default(),
            probe.entries
                .first()
                .map(|entry| entry.policy_leading_f32_1)
                .unwrap_or_default(),
            probe.entries
                .first()
                .map(|entry| entry.policy_leading_f32_2)
                .unwrap_or_default(),
            probe.entries
                .first()
                .map(|entry| entry.policy_trailing_word_hex.as_str())
                .unwrap_or("0x0000"),
            probe.entries.first().and_then(|entry| {
                entry.profile_collection.as_ref().map(|collection| collection.live_record_count)
            }),
            probe.entries.first().and_then(|entry| {
                entry.profile_collection
                    .as_ref()
                    .map(|collection| collection.trailing_padding_len)
            })
        ));
    }
    if let Some(collection) = &parts.region_collection {
        let total_profile_rows = collection
            .entries
            .iter()
            .map(|entry| {
                entry
                    .profile_collection
                    .as_ref()
                    .map(|collection| collection.entries.len())
                    .unwrap_or_default()
            })
            .sum::<usize>();
        let nonzero_prefix_count = collection
            .entries
            .iter()
            .filter(|entry| entry.pre_name_prefix_len != 0)
            .count();
        let nonzero_reserved_count = collection
            .entries
            .iter()
            .filter(|entry| entry.policy_reserved_dwords.iter().any(|raw| *raw != 0))
            .count();
        notes.push(format!(
            "Save-slice projection now carries {} loaded region triplet rows as first-class context, with {} embedded profile rows, {} rows with nonzero pre-name prefixes, and {} rows with nonzero reserved policy dwords.",
            collection.observed_entry_count,
            total_profile_rows,
            nonzero_prefix_count,
            nonzero_reserved_count
        ));
    }
    if let Some(summary) = &parts.region_fixed_row_run_summary {
        notes.push(format!(
            "Save-slice projection now also carries the region fixed-row run summary with {} candidate row bands at target stride {}, best rows offset {:?}, and best shape signature {:?}.",
            summary.candidates.len(),
            summary.target_row_stride_hex,
            summary
                .candidates
                .first()
                .map(|candidate| candidate.rows_offset_hex.as_str()),
            summary
                .candidates
                .first()
                .map(|candidate| candidate.shape_signature.as_str())
        ));
    }
    if let Some(probe) = &report.save_placed_structure_collection_header_probe {
        notes.push(format!(
            "Raw save tagged placed-structure header reports live_record_count={} and live_id_bound={} with serialized stride hint 0x{:x} at file offsets 0x{:x}/0x{:x}/0x{:x}.",
            probe.live_record_count,
            probe.live_id_bound,
            probe.direct_record_stride,
            probe.metadata_tag_offset,
            probe.records_tag_offset,
            probe.close_tag_offset
        ));
    }
    if let Some(probe) = &report.save_placed_structure_record_triplet_probe {
        notes.push(format!(
            "Raw save tagged placed-structure records also expose {} repeated 0x55f1/0x55f2/0x55f3 triplets; first stems={:?}/{:?}, first policy lanes=({:.3}, {:.3}, {:.3}, {:.3}, {:.3}), first footer payload={}, first footer status kind={:?}.",
            probe.record_count,
            probe.entries.first().map(|entry| entry.primary_name.as_str()),
            probe.entries.first().map(|entry| entry.secondary_name.as_str()),
            probe.entries.first().map(|entry| entry.policy_f32_lane_0).unwrap_or_default(),
            probe.entries.first().map(|entry| entry.policy_f32_lane_1).unwrap_or_default(),
            probe.entries.first().map(|entry| entry.policy_f32_lane_2).unwrap_or_default(),
            probe.entries.first().map(|entry| entry.policy_f32_lane_3).unwrap_or_default(),
            probe.entries.first().map(|entry| entry.policy_f32_lane_4).unwrap_or_default(),
            probe.entries.first().map(|entry| entry.profile_payload_dword_hex.as_str()).unwrap_or("0x00000000"),
            probe.entries.first().map(|entry| entry.profile_status_kind.as_str())
        ));
    }
    if let Some(collection) = &parts.placed_structure_collection {
        let farm_growth_stage_count = collection
            .entries
            .iter()
            .filter(|entry| entry.farm_growth_stage_index.is_some())
            .count();
        let opaque_status_count = collection
            .entries
            .iter()
            .filter(|entry| entry.profile_status_kind != "unset")
            .count();
        notes.push(format!(
            "Save-slice projection now carries {} loaded placed-structure triplet rows as first-class context, with {} farm growth-stage rows and {} non-default footer-status rows.",
            collection.observed_entry_count, farm_growth_stage_count, opaque_status_count
        ));
    }
    if let Some(probe) = &parts.placed_structure_dynamic_side_buffer_probe {
        let dominant_pattern = probe.compact_prefix_pattern_summaries.first();
        let payload_envelope_summary = probe.payload_envelope_summary.as_ref();
        let short_profile_flag_pair_summary = payload_envelope_summary
            .and_then(|summary| summary.short_profile_flag_pair_summary.as_ref());
        notes.push(format!(
            "Raw save also exposes the separate placed-structure dynamic-side-buffer candidate 0x38a5/0x38a6/0x38a7: live_record_count={}, owner-shared 0x38a6 dword={} at relative offset 0x{:x}, first compact prefix=({},{},{}), first embedded names={:?}/{:?}/{:?}, embedded 0x55f1 row count={}, rows with tertiary 0x55f1 string={}, unique compact prefix patterns={}, 0x55f3-leading rows={}, complete 0x55f1/0x55f2/0x55f3 envelopes={}, dominant 0x55f2 chunk len=0x{:x} x{}, dominant 0x55f3 span=0x{:x} x{}, dominant short 0x55f3 flag pair={}/{} x{}, dominant compact pattern={}/{}/{} x{}.",
            probe.live_record_count,
            probe.owner_shared_dword_hex,
            probe.owner_shared_dword_relative_offset,
            probe.prefix_leading_dword_hex,
            probe.prefix_trailing_word_hex,
            probe.prefix_separator_byte_hex,
            probe.first_embedded_primary_name.as_deref(),
            probe.first_embedded_secondary_name.as_deref(),
            probe.first_embedded_tertiary_name.as_deref(),
            probe.embedded_name_tag_count,
            probe.decoded_embedded_name_row_with_tertiary_name_count,
            probe.unique_compact_prefix_pattern_count,
            probe.prefix_leading_dword_matching_embedded_profile_tag_count,
            payload_envelope_summary
                .map(|summary| summary.row_count_with_complete_0x55f1_0x55f2_0x55f3_envelope)
                .unwrap_or_default(),
            payload_envelope_summary
                .and_then(|summary| summary.dominant_policy_chunk_len)
                .unwrap_or_default(),
            payload_envelope_summary
                .map(|summary| summary.dominant_policy_chunk_len_count)
                .unwrap_or_default(),
            payload_envelope_summary
                .and_then(|summary| summary.dominant_profile_chunk_len)
                .unwrap_or_default(),
            payload_envelope_summary
                .map(|summary| summary.dominant_profile_chunk_len_count)
                .unwrap_or_default(),
            short_profile_flag_pair_summary
                .and_then(|summary| summary.dominant_flag_pair.as_ref())
                .map(|pair| pair.first_flag_byte_hex.as_str())
                .unwrap_or("0x00"),
            short_profile_flag_pair_summary
                .and_then(|summary| summary.dominant_flag_pair.as_ref())
                .map(|pair| pair.second_flag_byte_hex.as_str())
                .unwrap_or("0x00"),
            short_profile_flag_pair_summary
                .and_then(|summary| summary.dominant_flag_pair.as_ref())
                .map(|pair| pair.count)
                .unwrap_or_default(),
            dominant_pattern
                .map(|pattern| pattern.prefix_leading_dword_hex.as_str())
                .unwrap_or("0x00000000"),
            dominant_pattern
                .map(|pattern| pattern.prefix_trailing_word_hex.as_str())
                .unwrap_or("0x0000"),
            dominant_pattern
                .map(|pattern| pattern.prefix_separator_byte_hex.as_str())
                .unwrap_or("0x00"),
            dominant_pattern.map(|pattern| pattern.count).unwrap_or_default()
        ));
        if probe.owner_shared_dword_matches_first_compact_prefix_leading_dword {
            notes.push(
                "Direct disassembly now shows 0x00493be0 consuming one shared 0x38a6 owner-local dword before iterating records; the first compact-prefix leading dword currently reuses that same lane."
                    .to_string(),
            );
        }
    }
    if let Some(summary) = &parts.placed_structure_dynamic_side_buffer_summary {
        notes.push(format!(
            "Save-slice projection now also carries the placed-structure dynamic side-buffer summary with {} decoded name rows, {} unique name pairs, and {} overlapping triplet name pairs.",
            summary.decoded_embedded_name_row_count,
            summary.unique_embedded_name_pair_count,
            summary.triplet_alignment_overlap_count
        ));
    }
    if let Some(roster) = &report.save_company_roster_probe {
        notes.push(format!(
            "Raw save inspection reconstructed {} company direct records from the tagged company collection.",
            roster.entries.len()
        ));
    }
    if let Some(table) = &report.save_chairman_profile_table_probe {
        notes.push(format!(
            "Raw save inspection reconstructed {} chairman/profile direct records from the tagged chairman collection.",
            table.entries.len()
        ));
    }

    notes
}
