# 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_fields(self, parameters: Dict[str, Any]) -> ActionResult:
    """Return ClickUp custom / built-in field definitions for a list (GET /list/{id}/field)."""
    connection_reference = parameters.get("connectionReference")
    path_query = (parameters.get("pathQuery") or parameters.get("path") or "").strip()
    list_id_param = (parameters.get("listId") or "").strip()

    if not connection_reference:
        return ActionResult.isFailure(error="connectionReference is required")

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

    list_id = list_id_param
    team_id = ""
    if not list_id:
        if not path_query:
            return ActionResult.isFailure(
                error="Provide listId or pathQuery like /team/{teamId}/list/{listId}"
            )
        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} (same as list picker / data source path)"
            )

    data = await self.services.clickup.getListFields(list_id)
    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_fields.json",
        documentData=json.dumps(data, ensure_ascii=False, indent=2),
        mimeType="application/json",
        validationMetadata={
            "actionType": "clickup.listFields",
            "teamId": team_id,
            "listId": list_id,
            "path": path_query or f"/list/{list_id}",
        },
    )
    return ActionResult.isSuccess(documents=[doc])
