"""Auto-execute eligibility for trusted Avatar owners with active grants."""

from __future__ import annotations

from typing import Any

from ..status_resolver import is_policy_trusted

from .avatar_chat import AvatarSuggestedAction

# Stop-zone command types — never auto-start without explicit user confirmation.
_STOP_ZONE_COMMANDS = frozenset(
    {
        "social_post_publish",
        "browser_click_publish",
        "email_send",
        "mass_mail_send",
        "public_accusation_post",
        "apply_update",
        "folder_wipe",
        "service_remove",
    }
)

_UI_CAP_BY_COMMAND: dict[str, str | None] = {
    "mouse_move_relative": "mouse_control",
    "keyboard_type_text": "keyboard_control",
    "browser_open_url": "network_control",
    "open_url": "network_control",
    "open_document_edit": "application_control",
    "write_file_in_workspace": "file_access",
    "read_file_in_workspace": "file_access",
    "empty_trash": "file_access",
    "get_diagnostics": None,
    "open_folder": "file_access",
    "application_launch": "application_control",
    "check_update": None,
    "social_post_draft": "application_control",
    "capture_screenshot": "screen_vision",
    "verify_screen_contains_text": "screen_vision",
    "describe_active_window": "screen_vision",
    "list_files_in_folder": "file_access",
    "generate_content": "network_control",
    "verify_workspace_file": "file_access",
}


def _is_trusted(trust_state: str) -> bool:
    return is_policy_trusted(trust_state)


def _grant_covers_command(command_type: str, ui_caps: dict[str, bool]) -> bool:
    ui_cap = _UI_CAP_BY_COMMAND.get(str(command_type or "").strip().lower())
    if ui_cap is None:
        return True
    return bool(ui_caps.get(ui_cap, False))


def should_auto_execute_action(
    action: AvatarSuggestedAction,
    *,
    trust_state: str,
    ui_caps: dict[str, bool],
) -> bool:
    """Trusted owner with grant may run low-risk single actions without pressing Execute."""
    if not _is_trusted(trust_state):
        return False
    command_type = str(action.command_type or "").strip().lower()
    if command_type in _STOP_ZONE_COMMANDS:
        return False
    if action.required_ui_capability and not ui_caps.get(action.required_ui_capability, False):
        return False
    return _grant_covers_command(command_type, ui_caps)


def should_auto_execute_plan(
    plan: dict[str, Any],
    *,
    trust_state: str,
    ui_caps: dict[str, bool],
) -> bool:
    """Auto-start plan when every step is in-scope and none are stop-zone actions."""
    if str(plan.get("execution_mode") or "").strip().lower() == "plan_only":
        return False
    if not _is_trusted(trust_state):
        return False
    steps = plan.get("steps") or []
    if not isinstance(steps, list) or not steps:
        return False
    for raw_step in steps:
        if not isinstance(raw_step, dict):
            return False
        command_type = str(raw_step.get("command_type") or "").strip().lower()
        if not command_type or command_type in _STOP_ZONE_COMMANDS:
            return False
        if not _grant_covers_command(command_type, ui_caps):
            return False
    return True


def plan_auto_start_delay_ms(plan: dict[str, Any]) -> int:
    """Brief pause before auto-start so the owner sees the plan card."""
    steps = plan.get("steps") or []
    if isinstance(steps, list) and len(steps) >= 2:
        return 2000
    return 500
