package distribution

import (
	"time"
)

// DistributionStatistics represents distribution performance statistics
type DistributionStatistics struct {
	// Operations
	TotalDistributions    int64         `json:"total_distributions"`     // Total distributions performed
	SuccessfulDistributions int64       `json:"successful_distributions"` // Successful distributions
	FailedDistributions   int64         `json:"failed_distributions"`    // Failed distributions
	TotalRetrievals       int64         `json:"total_retrievals"`        // Total retrievals performed
	SuccessfulRetrievals  int64         `json:"successful_retrievals"`   // Successful retrievals
	FailedRetrievals      int64         `json:"failed_retrievals"`       // Failed retrievals
	
	// Performance
	AverageDistributionTime time.Duration `json:"average_distribution_time"` // Average distribution time
	AverageRetrievalTime    time.Duration `json:"average_retrieval_time"`    // Average retrieval time
	AverageReplicationTime  time.Duration `json:"average_replication_time"`  // Average replication time
	
	// Storage
	TotalContextsStored   int64         `json:"total_contexts_stored"`   // Total contexts in DHT
	TotalStorageSize      int64         `json:"total_storage_size"`      // Total storage size
	AverageReplicationFactor float64    `json:"average_replication_factor"` // Average replication factor
	
	// Health
	HealthyNodes          int           `json:"healthy_nodes"`           // Number of healthy nodes
	UnhealthyNodes        int           `json:"unhealthy_nodes"`         // Number of unhealthy nodes
	AverageNodeLatency    time.Duration `json:"average_node_latency"`    // Average node latency
	
	// Conflicts
	TotalConflicts        int64         `json:"total_conflicts"`         // Total conflicts encountered
	ResolvedConflicts     int64         `json:"resolved_conflicts"`      // Successfully resolved conflicts
	PendingConflicts      int64         `json:"pending_conflicts"`       // Conflicts pending resolution
	
	// Synchronization
	LastSyncTime          time.Time     `json:"last_sync_time"`          // Last synchronization time
	SyncErrors            int64         `json:"sync_errors"`             // Synchronization errors
	
	// Network
	NetworkPartitions     int           `json:"network_partitions"`      // Current network partitions
	DataTransferred       int64         `json:"data_transferred"`        // Total data transferred
	
	// Timestamps
	LastResetTime         time.Time     `json:"last_reset_time"`         // When stats were last reset
	CollectedAt           time.Time     `json:"collected_at"`            // When stats were collected
}

// DHTStatistics represents DHT operation statistics
type DHTStatistics struct {
	// Basic operations
	PutOperations         int64         `json:"put_operations"`          // Total put operations
	GetOperations         int64         `json:"get_operations"`          // Total get operations
	DeleteOperations      int64         `json:"delete_operations"`       // Total delete operations
	ExistsOperations      int64         `json:"exists_operations"`       // Total exists operations
	
	// Performance
	AveragePutTime        time.Duration `json:"average_put_time"`        // Average put operation time
	AverageGetTime        time.Duration `json:"average_get_time"`        // Average get operation time
	AverageDeleteTime     time.Duration `json:"average_delete_time"`     // Average delete operation time
	
	// Success rates
	PutSuccessRate        float64       `json:"put_success_rate"`        // Put operation success rate
	GetSuccessRate        float64       `json:"get_success_rate"`        // Get operation success rate
	DeleteSuccessRate     float64       `json:"delete_success_rate"`     // Delete operation success rate
	
	// Storage
	TotalKeys             int64         `json:"total_keys"`              // Total keys stored
	TotalDataSize         int64         `json:"total_data_size"`         // Total data size
	AverageKeySize        int64         `json:"average_key_size"`        // Average key size
	AverageValueSize      int64         `json:"average_value_size"`      // Average value size
	
	// Network
	ConnectedPeers        int           `json:"connected_peers"`         // Number of connected peers
	NetworkLatency        time.Duration `json:"network_latency"`         // Average network latency
	BandwidthUsage        int64         `json:"bandwidth_usage"`         // Bandwidth usage in bytes/sec
	
	// Health
	HealthyPeers          int           `json:"healthy_peers"`           // Number of healthy peers
	UnresponsivePeers     int           `json:"unresponsive_peers"`      // Number of unresponsive peers
	
	// Errors
	ErrorRate             float64       `json:"error_rate"`              // Overall error rate
	TimeoutErrors         int64         `json:"timeout_errors"`          // Number of timeout errors
	NetworkErrors         int64         `json:"network_errors"`          // Number of network errors
	
	// Timestamps
	LastUpdated           time.Time     `json:"last_updated"`            // When stats were last updated
}

