//! Public sync-broadcast API and remote-op ingestion.

#![allow(unused_imports, dead_code)]
use std::collections::HashMap;

use super::hex;
use bft_json_crdt::json_crdt::*;
use bft_json_crdt::op::ROOT_ID;
use tokio::sync::broadcast;

use super::VectorClock;
use super::state::{
    ALL_OPS, SYNC_TX, VECTOR_CLOCK, apply_and_persist, emit_event, get_crdt, rebuild_index,
    rebuild_node_index, track_op,
};
use super::types::{CrdtEvent, PipelineDoc};
use crate::slog;

/// Subscribe to locally-created CRDT ops for sync replication.
///
/// Each `SignedOp` broadcast here was created by *this* node and should be
/// forwarded to connected peers.  Returns `None` before `init()`.
pub fn subscribe_ops() -> Option<broadcast::Receiver<SignedOp>> {
    SYNC_TX.get().map(|tx| tx.subscribe())
}

/// Return all persisted `SignedOp`s in causal order (oldest first).
///
/// Used during initial sync handshake so a newly-connected peer can
/// reconstruct the full CRDT state.  Returns `None` before `init()`.
pub fn all_ops_json() -> Option<Vec<String>> {
    ALL_OPS.get().map(|m| m.lock().unwrap().clone())
}

/// Return this node's current vector clock.
///
/// The clock maps each author's hex-encoded Ed25519 public key to the count
/// of ops received from that author.  A connecting peer sends its clock so
/// the other side can compute which ops are missing via [`ops_since`].
///
/// Returns `None` before `init()`.
pub fn our_vector_clock() -> Option<VectorClock> {
    VECTOR_CLOCK.get().map(|m| m.lock().unwrap().clone())
}

/// Return only the ops that a peer with the given `peer_clock` is missing.
///
/// Iterates the local op journal and, for each author, skips the first N ops
/// (where N = `peer_clock[author]`) and returns the rest.  An empty peer
/// clock returns all ops (full sync for new nodes).
///
/// Returns `None` before `init()`.
pub fn ops_since(peer_clock: &VectorClock) -> Option<Vec<String>> {
    let all = ALL_OPS.get()?.lock().ok()?;
    let mut author_counts: HashMap<String, u64> = HashMap::new();
    let mut result = Vec::new();

    for op_json in all.iter() {
        if let Ok(signed_op) = serde_json::from_str::<SignedOp>(op_json) {
            let author_hex = super::hex::encode(&signed_op.author());
            let count = author_counts.entry(author_hex.clone()).or_insert(0);
            *count += 1;

            let peer_has = peer_clock.get(&author_hex).copied().unwrap_or(0);
            if *count > peer_has {
                result.push(op_json.clone());
            }
        }
    }

    Some(result)
}

// ── Remote op ingestion (from sync peers) ───────────────────────────

