"""UI capability grant keys, presets, and agent-capability mapping (0.2.0.1)."""

from __future__ import annotations

from typing import FrozenSet

UI_CAPABILITY_KEYS: tuple[str, ...] = (
    "file_access",
    "application_control",
    "mouse_control",
    "keyboard_control",
    "network_control",
    "software_management",
    "root_operations",
    "screen_vision",
)

UI_GRANT_PREFIX = "ui."


def ui_grant_key(ui_key: str) -> str:
    return f"{UI_GRANT_PREFIX}{str(ui_key).strip()}"


def parse_ui_grant_key(capability_key: str) -> str | None:
    key = str(capability_key or "").strip()
    if not key.startswith(UI_GRANT_PREFIX):
        return None
    ui_key = key[len(UI_GRANT_PREFIX) :]
    return ui_key if ui_key in UI_CAPABILITY_KEYS else None


def __getattr__(name: str):
    if name == "PERMISSION_PRESETS":
        from .permission_profiles import PROFILE_UI_KEYS

        return PROFILE_UI_KEYS
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


# Agent command capability → UI row required for owner execution.
AGENT_CAPABILITY_TO_UI: dict[str, str | None] = {
    "agent.status.read": None,
    "agent.diagnostics.read": None,
    "agent.logs.collect": None,
    "agent.lifecycle.restart": None,
    "agent.update.check": None,
    "agent.update.apply": "software_management",
    "agent.ui.notify": None,
    "agent.workspace.file.read": "file_access",
    "agent.workspace.file.write": "file_access",
    "agent.browser.open_url": "network_control",
    "agent.desktop.app": "application_control",
    "agent.service.restart": "software_management",
    "agent.package.install.dry_run": "software_management",
    "agent.network.diagnostics": "network_control",
    "agent.network.fetch": "network_control",
    "agent.content.summarize": "network_control",
    "agent.screen.capture": "screen_vision",
    "agent.screen.verify": "screen_vision",
}

# Plan → UI capabilities the tariff allows granting (SaaS cap).
PLAN_UI_CAPABILITY_ALLOWLIST: dict[str, FrozenSet[str]] = {
    "free": frozenset({"file_access", "network_control"}),
    "pro": frozenset(UI_CAPABILITY_KEYS),
    "business": frozenset(UI_CAPABILITY_KEYS),
    "admin": frozenset(UI_CAPABILITY_KEYS),
}

UI_CAPABILITY_RISK: dict[str, str] = {
    "file_access": "low",
    "application_control": "medium",
    "mouse_control": "high",
    "keyboard_control": "high",
    "network_control": "medium",
    "software_management": "high",
    "root_operations": "critical",
    "screen_vision": "high",
}

DEFAULT_OWNER_GRANT_TTL_SECONDS = 604800  # 7 days; renewed on each sync
