# Copyright (c) 2025 Patrick Motsch
# All rights reserved.

import json
import logging
from typing import Any, Dict

from modules.datamodels.datamodelChat import ActionDocument, ActionResult
from ..helpers.pathparse import parse_team_and_list

logger = logging.getLogger(__name__)


async def list_tasks(self, parameters: Dict[str, Any]) -> ActionResult:
    connection_reference = parameters.get("connectionReference")
    path_query = (parameters.get("pathQuery") or parameters.get("path") or "").strip()
    if not connection_reference:
        return ActionResult.isFailure(error="connectionReference is required")
    if not path_query:
        return ActionResult.isFailure(error="path (virtual path to a list) is required, e.g. /team/{teamId}/list/{listId}")

    conn = self.connection.get_clickup_connection(connection_reference)
    if not conn:
        return ActionResult.isFailure(error="No valid ClickUp connection")

    team_id, list_id = parse_team_and_list(path_query)
    if not list_id:
        return ActionResult.isFailure(
            error="path must be /team/{teamId}/list/{listId} (browse to a list in the ClickUp picker)"
        )

    page = int(parameters.get("page") or 0)
    include_closed = bool(parameters.get("includeClosed", False))
    data = await self.services.clickup.getTasksInList(
        list_id, page=page, include_closed=include_closed, subtasks=True
    )
    if isinstance(data, dict) and data.get("error"):
        return ActionResult.isFailure(error=str(data.get("error")) + (data.get("body") or ""))

    doc = ActionDocument(
        documentName="clickup_list_tasks.json",
        documentData=json.dumps(data, ensure_ascii=False, indent=2),
        mimeType="application/json",
        validationMetadata={
            "actionType": "clickup.listTasks",
            "teamId": team_id,
            "listId": list_id,
            "path": path_query,
        },
    )
    return ActionResult.isSuccess(documents=[doc])
