package top.yeij.cyrene.service

import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo

class CyreneAccessibilityService : AccessibilityService() {

    companion object {
        @Volatile
        private var instance: CyreneAccessibilityService? = null

        fun getScreenContent(): String {
            return instance?.captureScreenContent() ?: ""
        }

        fun isRunning(): Boolean = instance != null
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        instance = this
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {}

    override fun onInterrupt() {}

    override fun onDestroy() {
        instance = null
        super.onDestroy()
    }

    private fun captureScreenContent(): String {
        val root = rootInActiveWindow ?: return ""
        return try {
            val sb = StringBuilder()
            collectNodeText(root, sb, depth = 0)
            sb.toString().trim()
        } finally {
            root.recycle()
        }
    }

    private fun collectNodeText(node: AccessibilityNodeInfo, sb: StringBuilder, depth: Int) {
        // Skip the root decor view itself content, and limit depth
        if (depth > 16) return

        val text = node.text?.toString()?.trim()
        val contentDesc = node.contentDescription?.toString()?.trim()

        if (!text.isNullOrEmpty() && text != contentDesc) {
            if (sb.isNotEmpty()) sb.append("\n")
            sb.append(text)
        } else if (!contentDesc.isNullOrEmpty() && depth > 0) {
            // Only include content descriptions for non-root nodes
            if (sb.isNotEmpty()) sb.append("\n")
            sb.append(contentDesc)
        }

        for (i in 0 until node.childCount) {
            val child = node.getChild(i) ?: continue
            collectNodeText(child, sb, depth + 1)
            child.recycle()
        }
    }
}
