import Foundation

/// Ring buffer for breadcrumbs with fixed max size
public actor BreadcrumbTrail {
    private var breadcrumbs: [DiagnosticsBreadcrumb] = []
    private let maxSize: Int
    
    public init(maxSize: Int = 100) {
        self.maxSize = maxSize
    }
    
    /// Add a breadcrumb to the trail
    public func add(category: String, message: String, data: [String: AnyCodable]? = nil) {
        let breadcrumb = DiagnosticsBreadcrumb(
            timestamp: ISO8601DateFormatter().string(from: Date()),
            category: category,
            message: message,
            data: data
        )
        
        breadcrumbs.append(breadcrumb)
        
        // Evict oldest if over limit
        if breadcrumbs.count > maxSize {
            breadcrumbs.removeFirst()
        }
    }
    
    /// Get all breadcrumbs (oldest first)
    public func getAll() -> [DiagnosticsBreadcrumb] {
        breadcrumbs
    }
    
    /// Get last N breadcrumbs
    public func getLast(_ n: Int) -> [DiagnosticsBreadcrumb] {
        Array(breadcrumbs.suffix(n))
    }
    
    /// Get most recent breadcrumb
    public func getMostRecent() -> DiagnosticsBreadcrumb? {
        breadcrumbs.last
    }
    
    /// Clear all breadcrumbs
    public func clear() {
        breadcrumbs.removeAll()
    }
    
    /// Get current size
    public func size() -> Int {
        breadcrumbs.count
    }
}
