# #region AssistantToolDeploy [C:3] [TYPE Module] [SEMANTICS assistant, tool, git, deploy]
# @BRIEF Handler for the "deploy_dashboard" tool — deploy dashboard to target environment.
# @LAYER API
# @RELATION DEPENDS_ON -> [AssistantToolRegistry]
# @RELATION DEPENDS_ON -> [TaskManager]

from __future__ import annotations

from typing import Any

from fastapi import HTTPException
from sqlalchemy.orm import Session

from src.core.config_manager import ConfigManager
from src.core.logger import belief_scope, logger
from src.core.task_manager import TaskManager
from src.schemas.auth import User

from ._resolvers import _resolve_dashboard_id_entity, _resolve_env_id
from ._schemas import AssistantAction
from ._tool_registry import _check_any_permission, assistant_tool


# #region handle_deploy_dashboard [C:3] [TYPE Function]
@assistant_tool(
    operation="deploy_dashboard",
    domain="git",
    description="Deploy dashboard (id/slug/title) to target environment",
    required_entities=["environment"],
    optional_entities=["dashboard_id", "dashboard_ref"],
    risk_level="guarded",
    requires_confirmation=False,
    permission_checks=[("plugin:git", "EXECUTE")],
)
@belief_scope("deploy_dashboard")
async def handle_deploy_dashboard(
    intent: dict[str, Any],
    current_user: User,
    task_manager: TaskManager,
    config_manager: ConfigManager,
    db: Session,
) -> tuple[str, str | None, list[AssistantAction]]:
    """Deploy dashboard to target environment."""
    _check_any_permission(current_user, [("plugin:git", "EXECUTE")])
    entities = intent.get("entities", {})
    env_token = entities.get("environment")
    env_id = _resolve_env_id(env_token, config_manager)
    dashboard_id = _resolve_dashboard_id_entity(
        entities, config_manager, env_hint=env_token
    )
    if not dashboard_id or not env_id:
        raise HTTPException(
            status_code=422, detail="Missing dashboard_id/dashboard_ref or environment"
        )
    task = await task_manager.create_task(
        plugin_id="git-integration",
        params={
            "operation": "deploy",
            "dashboard_id": dashboard_id,
            "environment_id": env_id,
        },
        user_id=current_user.id,
    )
    return (
        f"Деплой запущен. task_id={task.id}",
        task.id,
        [
            AssistantAction(type="open_task", label="Open Task", target=task.id),
            AssistantAction(
                type="open_reports", label="Open Reports", target="/reports"
            ),
        ],
    )


# #endregion handle_deploy_dashboard
# #endregion AssistantToolDeploy
