//! DuckDB sink — appends rich disasm items to the `instructions` table.
//!
//! Column layout matches [`crate::db`]: address, raw, mnemonic, operands,
//! disasm, ext_mnemonic, ext_operands, ext_disasm, section, function, label.

use duckdb::{Appender, params};

use crate::disasm::RichDisasmItem;

/// Append every item to the appender. Returns the number of rows written.
/// Does NOT flush — the caller decides when to flush, since multiple
/// section iterators typically share one appender.
pub fn append_instructions<'a>(
    appender: &mut Appender<'_>,
    items: impl IntoIterator<Item = RichDisasmItem<'a>>,
) -> duckdb::Result<u64> {
    let mut count: u64 = 0;
    for ri in items {
        let t = &ri.item.text;
        appender.append_row(params![
            ri.item.addr as i64,
            ri.item.raw as i64,
            t.mnemonic.as_str(),
            t.operands.as_str(),
            t.disasm.as_str(),
            t.ext_mnemonic.as_deref(),
            t.ext_operands.as_deref(),
            t.ext_disasm.as_deref(),
            t.branch_target.map(|t| t as i64),
            ri.section,
            ri.function.map(|f| f as i64),
            ri.label,
        ])?;
        count += 1;
    }
    Ok(count)
}
