"""MCP Resources — read-only, URI-based access to Cerebro data."""

import json
from cerebro_mcp.connection import execute
from cerebro_mcp.converters import task_to_dict, message_to_dict, attachment_to_dict, user_to_dict


def register_resources(mcp):

    @mcp.resource("cerebro://task/{task_id}")
    async def task_resource(task_id: str) -> str:
        """Полная информация о задаче: данные, сообщения, вложения."""
        tid = int(task_id)
        raw = await execute("task", tid)
        if not raw:
            return json.dumps({"error": f"Задача {tid} не найдена"})

        task = task_to_dict(raw)

        raw_msgs = await execute("task_messages", tid)
        task["messages"] = [message_to_dict(m) for m in (raw_msgs or [])]

        raw_atts = await execute("task_attachments", tid)
        task["attachments"] = [attachment_to_dict(a) for a in (raw_atts or []) if a[2] == 0]

        return json.dumps(task, ensure_ascii=False, default=str)

    @mcp.resource("cerebro://project/{project_id}/tree")
    async def project_tree(project_id: str) -> str:
        """Дерево задач проекта (2 уровня глубины)."""
        pid = int(project_id)
        raw = await execute("task_children", pid)
        tree = []
        for t in (raw or []):
            node = task_to_dict(t)
            sub_raw = await execute("task_children", int(node["id"]))
            node["children"] = [task_to_dict(s) for s in (sub_raw or [])]
            tree.append(node)
        return json.dumps(tree, ensure_ascii=False, default=str)

    @mcp.resource("cerebro://user/current")
    async def current_user_resource() -> str:
        """Текущий пользователь и его todo list."""
        raw = await execute("current_user")
        if not raw:
            return json.dumps({"error": "Не удалось получить пользователя"})

        user = user_to_dict(raw[0] if isinstance(raw[0], (list, tuple)) else raw)
        uid = int(user["id"])

        raw_todo = await execute("to_do_task_list", uid, False)
        user["todo_list"] = [task_to_dict(t) for t in (raw_todo or [])]

        return json.dumps(user, ensure_ascii=False, default=str)
