from typing import Literal

from phone_copilot.agent import Agent
from phone_copilot.device import detect_device
from phone_copilot.model_client import ModelClient

__all__ = ['run_task']


def run_task(
    task: str,
    *,
    base_url: str,
    model: str,
    api_key: str = '',
    device: str | None = None,
    language: Literal['zh', 'en'] = 'zh',
    max_steps: int = 100,
    ccf: int = 1000,
    adb_keyboard: bool = False,
) -> Agent:
    """Run a task on a connected device using the agent.

    Args:
        base_url (str): The base URL of the model API.
        model (str): The name of the model to use.
        api_key (str, optional): The API key for authentication. Defaults to ''.
        device (str | None, optional): The device ID to select. If None, auto-detects the first connected device. Defaults to None.
        language (Literal['zh', 'en'], optional): The language for system prompts. Defaults to 'zh'.
        max_steps (int, optional): The maximum number of steps the agent can take. Defaults to 100.
        ccf (int, optional): The context compression factor for the agent. Defaults to 1000.
        adb_keyboard (bool, optional): Whether to enable ADB keyboard input method. Defaults to False.

    Returns:
        agent: An instance of the Agent class after running the task.
    """  # noqa: E501
    device = detect_device(device=device)

    if adb_keyboard and getattr(device, 'install_and_set_adb_keyboard', None):
        device.install_and_set_adb_keyboard()

    model_client = ModelClient(base_url=base_url, model=model, api_key=api_key)

    agent = Agent(
        device=device,
        language=language,
        max_steps=max_steps,
        model_client=model_client,
        ccf=ccf,
    )

    agent.run(task=task)

    return agent
