"""Trusted plan-bound autonomous execution — Agent First, User Last (P2 §8 Stage 5)."""

from __future__ import annotations

from typing import Any

from .action_session_policy import (
    WEB_PLAN_BOUND_AUTO_COMMAND_TYPES,
    command_always_requires_confirm,
    plan_step_matches_session,
    session_confirmation_allows_skip,
)
from .goal_authorized_execution import (
    GOAL_AUTHORIZED_AUTO_COMMAND_TYPES,
    goal_authorization_skip_confirmation,
)
from .production_policy import is_publish_submit_action

# Minimum permission preset for full in-plan autonomy (expert = owner Trusted profile).
TRUSTED_AUTONOMOUS_PROFILE: str = "expert"

TRUSTED_AUTONOMOUS_PROFILES = frozenset({"full", "expert"})

TRUSTED_PLAN_BOUND_AUTO_COMMAND_TYPES = GOAL_AUTHORIZED_AUTO_COMMAND_TYPES


def is_trusted_autonomous_session(
    session_scope: dict[str, Any],
    *,
    trust_state: str = "",
    permission_preset: str = "",
) -> bool:
    if str(trust_state or "").strip().lower() != "trusted":
        return False
    if not str(session_scope.get("bound_to_plan_id") or "").strip():
        return False
    preset = str(permission_preset or session_scope.get("permission_preset") or "").strip().lower()
    return preset in TRUSTED_AUTONOMOUS_PROFILES


def trusted_autonomous_skip_confirmation(
    *,
    command_type: str,
    payload: dict[str, Any] | None,
    session_scope: dict[str, Any],
    trust_state: str,
    confirmation_mode: str,
    plan_bound: bool,
) -> bool:
    """True when trusted + plan-bound + grants cover step and action is not Stop Zone."""
    if command_always_requires_confirm(command_type, payload):
        return False
    if is_publish_submit_action(command_type, payload):
        return False
    if not plan_bound:
        return False
    if str(command_type or "").strip().lower() not in TRUSTED_PLAN_BOUND_AUTO_COMMAND_TYPES:
        return False
    if not is_trusted_autonomous_session(session_scope, trust_state=trust_state):
        return False
    step_plan_id = str((payload or {}).get("plan_id") or "").strip()
    if not plan_step_matches_session(session_scope, plan_id=step_plan_id):
        return False
    return session_confirmation_allows_skip(confirmation_mode, plan_bound=True)
