//! Query result types.

mod record;
mod value;
pub mod temporal;
pub mod extended_temporal;

pub use record::Record;
pub use value::{CypherValue, NodeValue, PathValue, RelationshipValue};
pub use temporal::{DateValue, DateTimeValue, DurationValue, ExtendedDateValue, ExtendedLocalDateTimeValue, LocalDateTimeValue, LocalTimeValue, TimeValue};
// Extended temporal types for Neo4j's full year range (±999,999,999)
pub use extended_temporal::{
    ExtendedDate, ExtendedLocalDateTime, ExtendedDateTime,
    NxDate, NxLocalDateTime, NxDateTime,
    MAX_YEAR, MIN_YEAR, CHRONO_MAX_YEAR, CHRONO_MIN_YEAR,
};

use std::fmt;

/// The result of executing a Cypher query.
#[derive(Debug, Clone)]
pub struct QueryResult {
    /// The column names.
    pub columns: Vec<String>,
    /// The result rows.
    pub rows: Vec<Record>,
    /// Statistics about the query execution.
    pub stats: QueryStats,
}

impl QueryResult {
    /// Create a new empty result.
    pub fn new() -> Self {
        Self {
            columns: Vec::new(),
            rows: Vec::new(),
            stats: QueryStats::default(),
        }
    }

    /// Create a result with the given columns.
    pub fn with_columns(columns: Vec<String>) -> Self {
        Self {
            columns,
            rows: Vec::new(),
            stats: QueryStats::default(),
        }
    }

    /// Add a row to the result.
    pub fn add_row(&mut self, row: Record) {
        self.rows.push(row);
    }

    /// Get the number of rows.
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Check if the result is empty.
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Get a single value from the first row.
    pub fn single_value(&self) -> Option<&CypherValue> {
        self.rows.first().and_then(|r| r.get_by_index(0))
    }

    /// Get all values from a specific column.
    pub fn column_values(&self, column: &str) -> Vec<&CypherValue> {
        self.rows.iter().filter_map(|r| r.get(column)).collect()
    }
}

impl Default for QueryResult {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for QueryResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Print header
        if !self.columns.is_empty() {
            for (i, col) in self.columns.iter().enumerate() {
                if i > 0 {
                    write!(f, " | ")?;
                }
                write!(f, "{}", col)?;
            }
            writeln!(f)?;

            // Separator
            for (i, col) in self.columns.iter().enumerate() {
                if i > 0 {
                    write!(f, "-+-")?;
                }
                for _ in 0..col.len() {
                    write!(f, "-")?;
                }
            }
            writeln!(f)?;
        }

        // Print rows
        for row in &self.rows {
            for (i, col) in self.columns.iter().enumerate() {
                if i > 0 {
                    write!(f, " | ")?;
                }
                if let Some(val) = row.get(col) {
                    write!(f, "{}", val)?;
                } else {
                    write!(f, "null")?;
                }
            }
            writeln!(f)?;
        }

        // Print stats
        writeln!(f)?;
        writeln!(f, "{} rows", self.rows.len())?;

        Ok(())
    }
}

/// Statistics about query execution.
#[derive(Debug, Clone, Default)]
pub struct QueryStats {
    /// Number of nodes created.
    pub nodes_created: usize,
    /// Number of nodes deleted.
    pub nodes_deleted: usize,
    /// Number of relationships created.
    pub relationships_created: usize,
    /// Number of relationships deleted.
    pub relationships_deleted: usize,
    /// Number of properties set (computed from unique properties in finalize).
    pub properties_set: usize,
    /// Number of properties removed.
    pub properties_removed: usize,
    /// Number of labels added.
    pub labels_added: usize,
    /// Number of labels removed.
    pub labels_removed: usize,
    /// Track unique labels added (internal use)
    #[doc(hidden)]
    pub unique_labels: std::collections::HashSet<String>,
    /// Track unique labels removed (internal use)
    #[doc(hidden)]
    pub unique_labels_removed: std::collections::HashSet<String>,
    /// Track IDs of nodes created in this query (for netting with deletes)
    #[doc(hidden)]
    pub nodes_created_ids: std::collections::HashSet<u64>,
    /// Track IDs of relationships created in this query (for netting with deletes)
    #[doc(hidden)]
    pub relationships_created_ids: std::collections::HashSet<u64>,
    /// Track IDs of nodes deleted in this query (for WAL logging)
    #[doc(hidden)]
    pub nodes_deleted_ids: std::collections::HashSet<u64>,
    /// Track IDs of relationships deleted in this query (for WAL logging)
    #[doc(hidden)]
    pub relationships_deleted_ids: std::collections::HashSet<u64>,
    /// Track unique node properties set (node_id, property_name) - internal use
    #[doc(hidden)]
    pub unique_node_properties: std::collections::HashSet<(u64, String)>,
    /// Track unique relationship properties set (rel_id, property_name) - internal use
    #[doc(hidden)]
    pub unique_rel_properties: std::collections::HashSet<(u64, String)>,
    /// Track label additions per node (node_id, label) - internal use for WAL
    #[doc(hidden)]
    pub labels_added_ids: std::collections::HashSet<(u64, String)>,
    /// Track label removals per node (node_id, label) - internal use for WAL
    #[doc(hidden)]
    pub labels_removed_ids: std::collections::HashSet<(u64, String)>,
}

