package com.jordanbot.autoride.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.accessibilityservice.GestureDescription
import android.graphics.Path
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.jordanbot.autoride.engine.RideDataMerger
import com.jordanbot.autoride.filter.FilterEngine
import com.jordanbot.autoride.model.RideRequest
import com.jordanbot.autoride.subscription.SubscriptionManager

class RideAccessibilityService : AccessibilityService() {

    private val handler = Handler(Looper.getMainLooper())

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        val rootNode = rootInActiveWindow ?: return
        val packageName = event.packageName?.toString() ?: ""

        // Only process supported apps
        if (!isSupportedApp(packageName)) return

        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED || 
            event.eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
            
            val screenData = scrapeScreen(rootNode, packageName)
            if (screenData != null) {
                RideDataMerger.updateFromScreen(screenData)
            }
        }
    }

    private fun isSupportedApp(pkg: String): Boolean {
        return pkg == "com.ubercab.driver" || 
               pkg == "com.careem.adma" || 
               pkg == "me.com.easytaxista" || // Jeeny
               pkg == "com.PetraRide_Captain" || // Petra Ride
               pkg == "com.taxif.driver" // TaxiF
    }

    private fun scrapeScreen(root: AccessibilityNodeInfo, pkg: String): RideRequest? {
        val allText = mutableListOf<String>()
        collectAllText(root, allText)
        val combinedText = allText.joinToString(" ")

        // Extract price
        val priceRegex = """(\d+\.?\d*)\s*(JOD|د\.أ|دينار)""".toRegex()
        val priceMatch = priceRegex.find(combinedText)
        val price = priceMatch?.groupValues?.get(1)?.toDoubleOrNull()

        if (price != null) {
            Log.d("JordanBot", "👁️ Scraped price from screen: $price $pkg")
            
            return RideRequest(
                appPackage = pkg,
                priceJod = price,
                minutesAway = null,
                distanceKm = null,
                title = "Screen Scrape",
                text = combinedText
            )
        }
        return null
    }

    private fun collectAllText(node: AccessibilityNodeInfo?, list: MutableList<String>) {
        if (node == null) return
        node.text?.let { list.add(it.toString()) }
        for (i in 0 until node.childCount) {
            collectAllText(node.getChild(i), list)
        }
    }

    private fun findAndAccept(root: AccessibilityNodeInfo, pkg: String) {
        val acceptTerms = listOf("Accept", "قبول", "Tap to accept", "Confirm", "تأكيد")
        
        for (term in acceptTerms) {
            val nodes = root.findAccessibilityNodeInfosByText(term)
            for (node in nodes) {
                if (node.isClickable || node.parent?.isClickable == true) {
                    val target = if (node.isClickable) node else node.parent
                    Log.d("JordanBot", "🤖 Auto-Accepting via Click: $term")
                    target.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    return
                }
            }
        }

        if (pkg == "com.ubercab.driver") {
            performUberSwipe()
        }
    }

    private fun performUberSwipe() {
        Log.d("JordanBot", "🤖 Attempting Uber Swipe...")
        val displayMetrics = resources.displayMetrics
        val width = displayMetrics.widthPixels
        val height = displayMetrics.heightPixels

        val path = Path()
        path.moveTo(width * 0.2f, height * 0.85f)
        path.lineTo(width * 0.8f, height * 0.85f)

        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 500))
            .build()

        dispatchGesture(gesture, null, null)
    }

    override fun onInterrupt() {}

    override fun onServiceConnected() {
        super.onServiceConnected()
        
        FilterEngine.init(this)
        
        RideDataMerger.onRideReady = { mergedRide ->
            val passesFilters = FilterEngine.evaluate(mergedRide)
            val canAccept = SubscriptionManager.canAcceptRides
            
            Log.d("JordanBot", "🏁 Merger callback: PassesFilters=$passesFilters, CanAcceptQuota=$canAccept for ${mergedRide.appPackage}")
            
            if (passesFilters) {
                if (canAccept) {
                    val rootNode = rootInActiveWindow
                    if (rootNode != null) {
                        findAndAccept(rootNode, mergedRide.appPackage)
                    } else {
                        Log.e("JordanBot", "Cannot accept: rootInActiveWindow is null")
                    }
                } else {
                    Log.w("JordanBot", "⚠️ Ride matches filters but DAILY LIMIT REACHED. Upgrade required.")
                }
            }
        }

        val info = AccessibilityServiceInfo().apply {
            eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            notificationTimeout = 100
            flags = AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS or AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
        }
        this.serviceInfo = info
    }
}
