package com.autopilot

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.util.concurrent.TimeUnit

/**
 * Autopilot App v1
 *
 * Captures a website question as a String, sends it to an AI API,
 * and returns the correct option index. Includes a basic UI with a
 * 'Submit' button and a 'Correct Answer' highlight.
 */

// ---------------------------------------------------------------------------
// Data models
// ---------------------------------------------------------------------------

data class Question(
    val text: String,
    val options: List<String>
)

data class AiResponse(
    val selectedIndex: Int,
    val confidence: Double,
    val rawResponse: String
)

// ---------------------------------------------------------------------------
// AI API client
// ---------------------------------------------------------------------------

class AiApiClient(private val apiKey: String = System.getenv("AI_API_KEY") ?: "demo-key") {

    private val json = Json { ignoreUnknownKeys = true }

    /**
     * Sends the question to the AI API and returns the parsed response.
     *
     * @param question The question text and its options.
     * @return An [AiResponse] containing the selected option index.
     */
    suspend fun ask(question: Question): AiResponse = withContext(Dispatchers.IO) {
        val prompt = buildPrompt(question)
        val requestBody = """
            {
                "model": "gpt-4",
                "messages": [
                    {
                        "role": "system",
                        "content": "You are a quiz assistant. Given a multiple-choice question and its options, respond with ONLY a JSON object of the form {\"selectedIndex\": <int>, \"confidence\": <float>} where selectedIndex is the 0-based index of the correct option. Do not include any other text."
                    },
                    {
                        "role": "user",
                        "content": ${json.encodeToString(JsonPrimitive(prompt))}
                    }
                ],
                "temperature": 0.0,
                "max_tokens": 100
            }
        """.trimIndent()

        val url = URL("https://api.openai.com/v1/chat/completions")
        val connection = url.openConnection() as HttpURLConnection
        connection.requestMethod = "POST"
        connection.setRequestProperty("Content-Type", "application/json")
        connection.setRequestProperty("Authorization", "Bearer $apiKey")
        connection.doOutput = true
        connection.connectTimeout = 30_000
        connection.readTimeout = 30_000

        val responseCode = connection.responseCode
        val responseStream = if (responseCode in 200..299) {
            connection.inputStream
        } else {
            connection.errorStream
        }
        val responseBody = responseStream.bufferedReader().use { it.readText() }

        if (responseCode !in 200..299) {
            throw RuntimeException("AI API returned HTTP $responseCode: $responseBody")
        }

        val parsed = json.parseToJsonElement(responseBody)
        val choices = (parsed as JsonObject).get("choices")
            ?: throw RuntimeException("No 'choices' in AI response")
        val firstChoice = (choices as kotlinx.serialization.json.JsonArray)[0]
        val message = (firstChoice as JsonObject).get("message")
            ?: throw RuntimeException("No 'message' in choice")
        val content = (message as JsonObject).get("content")
            ?: throw RuntimeException("No 'content' in message")
        val rawContent = (content as JsonPrimitive).contentOrNull
            ?: throw RuntimeException("Content is not a string primitive")

        Log.d("AiApiClient", "Raw AI response: $rawContent")

        val trimmed = rawContent.trim()
        val startIndex = trimmed.indexOf('{')
        val endIndex = trimmed.lastIndexOf('}')
        val jsonPart = if (startIndex >= 0 && endIndex > startIndex) {
            trimmed.substring(startIndex, endIndex + 1)
        } else {
            trimmed
        }

        val parsedJson = json.parseToJsonElement(jsonPart) as JsonObject
        val selectedIndex = (parsedJson["selectedIndex"] as? JsonPrimitive)?.contentOrNull?.toIntOrNull()
            ?: throw RuntimeException("Could not parse selectedIndex from: $jsonPart")
        val confidence = (parsedJson["confidence"] as? JsonPrimitive)?.contentOrNull?.toDoubleOrNull()
            ?: 0.0

        AiResponse(
            selectedIndex = selectedIndex,
            confidence = confidence,
            rawResponse = rawContent
        )
    }

    private fun buildPrompt(question: Question): String {
        val optionsText = question.options.mapIndexed { index, option ->
            "  [$index] $option"
        }.joinToString("\n")
        return """
            Question: ${question.text}
            Options:
            $optionsText
        """.trimIndent()
    }
}

// ---------------------------------------------------------------------------
// ViewModel
// ---------------------------------------------------------------------------

class AutopilotViewModel {

    private val scope = CoroutineScope(Dispatchers.Main)

    private val _questionText = MutableStateFlow("")
    val questionText: StateFlow<String> = _questionText.asStateFlow()

    private val _options = MutableStateFlow<List<String>>(emptyList())
    val options: StateFlow<List<String>> = _options.asStateFlow()

    private val _isSubmitting = MutableStateFlow(false)
    val isSubmitting: StateFlow<Boolean> = _isSubmitting.asStateFlow()

    private val _selectedIndex = MutableStateFlow<Int?>(null)
    val selectedIndex: StateFlow<Int?> = _selectedIndex.asStateFlow()

    private val _confidence = MutableStateFlow<Double?>(null)
    val confidence: StateFlow<Double?> = _confidence.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

    private val aiClient = AiApiClient()

