/*
 * Hermes Node Android
 * Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package net.nexlab.hermesnodeandroid.capabilities

import android.content.Context
import net.nexlab.hermesnodeandroid.CapabilityResult
import org.json.JSONObject

class AndroidBrowserControl(private val context: Context) {
    private val computer = AndroidComputerControl(context)
    private val observe = AndroidDesktopObserve(context)

    fun capabilityInfo(): JSONObject = JSONObject()
        .put("available", true)
        .put("backend", "android-intent-plus-compat")
        .put("supports_launch", true)
        .put("supports_navigation", true)
        .put("supports_visual_capture", true)
        .put("notes", "Android browser_control maps stable subsets to system browser intents plus desktop-observe screenshot fallback")

    fun handle(action: String?, params: JSONObject): CapabilityResult = when (action) {
        "launch" -> computer.handle("open_url", JSONObject().put("url", params.optString("url", defaultUrl(params))))
        "navigate" -> computer.handle("open_url", JSONObject().put("url", params.optString("url", defaultUrl(params))))
        "open_url" -> computer.handle("open_url", JSONObject().put("url", params.optString("url", defaultUrl(params))))
        "screenshot" -> observe.handle("screenshot", params)
        "evaluate", "click", "fill", "type", "press", "snapshot", "cdp", "playwright" ->
            CapabilityResult.unsupported("Android browser_control does not provide DOM/CDP automation; supported actions are launch, navigate/open_url, and screenshot")
        else -> CapabilityResult.unsupported("Unknown browser_control action: $action")
    }

    private fun defaultUrl(params: JSONObject): String = params.optString("target", params.optString("url", "https://www.google.com"))
}
