# #region AssistantToolCreateBranch [C:3] [TYPE Module] [SEMANTICS assistant, tool, git, branch]
# @BRIEF Handler for the "create_branch" tool — create git branch for a dashboard.
# @LAYER API
# @RELATION DEPENDS_ON -> [AssistantToolRegistry]
# @RELATION DEPENDS_ON -> [GitService]

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
from ._schemas import AssistantAction
from ._tool_registry import _check_any_permission, assistant_tool

from ._dispatch import _get_git_service


# #region handle_create_branch [C:3] [TYPE Function]
@assistant_tool(
    operation="create_branch",
    domain="git",
    description="Create git branch for dashboard by id/slug/title",
    required_entities=["branch_name"],
    optional_entities=["dashboard_id", "dashboard_ref"],
    risk_level="guarded",
    requires_confirmation=False,
    permission_checks=[("plugin:git", "EXECUTE")],
)
@belief_scope("create_branch")
async def handle_create_branch(
    intent: dict[str, Any],
    current_user: User,
    task_manager: TaskManager,
    config_manager: ConfigManager,
    db: Session,
) -> tuple[str, str | None, list[AssistantAction]]:
    """Create git branch for dashboard by id/slug/title."""
    _check_any_permission(current_user, [("plugin:git", "EXECUTE")])
    entities = intent.get("entities", {})
    dashboard_id = _resolve_dashboard_id_entity(entities, config_manager)
    branch_name = entities.get("branch_name")
    if not dashboard_id or not branch_name:
        raise HTTPException(
            status_code=422, detail="Missing dashboard_id/dashboard_ref or branch_name"
        )
    _get_git_service().create_branch(dashboard_id, branch_name, "main")
    return (f"Ветка `{branch_name}` создана для дашборда {dashboard_id}.", None, [])


# #endregion handle_create_branch
# #endregion AssistantToolCreateBranch