impl QueryStats {
    /// Check if any modifications were made.
    pub fn has_updates(&self) -> bool {
        self.nodes_created > 0
            || self.nodes_deleted > 0
            || self.relationships_created > 0
            || self.relationships_deleted > 0
            || self.properties_set > 0
            || self.properties_removed > 0
            || self.labels_added > 0
            || self.labels_removed > 0
    }

    /// Merge stats from another query.
    pub fn merge(&mut self, other: &QueryStats) {
        self.nodes_created += other.nodes_created;
        self.nodes_deleted += other.nodes_deleted;
        self.relationships_created += other.relationships_created;
        self.relationships_deleted += other.relationships_deleted;
        // Don't merge properties_set directly - it will be calculated in finalize() from unique properties
        self.properties_removed += other.properties_removed;
        // Don't merge labels_added - it will be calculated in finalize() from unique_labels
        // self.labels_added += other.labels_added;
        // Don't merge labels_removed - it will be calculated in finalize() from unique_labels_removed
        // self.labels_removed += other.labels_removed;
        self.unique_labels.extend(other.unique_labels.clone());
        self.unique_labels_removed.extend(other.unique_labels_removed.clone());
        self.nodes_created_ids.extend(other.nodes_created_ids.clone());
        self.relationships_created_ids.extend(other.relationships_created_ids.clone());
        self.nodes_deleted_ids.extend(other.nodes_deleted_ids.clone());
        self.relationships_deleted_ids.extend(other.relationships_deleted_ids.clone());
        self.unique_node_properties.extend(other.unique_node_properties.clone());
        self.unique_rel_properties.extend(other.unique_rel_properties.clone());
        self.labels_added_ids.extend(other.labels_added_ids.clone());
        self.labels_removed_ids.extend(other.labels_removed_ids.clone());
    }

    /// Finalize stats (should be called before returning)
    pub fn finalize(&mut self) {
        // labels_added should be the count of UNIQUE label types, not total additions
        // e.g., CREATE (:A), (:A) adds 2 labels but only 1 unique type
        self.labels_added = self.unique_labels.len();
        // labels_removed should also be the count of UNIQUE label types
        // e.g., DELETE 2 nodes with :User label removes 1 unique type
        self.labels_removed = self.unique_labels_removed.len();
        // properties_set is the count of UNIQUE (entity, property) pairs set
        // e.g., CREATE (a {x: 1}) SET a.x = 2 sets 1 unique property, not 2
        self.properties_set = self.unique_node_properties.len() + self.unique_rel_properties.len();
    }
}

impl fmt::Display for QueryStats {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts = Vec::new();

        if self.nodes_created > 0 {
            parts.push(format!("Nodes created: {}", self.nodes_created));
        }
        if self.nodes_deleted > 0 {
            parts.push(format!("Nodes deleted: {}", self.nodes_deleted));
        }
        if self.relationships_created > 0 {
            parts.push(format!(
                "Relationships created: {}",
                self.relationships_created
            ));
        }
        if self.relationships_deleted > 0 {
            parts.push(format!(
                "Relationships deleted: {}",
                self.relationships_deleted
            ));
        }
        if self.properties_set > 0 {
            parts.push(format!("Properties set: {}", self.properties_set));
        }
        if self.labels_added > 0 {
            parts.push(format!("Labels added: {}", self.labels_added));
        }
        if self.labels_removed > 0 {
            parts.push(format!("Labels removed: {}", self.labels_removed));
        }

        if parts.is_empty() {
            write!(f, "(no changes)")
        } else {
            write!(f, "{}", parts.join(", "))
        }
    }
}

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

    #[test]
    fn test_query_result() {
        let mut result = QueryResult::with_columns(vec!["name".to_string(), "age".to_string()]);

        let mut row1 = Record::new();
        row1.add("name", CypherValue::String("Alice".to_string()));
        row1.add("age", CypherValue::Integer(30));
        result.add_row(row1);

        let mut row2 = Record::new();
        row2.add("name", CypherValue::String("Bob".to_string()));
        row2.add("age", CypherValue::Integer(25));
        result.add_row(row2);

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.column_values("name").len(), 2);
    }

    #[test]
    fn test_query_stats() {
        let mut stats = QueryStats::default();
        assert!(!stats.has_updates());

        stats.nodes_created = 5;
        assert!(stats.has_updates());

        let mut other = QueryStats::default();
        other.relationships_created = 3;
        stats.merge(&other);

        assert_eq!(stats.nodes_created, 5);
        assert_eq!(stats.relationships_created, 3);
    }
}
