"""
Auto-generated Skill

Skill ID: update_cart_item
Version: v1

Inputs:
- product_id: The unique identifier (product code) of the item. (required)
- new_quantity: The desired new quantity. Must be a positive integer. (required)

Outputs:
- message: A string indicating success or failure.

Side Effects:
- Modifies the user's shopping cart via the update_cart MCP tool.

[WARNING] GENERATED CODE - DO NOT EDIT MANUALLY
"""

from typing import Dict, Any


def validate_inputs(inputs: Dict[str, Any]) -> None:
    if not isinstance(inputs, dict):
        raise ValueError("inputs must be a dictionary")
    if not inputs.get("product_id"):
        raise ValueError("product_id is required")
    if not inputs.get("new_quantity"):
        raise ValueError("new_quantity is required")


def run(inputs: Dict[str, Any]) -> Dict[str, Any]:
    validate_inputs(inputs)

    product_id = str(inputs["product_id"]).strip()
    new_quantity = int(inputs["new_quantity"])

    # Call the MCP tool
    from agent import mcp_runtime
    import json

    raw_response = mcp_runtime.execute_tool(
        "remote_service",
        "update_cart",
        {
            "cart_procode": product_id,
            "cart_item_qty": new_quantity
        }
    )

    # Normalize response to dict
    if isinstance(raw_response, str):
        try:
            response = json.loads(raw_response)
        except json.JSONDecodeError:
            return {
                "status": "FAILED",
                "message": f"Failed to parse API response: {raw_response[:200]}",
                "data": {"raw": raw_response[:500]}
            }
    elif isinstance(raw_response, dict):
        response = raw_response
    else:
        return {
            "status": "FAILED",
            "message": f"Unexpected response type: {type(raw_response).__name__}",
            "data": {"raw": str(raw_response)[:500]}
        }

    # Parse the error envelope
    error = response.get("error", {})
    if isinstance(error, str):
        return {
            "status": "FAILED",
            "message": f"API Error: {error}",
            "data": {"error": error}
        }

    error_status = error.get("status", False)

    if not error_status:
        return {
            "status": "SUCCESS",
            "message": "Quantity is successfully updated.",
            "data": {"product_id": product_id, "new_quantity": new_quantity}
        }
    else:
        error_msg = error.get("msg", "Unknown error")
        return {
            "status": "FAILED",
            "message": f"Failed to update quantity. Reason: {error_msg}",
            "data": {"product_id": product_id, "error": error_msg}
        }
