"""Browser-native Runner commands shared by the hosted Python CLI."""
from __future__ import annotations

import time
import webbrowser

from . import api


def _intent(out):
    return (out or {}).get("intent") or {}


def _wait(intent_id, seconds=8):
    deadline = time.monotonic() + max(0, seconds)
    intent = {}
    while time.monotonic() < deadline:
        intent = api.get(f"/api/v1/browser/intents/{intent_id}").get("intent") or {}
        if intent.get("status") not in ("pending", "claimed"):
            return intent
        time.sleep(0.35)
    return intent


def open_scope(
    scope,
    *,
    disposition="reuse",
    activation="focus",
    device=None,
    dedupe_key=None,
    fallback=True,
):
    out = api.post(
        "/api/v1/browser/intents",
        {
            "kind": "navigate",
            "scope": scope,
            "disposition": disposition,
            "activation": activation,
            "device": device,
            "dedupe_key": dedupe_key,
        },
    )
    intent = _intent(out)
    delivery = intent.get("delivery") or {}
    if delivery.get("available") or not fallback:
        return out
    # Do not leave a latent intent that would duplicate this cold open when the
    # extension wakes later.
    if intent.get("id"):
        api.delete(f"/api/v1/browser/intents/{intent['id']}")
    url = out.get("open_url")
    if url:
        webbrowser.open(url)
    out["intent"] = {**intent, "status": "cold_url"}
    out["delivery"] = {"mode": "system_browser", "available": bool(url)}
    return out


def notify_scope(
    scope,
    *,
    title=None,
    message=None,
    disposition="reuse",
    device=None,
    dedupe_key=None,
):
    return api.post(
        "/api/v1/browser/intents",
        {
            "kind": "notify",
            "scope": scope,
            "title": title,
            "message": message,
            "disposition": disposition,
            "device": device,
            "dedupe_key": dedupe_key,
        },
    )


def tabs(*, device=None, wait_seconds=8):
    out = api.post(
        "/api/v1/browser/intents",
        {
            "kind": "inspect",
            "device": device,
            "ttl_seconds": max(10, int(wait_seconds) + 5),
        },
    )
    intent = _intent(out)
    if not (intent.get("delivery") or {}).get("available"):
        return {
            "tabs": [],
            "intent": intent,
            "error": "no paired Runner Chrome device is currently active",
        }
    settled = _wait(intent["id"], wait_seconds)
    return {
        "tabs": (settled.get("result") or {}).get("tabs", []),
        "intent": settled,
    }


def devices():
    return api.get("/api/v1/browser/devices")