// ReplicationStatistics represents replication performance statistics
type ReplicationStatistics struct {
	// Replication operations
	ReplicationRequests   int64         `json:"replication_requests"`    // Total replication requests
	SuccessfulReplications int64        `json:"successful_replications"` // Successful replications
	FailedReplications    int64         `json:"failed_replications"`     // Failed replications
	
	// Repair operations
	RepairRequests        int64         `json:"repair_requests"`         // Total repair requests
	SuccessfulRepairs     int64         `json:"successful_repairs"`      // Successful repairs
	FailedRepairs         int64         `json:"failed_repairs"`          // Failed repairs
	
	// Performance
	AverageReplicationTime time.Duration `json:"average_replication_time"` // Average replication time
	AverageRepairTime     time.Duration `json:"average_repair_time"`      // Average repair time
	
	// Health
	UnderReplicatedData   int64         `json:"under_replicated_data"`   // Amount of under-replicated data
	OverReplicatedData    int64         `json:"over_replicated_data"`    // Amount of over-replicated data
	CorruptedReplicas     int64         `json:"corrupted_replicas"`      // Number of corrupted replicas
	
	// Rebalancing
	RebalanceOperations   int64         `json:"rebalance_operations"`    // Total rebalance operations
	LastRebalanceTime     time.Time     `json:"last_rebalance_time"`     // Last rebalance time
	
	// Statistics
	AverageReplicationFactor float64    `json:"average_replication_factor"` // Average replication factor
	ReplicationEfficiency float64       `json:"replication_efficiency"`     // Replication efficiency
	
	// Timestamps
	LastUpdated           time.Time     `json:"last_updated"`            // When stats were last updated
}

// GossipStatistics represents gossip protocol statistics
type GossipStatistics struct {
	// Messages
	MessagesSent          int64         `json:"messages_sent"`           // Total messages sent
	MessagesReceived      int64         `json:"messages_received"`       // Total messages received
	MessagesDropped       int64         `json:"messages_dropped"`        // Messages dropped
	
	// Rounds
	GossipRounds          int64         `json:"gossip_rounds"`           // Total gossip rounds
	AverageRoundTime      time.Duration `json:"average_round_time"`      // Average round time
	
	// Peers
	ActivePeers           int           `json:"active_peers"`            // Number of active peers
	ReachablePeers        int           `json:"reachable_peers"`         // Number of reachable peers
	UnreachablePeers      int           `json:"unreachable_peers"`       // Number of unreachable peers
	
	// Convergence
	ConvergenceTime       time.Duration `json:"convergence_time"`        // Average convergence time
	PartialConvergence    int64         `json:"partial_convergence"`     // Partial convergence events
	FullConvergence       int64         `json:"full_convergence"`        // Full convergence events
	
	// Bandwidth
	BandwidthUsage        int64         `json:"bandwidth_usage"`         // Bandwidth usage
	CompressionRatio      float64       `json:"compression_ratio"`       // Message compression ratio
	
	// Errors
	NetworkErrors         int64         `json:"network_errors"`          // Network errors
	ProtocolErrors        int64         `json:"protocol_errors"`         // Protocol errors
	
	// Timestamps
	LastGossipTime        time.Time     `json:"last_gossip_time"`        // Last gossip time
	LastUpdated           time.Time     `json:"last_updated"`            // When stats were last updated
}

