package com.agentui.desktop

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.util.Log
import android.widget.Toast
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit

class VoiceCommandActivity : Activity() {

    companion object {
        private const val TAG = "AgentUI.Voice"
        private const val SPEECH_REQUEST_CODE = 1001
    }

    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "VoiceCommandActivity created, action=${intent?.action}")

        when (intent?.action) {
            // Launched via share intent
            Intent.ACTION_SEND -> {
                if (intent.type == "text/plain") {
                    val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT)
                    if (!sharedText.isNullOrBlank()) {
                        sendTranscript(sharedText, "share-intent")
                        return
                    }
                }
            }
            // Launched as assist app or voice command
            Intent.ACTION_ASSIST,
            Intent.ACTION_VOICE_COMMAND,
            "android.intent.action.VOICE_COMMAND" -> {
                Log.d(TAG, "Launched as assistant, starting speech recognition")
                startSpeechRecognition()
                return
            }
        }

        // Default fallback: start speech recognition
        startSpeechRecognition()
    }

    private fun startSpeechRecognition() {
        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
            putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
            putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-HN")
            putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "es-HN")
            putExtra(RecognizerIntent.EXTRA_PROMPT, "Agent UI - Decí tu comando")
        }
        try {
            startActivityForResult(intent, SPEECH_REQUEST_CODE)
        } catch (e: Exception) {
            Log.e(TAG, "Speech recognition not available", e)
            Toast.makeText(this, "Speech recognition not available", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == SPEECH_REQUEST_CODE) {
            if (resultCode == RESULT_OK && data != null) {
                val results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
                val text = results?.firstOrNull()
                if (!text.isNullOrBlank()) {
                    Log.d(TAG, "Speech recognized: $text")
                    sendTranscript(text, "voice-assistant")
                    return
                }
            }
            Log.d(TAG, "Speech recognition cancelled or no result")
            finish()
        }
    }

    /**
     * Sends the transcribed text to the server's /api/voice-transcript endpoint,
     * then launches MainActivity with the target terminal so the floating
     * transcript debug opens on the correct session.
     */
    private fun sendTranscript(text: String, source: String) {
        Thread {
            try {
                val apiBase = ServerConfig.apiBaseUrl(this)

                if (apiBase == null) {
                    Log.w(TAG, "No server configured, cannot send transcript")
                    showToastAndFinish("No server configured")
                    return@Thread
                }

                val timestamp = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
                    .format(Date())

                val body = JSONObject().apply {
                    put("text", text)
                    put("timestamp", timestamp)
                    put("source", source)
                }.toString().toRequestBody("application/json".toMediaType())

                val request = Request.Builder()
                    .url("$apiBase/voice-transcript")
                    .post(body)
                    .build()

                Log.d(TAG, "Sending transcript to $apiBase/voice-transcript")

                val response = client.newCall(request).execute()
                val responseBody = response.body?.string() ?: ""

                if (response.isSuccessful) {
                    Log.d(TAG, "Server response: $responseBody")

                    // Parse the ephemeralSessionId from the response
                    val json = JSONObject(responseBody)
                    val terminal = json.optString("ephemeralSessionId", "")

                    // Launch MainActivity with the terminal info to open floating transcript
                    openMainWithTerminal(terminal, text)
                } else {
                    Log.e(TAG, "Server error ${response.code}: $responseBody")
                    showToastAndFinish("Server error: ${response.code}")
                }

            } catch (e: Exception) {
                Log.e(TAG, "Failed to send transcript", e)
                showToastAndFinish("Error: ${e.message?.take(50)}")
            }
        }.start()
    }

    /**
     * Opens MainActivity and tells the WebView to open FloatingTranscriptDebug
     * on the terminal that received the voice command.
     */
    private fun openMainWithTerminal(terminal: String, text: String) {
        runOnUiThread {
            Toast.makeText(this, "Sent: ${text.take(50)}", Toast.LENGTH_SHORT).show()

            val intent = Intent(this, MainActivity::class.java).apply {
                action = "com.agentui.desktop.VOICE_TERMINAL"
                putExtra("ephemeralSessionId", terminal)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
            }
            startActivity(intent)
            finish()
        }
    }

    private fun showToastAndFinish(message: String) {
        runOnUiThread {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
            finish()
        }
    }
}
