use crate::inspect::smp::world::SmpSaveCompanyChairmanAnalysisReport;
use std::collections::BTreeSet;

pub(super) fn build_region_service_trace_notes(
    analysis: &SmpSaveCompanyChairmanAnalysisReport,
) -> Vec<String> {
    let mut notes = Vec::new();
    notes.push(
        "Region service trace treats the queued kind-7 notice family as transient runtime state until a persisted owner seam is found.".to_string(),
    );
    notes.push(
        "Direct disassembly now grounds the core producer/consumer pair itself: 0x00422100 seeds [region+0x276] from the severity/source lane [region+0x25e] and appends the kind-7 notice through 0x004337c0, while 0x004358d0 consumes that amount, runs the city-connection peer probes 0x00420030/0x00420280 plus the linked-company resolver 0x0047efe0, and then stamps [region+0x302] or [region+0x316].".to_string(),
    );
    notes.push(
        "Direct disassembly now also tightens the severity/source side itself: 0x004cc930 is a selected-region editor helper that writes [region+0x25a] and [region+0x25e] together from one integer input, while 0x00438150 and 0x00442cc0 are fixed-region global reseed/clamp owners over collection 0x0062bae0 that adjust the same mirrored pair for hardcoded region ids.".to_string(),
    );
    notes.push(
        "Two more apparent offset hits are now ruled out as region false leads: 0x0043a5a0 is a separate constructor under vtable root 0x005ca078 that zeroes its own [this+0x302/+0x316] fields during local object setup, and 0x0045c460/0x0045c8xx is a separate vtable-0x005cb5e8 helper family whose [this+0x316] is a child-array pointer serialized through 0x61a9/0x61aa/0x61ab rather than a region latch.".to_string(),
    );
    notes.push(
        "A direct-writer census now narrows the remaining literal offset path further: the other `0x302/0x316` writer bands at 0x0043dd45/0x0043de19/0x0043e0a7/0x0043f5bc all hang off the same non-region 0x005ca078 object family as 0x0043a5a0 through helpers 0x0043af60/0x0043b030, so the only grounded region-owned literal writes left are the constructor 0x00421200 plus the producer/consumer pair 0x00422100 and 0x004358d0.".to_string(),
    );
    notes.push(
        "The later post-load per-region sweep is ruled down further now too: in the 0x00444887 restore strip, the follow-on loop at 0x00444b90 dispatches 0x00420560 over each live region, but that helper only zeroes and recomputes [region+0x312] from the embedded profile collection [region+0x37f]/[region+0x383] and lazily seeds the year-driven [region+0x317/+0x31b] band through 0x00420350, not [region+0x276/+0x302/+0x316].".to_string(),
    );
    notes.push(
        "The immediate profile-summary/display strip is ruled onto the rebuild side too: 0x00420410 rebuilds summary dwords [region+0x2f6/+0x2fa/+0x2fe] and 0x004204c0 refreshes cached-selector display strings [region+0x2f2] by walking the restored profile collection [region+0x37f], resolving backing candidates through 0x00412b70, and consuming candidate bytes [candidate+0xba/+0xbb]. Those bytes are therefore consumer-side summaries, not hidden persisted region lanes.".to_string(),
    );
    notes.push(
        "The current region seam is strong enough to prove record-envelope ownership, profile subcollection ownership, and the absence of hidden 0x55f3 tail padding on grounded saves.".to_string(),
    );
    if let Some(probe) = analysis.region_record_triplets.as_ref() {
        let mut trailing_words = probe
            .entries
            .iter()
            .map(|entry| entry.policy_trailing_word_hex.clone())
            .collect::<Vec<_>>();
        trailing_words.sort();
        trailing_words.dedup();
        let preview = trailing_words
            .iter()
            .take(4)
            .cloned()
            .collect::<Vec<_>>()
            .join(", ");
        notes.push(format!(
            "Region 0x55f2 trailing-word candidates currently collapse to {} distinct value(s): {}.",
            trailing_words.len(),
            if preview.is_empty() {
                "none".to_string()
            } else {
                preview
            }
        ));
        if probe.entries.iter().all(|entry| {
            entry.policy_reserved_dwords.iter().all(|word| *word == 0)
                && entry.policy_trailing_word == 1
        }) {
            notes.push(
                "Grounded region 0x55f2 fixed-policy chunks also keep all three reserved dwords at zero while the trailing word stays 0x0001, so that chunk is not currently carrying the missing latch/id discriminator."
                    .to_string(),
            );
        }
        let pre_name_prefix_count = probe
            .entries
            .iter()
            .filter(|entry| entry.pre_name_prefix_len != 0)
            .count();
        let unique_pre_name_prefix_lens = probe
            .entries
            .iter()
            .map(|entry| entry.pre_name_prefix_len)
            .collect::<BTreeSet<_>>()
            .into_iter()
            .collect::<Vec<_>>();
        notes.push(format!(
            "Grounded live-entry payload starts now also show {} of {} region records with nonzero bytes before the first 0x55f1 tag; unique pre-name prefix lengths are {:?}.",
            pre_name_prefix_count,
            probe.entries.len(),
            unique_pre_name_prefix_lens
        ));
    }
    notes
}