// NetworkStatistics represents network performance statistics
type NetworkStatistics struct {
	// Connectivity
	TotalNodes            int           `json:"total_nodes"`             // Total nodes in network
	ConnectedNodes        int           `json:"connected_nodes"`         // Connected nodes
	DisconnectedNodes     int           `json:"disconnected_nodes"`      // Disconnected nodes
	
	// Performance
	AverageLatency        time.Duration `json:"average_latency"`         // Average network latency
	MaxLatency            time.Duration `json:"max_latency"`             // Maximum latency
	MinLatency            time.Duration `json:"min_latency"`             // Minimum latency
	
	// Bandwidth
	TotalBandwidth        int64         `json:"total_bandwidth"`         // Total bandwidth usage
	IncomingBandwidth     int64         `json:"incoming_bandwidth"`      // Incoming bandwidth
	OutgoingBandwidth     int64         `json:"outgoing_bandwidth"`      // Outgoing bandwidth
	
	// Partitions
	NetworkPartitions     int           `json:"network_partitions"`      // Current partitions
	PartitionHistory      int64         `json:"partition_history"`       // Historical partition count
	AveragePartitionDuration time.Duration `json:"average_partition_duration"` // Average partition duration
	
	// Failures
	NodeFailures          int64         `json:"node_failures"`           // Node failures
	ConnectionFailures    int64         `json:"connection_failures"`     // Connection failures
	TimeoutFailures       int64         `json:"timeout_failures"`        // Timeout failures
	
	// Recovery
	RecoveryOperations    int64         `json:"recovery_operations"`     // Recovery operations
	AverageRecoveryTime   time.Duration `json:"average_recovery_time"`   // Average recovery time
	
	// Health
	OverallHealth         float64       `json:"overall_health"`          // Overall network health (0-1)
	ConnectivityIndex     float64       `json:"connectivity_index"`      // Connectivity index (0-1)
	
	// Timestamps
	LastHealthCheck       time.Time     `json:"last_health_check"`       // Last health check
	LastUpdated           time.Time     `json:"last_updated"`            // When stats were last updated
}

// GossipState represents current gossip protocol state
type GossipState struct {
	Running               bool          `json:"running"`                 // Whether gossip is running
	CurrentRound          int64         `json:"current_round"`           // Current gossip round
	RoundStartTime        time.Time     `json:"round_start_time"`        // When current round started
	RoundDuration         time.Duration `json:"round_duration"`          // Current round duration
	ActiveConnections     int           `json:"active_connections"`      // Active peer connections
	PendingMessages       int           `json:"pending_messages"`        // Pending messages
	NextRoundTime         time.Time     `json:"next_round_time"`         // Next scheduled round
	ProtocolVersion       string        `json:"protocol_version"`        // Gossip protocol version
	State                 string        `json:"state"`                   // Current state
}

// PartitionInfo represents network partition information
type PartitionInfo struct {
	PartitionDetected     bool          `json:"partition_detected"`      // Whether partition detected
	PartitionCount        int           `json:"partition_count"`         // Number of partitions
	LargestPartitionSize  int           `json:"largest_partition_size"`  // Size of largest partition
	CurrentPartitionSize  int           `json:"current_partition_size"`  // Size of current partition
	IsolatedNodes         []string      `json:"isolated_nodes"`          // List of isolated nodes
	ConnectivityMatrix    map[string]map[string]bool `json:"connectivity_matrix"` // Node connectivity matrix
	DetectedAt            time.Time     `json:"detected_at"`             // When partition was detected
	Duration              time.Duration `json:"duration"`                // Partition duration
	EstimatedRecoveryTime time.Duration `json:"estimated_recovery_time"` // Estimated recovery time
}

