"""Tags, hashtags, and checklists."""

from cerebro_mcp.connection import execute
from cerebro_mcp.converters import task_tag_to_dict, check_to_dict


def register(mcp):

    @mcp.tool()
    async def get_task_tags(task_id: str) -> str:
        """Получить значения тегов (кастомных полей) на задаче."""
        try:
            tid = int(task_id)
            raw = await execute("task_tags", tid)
            tags = [task_tag_to_dict(t) for t in (raw or [])]
            return str(tags)
        except Exception as e:
            return f"Ошибка: {e}"

    @mcp.tool()
    async def get_task_hashtags(task_id: str) -> str:
        """Получить хештеги задачи."""
        try:
            tid = int(task_id)
            raw = await execute("task_hashtags", tid)
            return str(raw or [])
        except Exception as e:
            return f"Ошибка: {e}"

    @mcp.tool()
    async def set_task_hashtags(task_id: str, hashtags: list[str]) -> str:
        """Установить хештеги на задачу. Каждый тег — одно слово без пробелов."""
        try:
            tid = int(task_id)
            result = await execute("task_set_hashtags", tid, set(hashtags))
            return str({"changed_ids": [str(x) for x in result] if result else []})
        except Exception as e:
            return f"Ошибка: {e}"

    @mcp.tool()
    async def get_task_checks(task_id: str) -> str:
        """Получить чеклист задачи (пункты и их значения 0/1)."""
        try:
            tid = int(task_id)
            # pycerebro bug: task_checks uses to_array() but SQL expects scalar bigint
            raw = await execute("execute", 'select * from "taskChecksColumn"(?::bigint)', tid)
            checks = [check_to_dict(c) for c in (raw or [])]
            return str(checks)
        except Exception as e:
            return f"Ошибка: {e}"

    @mcp.tool()
    async def set_task_check_value(task_id: str, check_id: str, value: bool) -> str:
        """Установить значение пункта чеклиста (True/False)."""
        try:
            tid = int(task_id)
            cid = int(check_id)
            await execute("task_set_checks_value", tid, cid, 1 if value else 0)
            return str({"ok": True})
        except Exception as e:
            return f"Ошибка: {e}"

    @mcp.tool()
    async def set_tag_value(task_id: str, tag_id: str, tag_type: str, value: str) -> str:
        """Установить значение тега на задаче.
        tag_type: 'int', 'float', 'string', 'enum', 'user'.
        Для enum: value = enum_id (int). Для user: value = user_id (int).
        Получите tag_id и tag_type через get_project_tags()."""
        try:
            tid = int(task_id)
            tgid = int(tag_id)
            if tag_type == "int":
                result = await execute("task_set_tag_int", tid, tgid, int(value))
            elif tag_type == "float":
                result = await execute("task_set_tag_float", tid, tgid, float(value))
            elif tag_type == "string":
                result = await execute("task_set_tag_string", tid, tgid, value)
            elif tag_type in ("enum", "multi_enum"):
                result = await execute("task_set_tag_enum", tid, int(value), True)
            elif tag_type in ("user", "multi_user"):
                result = await execute("task_set_tag_user", tid, tgid, int(value), True)
            else:
                return f"Неизвестный tag_type: {tag_type}"
            return str({"changed_ids": [str(x) for x in result] if result else []})
        except Exception as e:
            return f"Ошибка: {e}"
