"""Bridge adapter for MobileAgent v3.5 integration.

Provides a high-level async interface for TaskEngine to drive the
MobileAgent perception-action loop via DeviceRuntime.
"""

from __future__ import annotations

import asyncio
import logging
from dataclasses import dataclass
from typing import Any, Awaitable, Callable

from ..runtime.base import DeviceRuntime
from .mobile_agent.agent import StepResult, run_mobile_agent

logger = logging.getLogger(__name__)


@dataclass
class AgentStep:
    index: int
    action: str
    reasoning: str
    screenshot_b64: str | None = None
    status: str = "running"


StepCallback = Callable[[AgentStep], Awaitable[None]]


class MobileAgentBridge:
    """Wraps MobileAgent v3.5 for integration with TaskEngine.

    Usage::

        bridge = MobileAgentBridge(
            runtime=my_runtime,
            vlm_api_key="...",
            vlm_base_url="https://openrouter.ai/api/v1",
            vlm_model="bytedance/ui-tars-1.5-7b",
        )
        steps = await bridge.run("打开设置")
    """

    def __init__(
        self,
        runtime: DeviceRuntime,
        vlm_api_key: str = "",
        vlm_base_url: str = "",
        vlm_model: str = "",
        on_step: StepCallback | None = None,
        max_steps: int = 30,
    ) -> None:
        self._runtime = runtime
        self._vlm_api_key = vlm_api_key
        self._vlm_base_url = vlm_base_url
        self._vlm_model = vlm_model
        self._on_step = on_step
        self._max_steps = max_steps
        self._running = False
        self._cancel_event = asyncio.Event()

    @property
    def running(self) -> bool:
        return self._running

    async def run(self, instruction: str) -> list[AgentStep]:
        """Execute an AI automation task via MobileAgent v3.5."""
        self._running = True
        self._cancel_event.clear()
        steps: list[AgentStep] = []

        try:
            async for result in run_mobile_agent(
                runtime=self._runtime,
                instruction=instruction,
                api_key=self._vlm_api_key,
                base_url=self._vlm_base_url,
                model=self._vlm_model,
                max_steps=self._max_steps,
            ):
                if self._cancel_event.is_set():
                    break

                step = AgentStep(
                    index=result.index,
                    action=result.action,
                    reasoning=result.reasoning,
                    status=result.status,
                )
                steps.append(step)

                if self._on_step:
                    await self._on_step(step)

        except Exception as exc:
            logger.exception("MobileAgent execution error")
            steps.append(AgentStep(
                index=len(steps),
                action="error",
                reasoning=str(exc),
                status="error",
            ))
        finally:
            self._running = False

        return steps

    def cancel(self) -> None:
        self._cancel_event.set()
