package com.agentui.desktop

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.service.voice.VoiceInteractionSession
import android.service.voice.VoiceInteractionSessionService
import android.util.Log

class AgentVoiceInteractionSessionService : VoiceInteractionSessionService() {

    override fun onNewSession(args: Bundle?): VoiceInteractionSession {
        Log.d(TAG, "onNewSession called")
        return AgentSession(this)
    }

    private class AgentSession(
        private val ctx: android.content.Context
    ) : VoiceInteractionSession(ctx) {

        override fun onPrepareShow(args: Bundle?, showFlags: Int) {
            super.onPrepareShow(args, showFlags)
            // Disable the default VoiceInteractionSession window/UI -
            // we launch our own activity instead
            setUiEnabled(false)
            Log.d(TAG, "onPrepareShow: UI disabled, will launch activity")
        }

        override fun onShow(args: Bundle?, showFlags: Int) {
            super.onShow(args, showFlags)
            Log.d(TAG, "onShow called, flags=$showFlags")

            val intent = Intent(ctx, VoiceCommandActivity::class.java).apply {
                action = Intent.ACTION_VOICE_COMMAND
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    // API 30+: startAssistantActivity is the proper method
                    // for launching activities from a VoiceInteractionSession
                    startAssistantActivity(intent)
                    Log.d(TAG, "startAssistantActivity dispatched (API 30+)")
                } else {
                    // API 23-29: use startVoiceActivity
                    startVoiceActivity(intent)
                    Log.d(TAG, "startVoiceActivity dispatched (API <30)")
                }
            } catch (e: Exception) {
                Log.e(TAG, "Assistant/Voice activity launch failed, trying startActivity", e)
                try {
                    ctx.startActivity(intent)
                    Log.d(TAG, "Fallback startActivity dispatched")
                } catch (e2: Exception) {
                    Log.e(TAG, "All launch methods failed", e2)
                }
            }

            // Finish the session - the activity handles everything from here
            finish()
        }

        override fun onHandleAssist(
            data: Bundle?,
            structure: android.app.assist.AssistStructure?,
            content: android.app.assist.AssistContent?
        ) {
            Log.d(TAG, "onHandleAssist called")
        }
    }

    companion object {
        private const val TAG = "AgentUI.VISS"
    }
}
