# 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_task_id

logger = logging.getLogger(__name__)


async def update_task(self, parameters: Dict[str, Any]) -> ActionResult:
    connection_reference = parameters.get("connectionReference")
    task_id = (parameters.get("taskId") or "").strip()
    path_hint = (parameters.get("path") or "").strip()
    if not connection_reference:
        return ActionResult.isFailure(error="connectionReference is required")
    if not task_id and path_hint:
        task_id = parse_task_id(path_hint) or ""
    if not task_id:
        return ActionResult.isFailure(error="taskId is required")

    raw_update = parameters.get("taskUpdate") or parameters.get("taskJson") or parameters.get("body")
    if raw_update is None or raw_update == "":
        return ActionResult.isFailure(error="taskUpdate (JSON object) is required — add update fields or advanced JSON")
    if isinstance(raw_update, str):
        try:
            body = json.loads(raw_update)
        except json.JSONDecodeError as e:
            return ActionResult.isFailure(error=f"taskUpdate must be valid JSON: {e}")
    elif isinstance(raw_update, dict):
        body = raw_update
    else:
        return ActionResult.isFailure(error="taskUpdate must be a JSON string or object")

    if not isinstance(body, dict):
        return ActionResult.isFailure(error="taskUpdate JSON must be an object")
    if not body:
        return ActionResult.isFailure(error="taskUpdate is empty — set at least one field to update")

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

    data = await self.services.clickup.updateTask(task_id, body)
    if isinstance(data, dict) and data.get("error"):
        return ActionResult.isFailure(error=str(data.get("error")) + (data.get("body") or ""))

    doc = ActionDocument(
        documentName=f"clickup_task_{task_id}_updated.json",
        documentData=json.dumps(data, ensure_ascii=False, indent=2),
        mimeType="application/json",
        validationMetadata={"actionType": "clickup.updateTask", "taskId": task_id},
    )
    return ActionResult.isSuccess(documents=[doc])
