use atlas::invocation::SkillContext;
use atlas::vault_store;
use forge::tracker::store::{ExecutionRecord, ExecutionStore};
use vault::fact::MemoryTier;

#[derive(Debug, Clone)]
pub struct HarvestedSignal {
    pub source: String,
    pub content: String,
}

impl HarvestedSignal {
    fn from_exec(rec: &ExecutionRecord) -> Self {
        Self {
            source: format!("exec:{}", rec.program),
            content: format!(
                "[{}] {} {} → exit={} tokens={}/{}",
                rec.timestamp,
                rec.program,
                rec.args,
                rec.exit_code,
                rec.tokens_after,
                rec.tokens_before
            ),
        }
    }

    fn from_vault(key: &str, value: &str, tier: &str) -> Self {
        Self {
            source: format!("vault:{tier}"),
            content: format!("{key}: {value}"),
        }
    }
}

pub fn harvest(ctx: &SkillContext) -> Vec<HarvestedSignal> {
    let mut signals: Vec<HarvestedSignal> = Vec::new();

    // Pull recent executions from forge's SQLite tracker
    let db_path = {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
        std::path::PathBuf::from(home)
            .join(".bctx")
            .join("executions.db")
    };
    if let Ok(store) = ExecutionStore::open(&db_path) {
        if let Ok(rows) = store.recent(10) {
            for rec in &rows {
                signals.push(HarvestedSignal::from_exec(rec));
            }
        }
    }

    // Pull ImmediateTrace facts from the process Vault
    {
        let vault = vault_store::vault().lock().unwrap();
        let q = vault::retrieval::query::VaultQuery::new("")
            .in_tier(MemoryTier::Immediate)
            .top_k(20);
        for fact in vault.query(&q) {
            signals.push(HarvestedSignal::from_vault(
                &fact.key,
                &fact.value,
                "immediate",
            ));
        }
    }

    let _ = ctx; // future: filter signals by ctx.task_hint
    signals
}
