use crate::reconcile::Patch;
use serde::{Deserialize, Serialize};

/// Messages sent over the wire for Remote UI
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum RemoteMessage {
    /// Initial tree sent when client connects
    InitialTree(InitialTree),

    /// Incremental patches
    Patch(PatchStream),

    /// Action dispatched from client
    DispatchAction {
        module: String,
        action: String,
        payload: Option<serde_json::Value>,
    },

    /// State update from host
    StateUpdate {
        module: String,
        state: serde_json::Value,
    },
}

/// Initial tree sent to clients
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitialTree {
    /// Module name
    pub module: String,

    /// Initial state snapshot
    pub state: serde_json::Value,

    /// Initial patches to construct the tree
    pub patches: Vec<Patch>,

    /// Revision number (starts at 0)
    pub revision: u64,

    /// Optional integrity hash
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
}

impl InitialTree {
    pub fn new(module: String, state: serde_json::Value, patches: Vec<Patch>) -> Self {
        Self {
            module,
            state,
            patches,
            revision: 0,
            hash: None,
        }
    }

    pub fn with_hash(mut self, hash: String) -> Self {
        self.hash = Some(hash);
        self
    }
}

/// Patch stream for incremental updates
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatchStream {
    /// Module name
    pub module: String,

    /// Patches to apply
    pub patches: Vec<Patch>,

    /// Revision number (monotonically increasing)
    pub revision: u64,

    /// Optional integrity hash
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hash: Option<String>,
}

impl PatchStream {
    pub fn new(module: String, patches: Vec<Patch>, revision: u64) -> Self {
        Self {
            module,
            patches,
            revision,
            hash: None,
        }
    }

    pub fn with_hash(mut self, hash: String) -> Self {
        self.hash = Some(hash);
        self
    }
}

/// Helper to serialize messages to JSON
pub fn serialize_message(message: &RemoteMessage) -> Result<String, serde_json::Error> {
    serde_json::to_string(message)
}

/// Helper to deserialize messages from JSON
pub fn deserialize_message(json: &str) -> Result<RemoteMessage, serde_json::Error> {
    serde_json::from_str(json)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_serialize_initial_tree() {
        let initial = InitialTree::new(
            "TestModule".to_string(),
            serde_json::json!({"count": 0}),
            vec![],
        );

        let message = RemoteMessage::InitialTree(initial);
        let json = serialize_message(&message).unwrap();

        assert!(json.contains("initialTree"));
        assert!(json.contains("TestModule"));
    }

    #[test]
    fn test_roundtrip() {
        let message = RemoteMessage::DispatchAction {
            module: "Test".to_string(),
            action: "increment".to_string(),
            payload: Some(serde_json::json!({"amount": 1})),
        };

        let json = serialize_message(&message).unwrap();
        let deserialized = deserialize_message(&json).unwrap();

        match deserialized {
            RemoteMessage::DispatchAction { module, action, .. } => {
                assert_eq!(module, "Test");
                assert_eq!(action, "increment");
            }
            _ => panic!("Wrong message type"),
        }
    }
}