/// Apply a `SignedOp` received from a remote peer.
///
/// The op is validated, applied to the local CRDT, persisted to SQLite,
/// and any resulting stage transitions are broadcast as [`CrdtEvent`]s.
/// Unlike `apply_and_persist`, this does **not** re-broadcast the op on
/// the sync channel (to avoid infinite echo loops).
///
/// Returns `true` if the op was new and applied, `false` if it was a
/// duplicate or failed validation.
pub fn apply_remote_op(op: SignedOp) -> bool {
    let Some(state_mutex) = get_crdt() else {
        return false;
    };
    let Ok(mut state) = state_mutex.lock() else {
        return false;
    };

    // Snapshot stage state before applying so we can detect transitions.
    let pre_stages: HashMap<String, String> = state
        .index
        .iter()
        .filter_map(|(sid, &idx)| match state.crdt.doc.items[idx].stage.view() {
            JsonValue::String(s) => Some((sid.clone(), s)),
            _ => None,
        })
        .collect();

    let result = state.crdt.apply(op.clone());

    // Self-loop guard: op was already applied (came back via echo from peer).
    // Return false immediately — do not re-persist or re-add to ALL_OPS.
    if result == bft_json_crdt::json_crdt::OpState::AlreadySeen {
        return false;
    }

    if result != bft_json_crdt::json_crdt::OpState::Ok
        && result != bft_json_crdt::json_crdt::OpState::MissingCausalDependencies
    {
        return false;
    }

    // Persist the op.
    if let Err(e) = state.persist_tx.send(op.clone()) {
        crate::slog_error!(
            "[crdt] Failed to send remote op to persist task: {e}; persist task may be dead. \
             In-memory state is now ahead of persisted state."
        );
    }

    // Track in ALL_OPS + VECTOR_CLOCK.
    if let Ok(json) = serde_json::to_string(&op) {
        track_op(&op, json);
    }

    // Rebuild indices (new items or nodes may have been inserted).
    state.index = rebuild_index(&state.crdt);
    state.node_index = rebuild_node_index(&state.crdt);

    // Detect and broadcast stage transitions.
    for (sid, &idx) in &state.index {
        let new_stage = match state.crdt.doc.items[idx].stage.view() {
            JsonValue::String(s) => s,
            _ => continue,
        };
        let old_stage = pre_stages.get(sid).cloned();
        let changed = old_stage.as_deref() != Some(&new_stage);
        if changed {
            let name = match state.crdt.doc.items[idx].name.view() {
                JsonValue::String(s) if !s.is_empty() => Some(s),
                _ => None,
            };
            emit_event(CrdtEvent {
                story_id: sid.clone(),
                from_stage: old_stage,
                to_stage: new_stage,
                name,
            });
        }
    }

    true
}

#[cfg(test)]
mod tests {
    use super::super::state::init_for_test;
    use super::super::types::{NodePresenceCrdt, PipelineItemCrdt};
    use super::super::write::write_item;
    use super::*;
    use bft_json_crdt::json_crdt::OpState;
    use bft_json_crdt::keypair::make_keypair;
    use bft_json_crdt::op::ROOT_ID;
    use fastcrypto::ed25519::Ed25519KeyPair;
    use serde_json::json;

    #[test]
    fn signed_op_serialization_roundtrip() {
        let kp = make_keypair();
        let mut crdt = BaseCrdt::<PipelineDoc>::new(&kp);

        let item: JsonValue = json!({
            "story_id": "60_story_serde",
            "stage": "1_backlog",
            "name": "Serde Test",
            "agent": "",
            "retry_count": 0.0,
            "blocked": false,
            "depends_on": "",
            "claimed_by": "",
            "claimed_at": 0.0,
        })
        .into();

        let op = crdt.doc.items.insert(ROOT_ID, item).sign(&kp);
        let json_str = serde_json::to_string(&op).unwrap();
        let deserialized: SignedOp = serde_json::from_str(&json_str).unwrap();

        assert_eq!(op.id(), deserialized.id());
        assert_eq!(op.inner.seq, deserialized.inner.seq);
    }

    #[test]
    fn apply_remote_op_returns_false_when_not_initialised() {
        // Without the global CRDT state, apply_remote_op should return false.
        let kp = make_keypair();
        let mut crdt = BaseCrdt::<PipelineDoc>::new(&kp);
        let item: JsonValue = serde_json::json!({
            "story_id": "80_story_remote",
            "stage": "1_backlog",
            "name": "Remote",
            "agent": "",
            "retry_count": 0.0,
            "blocked": false,
            "depends_on": "",
            "claimed_by": "",
            "claimed_at": 0.0,
        })
        .into();
        let op = crdt
            .doc
            .items
            .insert(bft_json_crdt::op::ROOT_ID, item)
            .sign(&kp);
        // This uses the global state which may not be initialised in tests.
        let _ = apply_remote_op(op);
    }