// NetworkTopology represents current network topology
type NetworkTopology struct {
	TotalNodes            int                    `json:"total_nodes"`            // Total nodes
	Connections           map[string][]string    `json:"connections"`            // Node connections
	ClusterDiameter       int                    `json:"cluster_diameter"`       // Network diameter
	ClusteringCoefficient float64                `json:"clustering_coefficient"` // Clustering coefficient
	CentralNodes          []string               `json:"central_nodes"`          // Most central nodes
	BridgeNodes           []string               `json:"bridge_nodes"`           // Bridge nodes
	Regions               map[string][]string    `json:"regions"`                // Geographic regions
	AvailabilityZones     map[string][]string    `json:"availability_zones"`     // Availability zones
	UpdatedAt             time.Time              `json:"updated_at"`             // When topology was updated
}

// PeerInfo represents information about peer nodes
type PeerInfo struct {
	NodeID                string        `json:"node_id"`                 // Node identifier
	Address               string        `json:"address"`                 // Network address
	Status                string        `json:"status"`                  // Node status
	Version               string        `json:"version"`                 // Software version
	Region                string        `json:"region"`                  // Geographic region
	AvailabilityZone      string        `json:"availability_zone"`       // Availability zone
	Capacity              int64         `json:"capacity"`                // Storage capacity
	UsedCapacity          int64         `json:"used_capacity"`           // Used storage
	CPU                   float64       `json:"cpu"`                     // CPU usage
	Memory                float64       `json:"memory"`                  // Memory usage
	Latency               time.Duration `json:"latency"`                 // Network latency
	LastSeen              time.Time     `json:"last_seen"`               // When last seen
	Capabilities          []string      `json:"capabilities"`            // Node capabilities
}

// ConnectivityReport represents connectivity test results
type ConnectivityReport struct {
	TotalPeers            int                    `json:"total_peers"`             // Total peers tested
	ReachablePeers        int                    `json:"reachable_peers"`         // Reachable peers
	UnreachablePeers      int                    `json:"unreachable_peers"`       // Unreachable peers
	PeerResults           map[string]*ConnectivityResult `json:"peer_results"` // Individual results
	AverageLatency        time.Duration          `json:"average_latency"`         // Average latency
	OverallHealth         float64                `json:"overall_health"`          // Overall health
	TestedAt              time.Time              `json:"tested_at"`               // When test was performed
	TestDuration          time.Duration          `json:"test_duration"`           // Test duration
}

// ConnectivityResult represents connectivity test result for a single peer
type ConnectivityResult struct {
	PeerID                string        `json:"peer_id"`                 // Peer identifier
	Reachable             bool          `json:"reachable"`               // Whether reachable
	Latency               time.Duration `json:"latency"`                 // Network latency
	PacketLoss            float64       `json:"packet_loss"`             // Packet loss percentage
	Bandwidth             int64         `json:"bandwidth"`               // Available bandwidth
	Error                 string        `json:"error,omitempty"`         // Error message if any
	TestedAt              time.Time     `json:"tested_at"`               // When tested
}

// RecoveryResult represents partition recovery results
type RecoveryResult struct {
	RecoverySuccessful    bool          `json:"recovery_successful"`     // Whether recovery succeeded
	RecoveredNodes        []string      `json:"recovered_nodes"`         // Nodes that recovered
	StillIsolatedNodes    []string      `json:"still_isolated_nodes"`    // Still isolated nodes
	DataReconciled        int64         `json:"data_reconciled"`         // Amount of data reconciled
	ConflictsResolved     int           `json:"conflicts_resolved"`      // Conflicts resolved
	RecoveryTime          time.Duration `json:"recovery_time"`           // Time taken for recovery
	RecoveredAt           time.Time     `json:"recovered_at"`            // When recovery completed
	NextRetryTime         *time.Time    `json:"next_retry_time,omitempty"` // Next retry time if failed
}

