use crate::beacon::{local::LocalBeacon, Beacon, BeaconEmitter};
use crate::graph::SignalGraph;
use anyhow::Result;
use atlas::{invocation::SkillContext, outcome::SkillOutcome, vault_store};
use vault::fact::{MemoFact, MemoryTier};

pub fn merge(outcomes: Vec<Result<SkillOutcome>>, graph: &mut SignalGraph, _ctx: &SkillContext) {
    let beacon_emitter = LocalBeacon::new(LocalBeacon::default_path());

    for outcome in outcomes.into_iter().flatten() {
        {
            let tokens_used = outcome.tokens_used;
            graph.record_skill_outcome(&outcome.skill_id, tokens_used);

            // Emit Beacon for every completed skill
            let b = Beacon::new(&outcome.skill_id, tokens_used, 0, 0);
            beacon_emitter.emit(&b);

            // Auto-persist notable archivist hits back as ImmediateTrace facts
            if outcome.skill_id == "archivist" {
                if let Some(hits) = outcome.result.get("hits").and_then(|v| v.as_array()) {
                    let mut vault = vault_store::vault().lock().unwrap();
                    for hit in hits {
                        let key = hit
                            .get("key")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        let value = hit
                            .get("value")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string();
                        if !key.is_empty() {
                            let fact = MemoFact::new(
                                MemoryTier::Immediate,
                                "archivist_hit",
                                &key,
                                &value,
                                0.7,
                            );
                            vault.insert(fact);
                        }
                    }
                }
            }
        }
    }
}