    #[test]
    fn signed_op_survives_sync_serialization_roundtrip() {
        // Verify that a SignedOp serialised to JSON and back produces
        // the same op (critical for the sync wire protocol).
        let kp = make_keypair();
        let mut crdt = BaseCrdt::<PipelineDoc>::new(&kp);
        let item: JsonValue = serde_json::json!({
            "story_id": "90_story_wire",
            "stage": "2_current",
            "name": "Wire Test",
            "agent": "coder",
            "retry_count": 1.0,
            "blocked": false,
            "depends_on": "[10]",
            "claimed_by": "",
            "claimed_at": 0.0,
        })
        .into();
        let op = crdt
            .doc
            .items
            .insert(bft_json_crdt::op::ROOT_ID, item)
            .sign(&kp);

        let json1 = serde_json::to_string(&op).unwrap();
        let roundtripped: SignedOp = serde_json::from_str(&json1).unwrap();
        let json2 = serde_json::to_string(&roundtripped).unwrap();

        assert_eq!(json1, json2);
        assert_eq!(op.id(), roundtripped.id());
        assert_eq!(op.inner.seq, roundtripped.inner.seq);
        assert_eq!(op.author(), roundtripped.author());
    }

    #[test]
    fn sync_broadcast_channel_round_trip() {
        let (tx, mut rx) = broadcast::channel::<SignedOp>(16);
        let kp = make_keypair();
        let mut crdt = BaseCrdt::<PipelineDoc>::new(&kp);
        let item: JsonValue = serde_json::json!({
            "story_id": "95_story_sync_bcast",
            "stage": "1_backlog",
            "name": "",
            "agent": "",
            "retry_count": 0.0,
            "blocked": false,
            "depends_on": "",
            "claimed_by": "",
            "claimed_at": 0.0,
        })
        .into();
        let op = crdt
            .doc
            .items
            .insert(bft_json_crdt::op::ROOT_ID, item)
            .sign(&kp);
        tx.send(op.clone()).unwrap();

        let received = rx.try_recv().unwrap();
        assert_eq!(received.id(), op.id());
    }

    fn make_ops(
        kp: &Ed25519KeyPair,
        crdt: &mut BaseCrdt<PipelineDoc>,
        count: usize,
        prefix: &str,
    ) -> Vec<(SignedOp, String)> {
        let mut ops = Vec::new();
        for i in 0..count {
            let item: JsonValue = json!({
                "story_id": format!("{prefix}_{i}"),
                "stage": "1_backlog",
                "name": format!("Item {i}"),
                "agent": "",
                "retry_count": 0.0,
                "blocked": false,
                "depends_on": "",
                "claimed_by": "",
                "claimed_at": 0.0,
            })
            .into();
            let op = crdt.doc.items.insert(ROOT_ID, item).sign(kp);
            crdt.apply(op.clone());
            let json = serde_json::to_string(&op).unwrap();
            ops.push((op, json));
        }
        ops
    }

    fn build_clock(ops: &[(SignedOp, String)]) -> VectorClock {
        let mut clock = VectorClock::new();
        for (op, _) in ops {
            let author = hex::encode(&op.author());
            *clock.entry(author).or_insert(0) += 1;
        }
        clock
    }

    fn local_ops_since(all_ops: &[(SignedOp, String)], peer_clock: &VectorClock) -> Vec<String> {
        let mut author_counts: HashMap<String, u64> = HashMap::new();
        let mut result = Vec::new();
        for (op, json) in all_ops {
            let author = hex::encode(&op.author());
            let count = author_counts.entry(author.clone()).or_insert(0);
            *count += 1;
            let peer_has = peer_clock.get(&author).copied().unwrap_or(0);
            if *count > peer_has {
                result.push(json.clone());
            }
        }
        result
    }

    #[test]
    fn delta_sync_low_bandwidth_fully_caught_up() {
        let kp_a = make_keypair();
        let mut crdt_a = BaseCrdt::<PipelineDoc>::new(&kp_a);

        let ops_a = make_ops(&kp_a, &mut crdt_a, 100, "631_low");

        // B has already seen all 100 ops (its clock matches A's journal).
        let clock_b = build_clock(&ops_a);

        // Delta should be empty.
        let delta = local_ops_since(&ops_a, &clock_b);
        assert_eq!(
            delta.len(),
            0,
            "caught-up peer should receive 0 ops, got {}",
            delta.len()
        );
    }