// RepairResult represents replica repair results
type RepairResult struct {
	Address               string        `json:"address"`                 // Context address
	RepairedReplicas      int           `json:"repaired_replicas"`       // Number of repaired replicas
	CreatedReplicas       int           `json:"created_replicas"`        // Number of created replicas
	RemovedReplicas       int           `json:"removed_replicas"`        // Number of removed replicas
	RepairTime            time.Duration `json:"repair_time"`             // Time taken for repair
	RepairSuccessful      bool          `json:"repair_successful"`       // Whether repair succeeded
	Errors                []string      `json:"errors,omitempty"`        // Repair errors
	RepairedAt            time.Time     `json:"repaired_at"`             // When repair completed
}

// RebalanceResult represents rebalancing operation results
type RebalanceResult struct {
	MovedReplicas         int           `json:"moved_replicas"`          // Number of moved replicas
	CreatedReplicas       int           `json:"created_replicas"`        // Number of created replicas
	RemovedReplicas       int           `json:"removed_replicas"`        // Number of removed replicas
	DataMoved             int64         `json:"data_moved"`              // Amount of data moved
	RebalanceTime         time.Duration `json:"rebalance_time"`          // Time taken for rebalance
	RebalanceSuccessful   bool          `json:"rebalance_successful"`    // Whether rebalance succeeded
	LoadBalanceImprovement float64      `json:"load_balance_improvement"` // Load balance improvement
	Errors                []string      `json:"errors,omitempty"`        // Rebalance errors
	RebalancedAt          time.Time     `json:"rebalanced_at"`           // When rebalance completed
}

// ReplicationStatus represents current replication status
type ReplicationStatus struct {
	Address               string                 `json:"address"`                 // Context address
	DesiredReplicas       int                    `json:"desired_replicas"`        // Desired replica count
	CurrentReplicas       int                    `json:"current_replicas"`        // Current replica count
	HealthyReplicas       int                    `json:"healthy_replicas"`        // Healthy replica count
	ReplicationHealth     float64                `json:"replication_health"`      // Replication health (0-1)
	ReplicaDistribution   map[string]int         `json:"replica_distribution"`    // Replicas per zone
	LastReplication       time.Time              `json:"last_replication"`        // Last replication time
	ReplicationErrors     []string               `json:"replication_errors"`      // Recent replication errors
	Status                string                 `json:"status"`                  // Overall status
}

// Additional utility types

// KeyGenerator generates consistent keys for DHT storage
type KeyGenerator interface {
	GenerateContextKey(address string, role string) string
	GenerateMetadataKey(address string) string
	GenerateReplicationKey(address string) string
}

// ConsistentHashing provides consistent hashing for node selection
type ConsistentHashing interface {
	GetNode(key string) (string, error)
	GetNodes(key string, count int) ([]string, error)
	AddNode(nodeID string) error
	RemoveNode(nodeID string) error
	GetAllNodes() []string
}

// VectorClock represents vector clock for conflict resolution
type VectorClock struct {
	Clock     map[string]int64 `json:"clock"`      // Vector clock entries
	UpdatedAt time.Time        `json:"updated_at"` // When last updated
}

// VectorClockManager manages vector clocks for conflict resolution
type VectorClockManager interface {
	GetClock(nodeID string) (*VectorClock, error)
	UpdateClock(nodeID string, clock *VectorClock) error
	CompareClock(clock1, clock2 *VectorClock) ClockRelation
	MergeClock(clocks []*VectorClock) *VectorClock
}

// ClockRelation represents relationship between vector clocks
type ClockRelation string

const (
	ClockBefore     ClockRelation = "before"     // clock1 happened before clock2
	ClockAfter      ClockRelation = "after"      // clock1 happened after clock2
	ClockConcurrent ClockRelation = "concurrent" // clocks are concurrent
	ClockEqual      ClockRelation = "equal"      // clocks are equal
)