package com.bytelyst.platform

import android.net.Uri
import android.util.Log

/**
 * Deep Link Route data class
 */
data class DeepLinkRoute(
    val screen: String,
    val params: Map<String, String> = emptyMap()
)

/**
 * Deep link handler type alias
 */
typealias DeepLinkHandler = (DeepLinkRoute) -> Unit

/**
 * Deep Link Router class
 * Handles routing from push notification deep links to app screens
 */
class DeepLinkRouter {
    private val handlers = mutableMapOf<String, DeepLinkHandler>()
    private var fallbackHandler: DeepLinkHandler? = null

    companion object {
        private const val TAG = "DeepLinkRouter"
    }

    /**
     * Register a handler for a specific screen
     */
    fun register(screen: String, handler: DeepLinkHandler) {
        handlers[screen] = handler
    }

    /**
     * Set a fallback handler for unregistered screens
     */
    fun setFallback(handler: DeepLinkHandler) {
        fallbackHandler = handler
    }

    /**
     * Parse a deep link URL and extract route
     */
    fun parseDeepLink(urlString: String): DeepLinkRoute? {
        return try {
            val uri = Uri.parse(urlString)
            
            // Handle app-specific URLs: myapp://screen/params
            if (uri.scheme != "http" && uri.scheme != "https") {
                val pathSegments = uri.pathSegments
                val screen = pathSegments.firstOrNull() ?: "home"
                
                val params = mutableMapOf<String, String>()
                uri.queryParameterNames.forEach { key ->
                    uri.getQueryParameter(key)?.let { value ->
                        params[key] = value
                    }
                }
                
                DeepLinkRoute(screen, params)
            }
            // Handle web URLs with deep link params
            else if (uri.getQueryParameter("dl") != null) {
                parseDeepLink(uri.getQueryParameter("dl")!!)
            }
            // Handle path-based routing: /screen/params
            else {
                val pathSegments = uri.pathSegments
                if (pathSegments.isNotEmpty()) {
                    val screen = pathSegments[0]
                    
                    val params = mutableMapOf<String, String>()
                    uri.queryParameterNames.forEach { key ->
                        uri.getQueryParameter(key)?.let { value ->
                            params[key] = value
                        }
                    }
                    
                    DeepLinkRoute(screen, params)
                } else {
                    null
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "Failed to parse deep link: $urlString", e)
            null
        }
    }

    /**
     * Handle a deep link route
     */
    fun handle(route: DeepLinkRoute): Boolean {
        val handler = handlers[route.screen]
        
        return if (handler != null) {
            handler(route)
            true
        } else if (fallbackHandler != null) {
            fallbackHandler?.invoke(route)
            true
        } else {
            Log.w(TAG, "No handler for screen: ${route.screen}")
            false
        }
    }

    /**
     * Process a deep link URL end-to-end
     */
    fun process(urlString: String): Boolean {
        val route = parseDeepLink(urlString)
        return if (route != null) {
            handle(route)
        } else {
            Log.w(TAG, "Failed to parse deep link: $urlString")
            false
        }
    }
}

/**
 * Create a broadcast deep link URL
 */
fun createBroadcastDeepLink(
    baseUrl: String,
    screen: String,
    params: Map<String, String> = emptyMap(),
    broadcastId: String? = null
): String {
    val uriBuilder = Uri.parse(baseUrl).buildUpon()
        .path("/$screen")
    
    params.forEach { (key, value) ->
        uriBuilder.appendQueryParameter(key, value)
    }
    
    broadcastId?.let {
        uriBuilder.appendQueryParameter("broadcastId", it)
    }
    
    return uriBuilder.build().toString()
}

/**
 * Common deep link screens
 */
object DeepLinkScreens {
    // Broadcasts
    const val BROADCAST = "broadcast"
    const val ANNOUNCEMENTS = "announcements"
    
    // Surveys
    const val SURVEY = "survey"
    const val SURVEY_LIST = "surveys"
    
    // Product-specific
    const val SETTINGS = "settings"
    const val PROFILE = "profile"
    const val UPGRADE = "upgrade"
    const val SUPPORT = "support"
    
    // Fallback
    const val HOME = "home"
}

// Singleton instance for app-wide use
val deepLinkRouter = DeepLinkRouter()