    #[test]
    fn delta_sync_mid_stream_partial_catch_up() {
        let kp_a = make_keypair();
        let mut crdt_a = BaseCrdt::<PipelineDoc>::new(&kp_a);

        // Phase 1: 100 ops that B has seen.
        let ops_phase1 = make_ops(&kp_a, &mut crdt_a, 100, "631_mid1");
        let clock_b = build_clock(&ops_phase1);

        // Phase 2: 50 more ops that B missed.
        let ops_phase2 = make_ops(&kp_a, &mut crdt_a, 50, "631_mid2");

        // A's full journal is phase1 + phase2.
        let mut all_ops_a: Vec<(SignedOp, String)> = ops_phase1;
        all_ops_a.extend(ops_phase2);

        let delta = local_ops_since(&all_ops_a, &clock_b);
        assert_eq!(
            delta.len(),
            50,
            "peer should receive exactly 50 missed ops, got {}",
            delta.len()
        );
    }

    #[test]
    fn delta_sync_new_node_receives_all_ops() {
        let kp_a = make_keypair();
        let mut crdt_a = BaseCrdt::<PipelineDoc>::new(&kp_a);

        let ops_phase1 = make_ops(&kp_a, &mut crdt_a, 100, "631_new1");
        let ops_phase2 = make_ops(&kp_a, &mut crdt_a, 50, "631_new2");

        let mut all_ops_a: Vec<(SignedOp, String)> = ops_phase1;
        all_ops_a.extend(ops_phase2);

        // Empty clock = new node.
        let empty_clock = VectorClock::new();
        let delta = local_ops_since(&all_ops_a, &empty_clock);
        assert_eq!(
            delta.len(),
            150,
            "new node should receive all 150 ops, got {}",
            delta.len()
        );
    }

    #[test]
    fn delta_sync_multi_author() {
        use fastcrypto::traits::KeyPair;

        let kp_a = make_keypair();
        let kp_b = make_keypair();
        let mut crdt_a = BaseCrdt::<PipelineDoc>::new(&kp_a);
        let mut crdt_b = BaseCrdt::<PipelineDoc>::new(&kp_b);

        let ops_a = make_ops(&kp_a, &mut crdt_a, 30, "631_ma_a");
        let ops_b = make_ops(&kp_b, &mut crdt_b, 20, "631_ma_b");

        // Combined journal on a hypothetical server.
        let mut all_ops: Vec<(SignedOp, String)> = ops_a.clone();
        all_ops.extend(ops_b);

        // Peer has seen all of A's ops but none of B's.
        let mut peer_clock = VectorClock::new();
        let author_a_hex = hex::encode(&kp_a.public().0.to_bytes());
        peer_clock.insert(author_a_hex, 30);

        let delta = local_ops_since(&all_ops, &peer_clock);
        assert_eq!(
            delta.len(),
            20,
            "peer should receive 20 ops from author B, got {}",
            delta.len()
        );
    }

    #[test]
    fn build_vector_clock_from_ops() {
        use fastcrypto::traits::KeyPair;

        let kp = make_keypair();
        let mut crdt = BaseCrdt::<PipelineDoc>::new(&kp);
        let ops = make_ops(&kp, &mut crdt, 10, "631_vc");

        let clock = build_clock(&ops);
        let author_hex = hex::encode(&kp.public().0.to_bytes());

        assert_eq!(clock.len(), 1, "single author should produce 1 clock entry");
        assert_eq!(clock[&author_hex], 10, "clock should show 10 ops");
    }

    #[test]
    fn clock_message_serialization_roundtrip() {
        let mut clock = VectorClock::new();
        clock.insert("aabbcc".to_string(), 42);
        clock.insert("ddeeff".to_string(), 7);

        let json = serde_json::to_value(&clock).unwrap();
        assert!(json.is_object());
        let deserialized: VectorClock = serde_json::from_value(json).unwrap();
        assert_eq!(deserialized["aabbcc"], 42);
        assert_eq!(deserialized["ddeeff"], 7);
    }
}
