//! OTLP log processing and storage.
//!
//! This module provides the core logic for processing OpenTelemetry log requests
//! and storing the parsed events.

use crate::model::Storage;

use super::{ExportLogsServiceRequest, ParsedApiRequest, ParsedCodexEvent};

/// Process an OpenTelemetry logs request and store parsed events.
///
/// Iterates through all log records in the request, attempting to parse each as either:
/// - An API request (token-bearing event from Claude Code, etc.)
/// - A Codex activity event (non-token event from Codex CLI)
///
/// Returns the number of events successfully stored.
///
/// # Arguments
///
/// * `storage` - The storage backend to insert events into
/// * `request` - The OTLP logs export request to process
/// * `machine_id` - Machine identifier to associate with parsed events
///
/// # Example
///
/// ```no_run
/// use mi6_core::{ExportLogsServiceRequest, Storage, process_logs_request};
///
/// fn process<S: Storage>(storage: &S, request: &ExportLogsServiceRequest, machine_id: &str) {
///     let count = process_logs_request(storage, request, machine_id);
///     println!("Stored {} events", count);
/// }
/// ```
pub fn process_logs_request<S: Storage>(
    storage: &S,
    request: &ExportLogsServiceRequest,
    machine_id: &str,
) -> usize {
    let mut count = 0;

    for resource_logs in &request.resource_logs {
        for scope_logs in &resource_logs.scope_logs {
            for log_record in &scope_logs.log_records {
                // Try to parse as API request (token-bearing event)
                if let Some(parsed) = ParsedApiRequest::from_log_record(log_record)
                    && let Some(event) = parsed.into_event(machine_id.to_string())
                    && storage.insert(&event).is_ok()
                {
                    count += 1;
                    continue;
                }

                // Try to parse as Codex activity event (non-token event)
                if let Some(codex_event) = ParsedCodexEvent::from_log_record(log_record) {
                    let event = codex_event.into_event(machine_id.to_string());
                    if storage.insert(&event).is_ok() {
                        count += 1;
                    }
                }
            }
        }
    }

    count
}
