"""RAG scope tool."""

from __future__ import annotations

from fabledassistant.services.tools._registry import tool


@tool(
    name="set_rag_scope",
    description="Change the RAG scope for this conversation. Use project_id=<int> to scope to a project, project_id=null to scope to orphan notes only, project_id=-1 for all notes.",
    parameters={
        "project_id": {"type": ["integer", "null"], "description": "Project ID to scope to, null for orphan-only, -1 for all notes"},
    },
    required=["project_id"],
)
async def set_rag_scope_tool(*, user_id, arguments, conv_id=None, workspace_project_id=None, **_ctx):
    if workspace_project_id is not None:
        return {"success": False, "error": "Cannot change RAG scope in workspace view"}
    if conv_id is None:
        return {"success": False, "error": "No conversation context available"}
    project_id = arguments.get("project_id")
    if project_id is not None and project_id != -1:
        from fabledassistant.services.projects import get_project
        proj = await get_project(user_id, int(project_id))
        if proj is None:
            return {"success": False, "error": "Project not found"}
        scope_label = proj.title
    elif project_id == -1:
        scope_label = "All notes"
    else:
        scope_label = "Orphan notes only"
    from fabledassistant.services.chat import update_conversation
    await update_conversation(user_id, conv_id, rag_project_id=project_id)
    return {"success": True, "type": "rag_scope_set", "scope_label": scope_label}
