# #region AssistantToolLlmDocumentation [C:3] [TYPE Module] [SEMANTICS assistant, tool, llm, documentation]
# @BRIEF Handler for the "run_llm_documentation" tool — generate dataset documentation via LLM.
# @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_env_id, _resolve_provider_id
from ._schemas import AssistantAction
from ._tool_registry import _check_any_permission, assistant_tool


# #region handle_run_llm_documentation [C:3] [TYPE Function]
@assistant_tool(
    operation="run_llm_documentation",
    domain="llm",
    description="Generate dataset documentation via LLM",
    required_entities=["dataset_id"],
    optional_entities=["environment", "provider"],
    risk_level="guarded",
    requires_confirmation=False,
    permission_checks=[("plugin:llm_documentation", "EXECUTE")],
)
@belief_scope("run_llm_documentation")
async def handle_run_llm_documentation(
    intent: dict[str, Any],
    current_user: User,
    task_manager: TaskManager,
    config_manager: ConfigManager,
    db: Session,
) -> tuple[str, str | None, list[AssistantAction]]:
    """Generate dataset documentation via LLM."""
    _check_any_permission(current_user, [("plugin:llm_documentation", "EXECUTE")])
    entities = intent.get("entities", {})
    dataset_id = entities.get("dataset_id")
    env_id = _resolve_env_id(entities.get("environment"), config_manager)
    provider_id = _resolve_provider_id(
        entities.get("provider"),
        db,
        config_manager=config_manager,
        task_key="documentation",
    )
    if not dataset_id or not env_id or (not provider_id):
        raise HTTPException(
            status_code=400, detail="Missing dataset_id/environment/provider"
        )
    task = await task_manager.create_task(
        plugin_id="llm_documentation",
        params={
            "dataset_id": str(dataset_id),
            "environment_id": env_id,
            "provider_id": provider_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_run_llm_documentation
# #endregion AssistantToolLlmDocumentation
