use crate::types::*;

/// Classification of noise patterns in Claude Code JSONL.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NoiseKind {
    Meta,
    Warmup,
    Interrupted,
    Continuation,
    ApiError,
    SystemCaveat,
    QueueOp,
}

/// Classify a message as noise, if applicable.
/// Returns None for normal messages.
pub fn classify_noise(message: &RawMessage) -> Option<NoiseKind> {
    match message {
        RawMessage::QueueOperation(_) => Some(NoiseKind::QueueOp),
        RawMessage::User(user) => {
            if user.is_meta.unwrap_or(false) {
                return Some(NoiseKind::Meta);
            }
            if let Some(text) = extract_user_text(user) {
                if text == "Warmup" {
                    return Some(NoiseKind::Warmup);
                }
                if text.starts_with("[Request interrupted") {
                    return Some(NoiseKind::Interrupted);
                }
                if text.starts_with("This session is being continued") {
                    return Some(NoiseKind::Continuation);
                }
                if text.starts_with("API Error") {
                    return Some(NoiseKind::ApiError);
                }
                if text.starts_with("Caveat: The messages below") {
                    return Some(NoiseKind::SystemCaveat);
                }
            }
            None
        }
        _ => None,
    }
}

/// Extract plain text from a user message's content.
fn extract_user_text(user: &RawUserMessage) -> Option<&str> {
    match &user.message.content {
        Content::Text(s) => Some(s.as_str()),
        Content::Blocks(_) => None, // tool_result blocks, not plain text
    }
}

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

    #[test]
    fn normal_assistant_is_not_noise() {
        let json = r#"{"type":"assistant","uuid":"x","timestamp":"2026-01-01T00:00:00Z","sessionId":"s","message":{"id":"m","role":"assistant","content":[{"type":"text","text":"Hello"}],"stop_reason":"end_turn"}}"#;
        let msg: RawMessage = serde_json::from_str(json).unwrap();
        assert_eq!(classify_noise(&msg), None);
    }

    #[test]
    fn queue_op_is_noise() {
        let json = r#"{"type":"queue-operation","operation":"enqueue","timestamp":"2026-01-01T00:00:00Z","sessionId":"s"}"#;
        let msg: RawMessage = serde_json::from_str(json).unwrap();
        assert_eq!(classify_noise(&msg), Some(NoiseKind::QueueOp));
    }
}
