package com.bytelyst.platform.diagnostics

import java.text.SimpleDateFormat
import java.util.*

/**
 * Ring buffer for breadcrumbs with fixed max size
 */
class BreadcrumbTrail(private val maxSize: Int = 100) {
    private val breadcrumbs = mutableListOf<DiagnosticsBreadcrumb>()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply {
        timeZone = TimeZone.getTimeZone("UTC")
    }

    /**
     * Add a breadcrumb to the trail
     */
    @Synchronized
    fun add(category: String, message: String, data: Map<String, String>? = null) {
        val breadcrumb = DiagnosticsBreadcrumb(
            timestamp = dateFormat.format(Date()),
            category = category,
            message = message,
            data = data
        )

        breadcrumbs.add(breadcrumb)

        // Evict oldest if over limit
        if (breadcrumbs.size > maxSize) {
            breadcrumbs.removeAt(0)
        }
    }

    /**
     * Get all breadcrumbs (oldest first)
     */
    @Synchronized
    fun getAll(): List<DiagnosticsBreadcrumb> {
        return breadcrumbs.toList()
    }

    /**
     * Get last N breadcrumbs
     */
    @Synchronized
    fun getLast(n: Int): List<DiagnosticsBreadcrumb> {
        return breadcrumbs.takeLast(n)
    }

    /**
     * Get most recent breadcrumb
     */
    @Synchronized
    fun getMostRecent(): DiagnosticsBreadcrumb? {
        return breadcrumbs.lastOrNull()
    }

    /**
     * Clear all breadcrumbs
     */
    @Synchronized
    fun clear() {
        breadcrumbs.clear()
    }

    /**
     * Get current size
     */
    @Synchronized
    fun size(): Int {
        return breadcrumbs.size
    }
}