    fun setQuestion(text: String) {
        _questionText.update { text }
    }

    fun setOptions(options: List<String>) {
        _options.update { options }
    }

    fun submit() {
        val question = questionText.value
        val opts = options.value
        if (question.isBlank() || opts.isEmpty()) {
            _errorMessage.update { "Please enter a question and at least one option." }
            return
        }

        _isSubmitting.update { true }
        _selectedIndex.update { null }
        _confidence.update { null }
        _errorMessage.update { null }

        scope.launch {
            try {
                val q = Question(text = question, options = opts)
                val response = aiClient.ask(q)
                _selectedIndex.update { response.selectedIndex }
                _confidence.update { response.confidence }
            } catch (e: Exception) {
                Log.e("AutopilotViewModel", "Submit failed", e)
                _errorMessage.update { "Error: ${e.message}" }
            } finally {
                _isSubmitting.update { false }
            }
        }
    }

    fun reset() {
        _questionText.update { "" }
        _options.update { emptyList() }
        _selectedIndex.update { null }
        _confidence.update { null }
        _errorMessage.update { null }
    }

    fun destroy() {
        scope.cancel()
    }
}

// ---------------------------------------------------------------------------
// Activity
// ---------------------------------------------------------------------------

class AutopilotActivity : Activity() {

    private lateinit var viewModel: AutopilotViewModel
    private lateinit var questionInput: EditText
    private lateinit var optionsContainer: LinearLayout
    private lateinit var submitButton: Button
    private lateinit var resultText: TextView
    private lateinit var confidenceText: TextView
    private lateinit var errorText: TextView
    private lateinit var optionButtons: MutableList<Button>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = AutopilotViewModel()
        setContentView(buildUi())
        observeViewModel()
    }

    private fun buildUi(): View {
        val root = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(32, 32, 32, 32)
        }

        val title = TextView(this).apply {
            text = "Autopilot"
            textSize = 24f
            setPadding(0, 0, 0, 16)
        }
        root.addView(title)

        questionInput = EditText(this).apply {
            hint = "Enter the question text..."
            textSize = 16f
        }
        root.addView(questionInput)

        val optionsLabel = TextView(this).apply {
            text = "Options (one per line)"
            textSize = 14f
            setPadding(0, 16, 0, 4)
        }
        root.addView(optionsLabel)

        val optionsInput = EditText(this).apply {
            hint = "Option A\nOption B\nOption C\nOption D"
            textSize = 16f
            minLines = 4
        }
        root.addView(optionsInput)

        optionsContainer = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(0, 16, 0, 0)
        }
        root.addView(optionsContainer)

        submitButton = Button(this).apply {
            text = "Submit"
            setOnClickListener {
                val opts = optionsInput.text.toString()
                    .split("\n")
                    .map { it.trim() }
                    .filter { it.isNotEmpty() }
                viewModel.setOptions(opts)
                viewModel.submit()
            }
        }
        root.addView(submitButton)

        resultText = TextView(this).apply {
            textSize = 18f
            setPadding(0, 16, 0, 4)
        }
        root.addView(resultText)

        confidenceText = TextView(this).apply {
            textSize = 14f
            setPadding(0, 0, 0, 4)
        }
        root.addView(confidenceText)

        errorText = TextView(this).apply {
            textSize = 14f
            setPadding(0, 0, 0, 0)
        }
        root.addView(errorText)

        return root
    }

    private fun observeViewModel() {
        lifecycleScope {
            launch {
                viewModel.selectedIndex.collectLatest { index ->
                    if (index != null) {
                        highlightOption(index)
                        resultText.text = "Correct Answer: Option ${index + 1}"
                    } else {
                        clearHighlights()
                        resultText.text = ""
                    }
                }
            }
            launch {
                viewModel.confidence.collectLatest { conf ->
                    confidenceText.text = conf?.let { "Confidence: ${"%.1f".format(it * 100)}%" } ?: ""
                }
            }
            launch {
                viewModel.errorMessage.collectLatest { msg ->
                    errorText.text = msg ?: ""
                    errorText.visibility = if (msg != null) View.VISIBLE else View.GONE
                }
            }
            launch {
                viewModel.isSubmitting.collectLatest { submitting ->
                    submitButton.isEnabled = !submitting
                    submitButton.text = if (submitting) "Submitting..." else "Submit"
                }
            }
        }
    }

    private fun highlightOption(index: Int) {
        optionButtons.forEachIndexed { i, btn ->
            if (i == index) {
                btn.setBackgroundColor(0xFF4CAF50.toInt())
                btn.setTextColor(0xFFFFFFFF.toInt())
            } else {
                btn.setBackgroundColor(0xFFE0E0E0.toInt())
                btn.setTextColor(0xFF000000.toInt())
            }
        }
    }

    private fun clearHighlights() {
        optionButtons.forEach { btn ->
            btn.setBackgroundColor(0xFFE0E0E0.toInt())
            btn.setTextColor(0xFF000000.toInt())
        }
    }

    private fun lifecycleScope(block: suspend CoroutineScope.() -> Unit) {
        CoroutineScope(Dispatchers.Main).launch { block() }
    }

    override fun onDestroy() {
        super.onDestroy()
        viewModel.destroy()
    }
}
