package com.jordanbot.autoride.engine

import android.util.Log
import com.jordanbot.autoride.model.RideRequest
import kotlinx.coroutines.*

object RideDataMerger {
    private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
    private var lastRequest: RideRequest? = null
    private var lastTimestamp: Long = 0
    private const val MERGE_WINDOW_MS = 5000L

    var onRideReady: ((RideRequest) -> Unit)? = null

    @Synchronized
    fun updateFromNotification(request: RideRequest) {
        Log.d("JordanBot", "🔔 Merger received Notification data: ${request.priceJod} JOD")
        merge(request)
    }

    @Synchronized
    fun updateFromScreen(request: RideRequest) {
        Log.d("JordanBot", "👁️ Merger received Screen data: ${request.priceJod} JOD")
        merge(request)
    }

    private fun merge(newPart: RideRequest) {
        val now = System.currentTimeMillis()
        val current = lastRequest

        if (current == null || (now - lastTimestamp) > MERGE_WINDOW_MS || current.appPackage != newPart.appPackage) {
            // New request sequence
            lastRequest = newPart
            lastTimestamp = now
            
            // Speed optimization: If the very first source has the price, emit INSTANTLY. No delays.
            emitIfReady()
        } else {
            // Merge into current
            lastRequest = current.copy(
                priceJod = newPart.priceJod ?: current.priceJod,
                minutesAway = newPart.minutesAway ?: current.minutesAway,
                distanceKm = newPart.distanceKm ?: current.distanceKm,
                pickupAddress = newPart.pickupAddress ?: current.pickupAddress,
                dropoffAddress = newPart.dropoffAddress ?: current.dropoffAddress,
                title = if (newPart.title.isNotEmpty() && newPart.title != "Screen Scrape") newPart.title else current.title,
                text = if (newPart.text.isNotEmpty() && newPart.text != current.text) "${current.text} | ${newPart.text}" else current.text
            )
            lastTimestamp = now
            emitIfReady()
        }
    }

    private fun emitIfReady() {
        val ride = lastRequest ?: return
        
        // Criteria for "Ready": We have at least a price
        if (ride.priceJod != null) {
            Log.d("JordanBot", "⚡ FLASH ACCEPT: RIDE READY IN MILLISECONDS: $ride")
            onRideReady?.invoke(ride)
            lastRequest = null // Clear to avoid double emission
        }
    }
}
