// src/economic/helpers.rs
use super::types::*;
use chrono::{Local};
use std::collections::{HashMap};

pub fn event_key(e: &EconomicEvent) -> String {
    format!("{}|{}|{}", e.date, e.time, e.event)
}

pub fn identity_key(e: &EconomicEvent) -> String {
    format!("{}|{}|{}", e.country, e.event, e.date.split('-').take(2).collect::<Vec<_>>().join("-"))
}

pub fn build_identity_lookup(events: &HashMap<String, EconomicEvent>) -> HashMap<String, (String, EconomicEvent)> {
    let mut map = HashMap::new();
    for (k, e) in events {
        map.insert(identity_key(e), (k.clone(), e.clone()));
    }
    map
}

pub fn build_date_event_lookup(
    events: &HashMap<String, EconomicEvent>,
) -> HashMap<String, Vec<(String, EconomicEvent)>> {
    let mut map: HashMap<String, Vec<(String, EconomicEvent)>> = HashMap::new();

    for (k, e) in events {
        let key = format!("{}|{}|{}", e.country, e.event, e.date);
        map.entry(key).or_default().push((k.clone(), e.clone()));
    }
    map
}

pub fn detect_changes(old: &EconomicEvent, new: &EconomicEvent, today: &str) -> Vec<EventChange> {
    let mut changes = Vec::new();
    let ts = Local::now().format("%Y-%m-%d %H:%M:%S").to_string();

    if new.date.as_str() <= today { return changes; }

    let fields = [
        ("actual", &old.actual, &new.actual),
        ("forecast", &old.forecast, &new.forecast),
        ("previous", &old.previous, &new.previous),
        ("description", &old.description, &new.description),
    ];

    for (field, old_val, new_val) in fields {
        if old_val != new_val {
            changes.push(EventChange {
                date: new.date.clone(),
                event: new.event.clone(),
                country: new.country.clone(),
                field_changed: field.to_string(),
                old_value: old_val.clone(),
                new_value: new_val.clone(),
                detected_at: ts.clone(),
            });
        }
    }
    changes
}