"""
Auto-generated Skill

Skill ID: check_cart
Version: v1

Inputs:
None. All necessary authentication and context are handled by the MCP server, and the underlying `view_cart` tool requires no user-provided inputs.

Outputs:
- cart_items (list of objects): A list of products currently in the user's cart. Each object within this list contains:
    - cart_procode (string): The unique product code.
    - cart_item_name (string): The name of the product.
    - cart_item_quantity (integer): The number of units of this product in the cart.
    - cart_discounted_price (number): The price of a single unit of the product after any discounts.
    - cart_total_price (number): The total price for this specific line item (quantity * discounted_price).
- total_cart_price (number): The aggregate total monetary value of all items in the shopping cart.

Side Effects:
This skill performs a read-only operation and does not modify any system state, user data, or shopping cart contents. There are no side effects.

[WARNING] GENERATED CODE — DO NOT EDIT MANUALLY

## Supported Output Types

The `run()` function should return a dict with these fields:

### Required:
- status: "SUCCESS" | "FAILED" | "ERROR"
- message: Human-readable summary

### Optional Rich Outputs (UI will render these):
- output: Plain text response
- data: Any structured data (dict)
- table: {{headers: [...], rows: [[...], [...]]}}
- file: {{name: "file.pdf", path: "/path", mime: "application/pdf", size: "1.2 MB"}}
- image: {{url: "/static/img.png", caption: "Description", alt: "Alt text"}}
- chart: {{type: "bar", title: "Title", labels: [...], datasets: [{{label: "A", data: [...]}}]}}
- actions: [{{id: "action_id", label: "Button Text", style: "primary|secondary|success|danger"}}]
"""

from typing import Dict, Any, List
# import json # Not strictly needed for this implementation, but allowed.
import agent.mcp_runtime


def validate_inputs(inputs: Dict[str, Any]) -> None:
    """
    Validate required inputs.
    Raise ValueError if invalid.
    """
    if not isinstance(inputs, dict):
        raise ValueError("inputs must be a dictionary")
    # No specific inputs are expected for this skill as per contract,
    # so no further validation of input content is needed.


def run(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Single entrypoint for this skill.
    """
    validate_inputs(inputs)

    # Initialize result structure with a default ERROR status
    result = {
        "status": "ERROR",
        "message": "An unexpected error occurred.",
        "output": "An unexpected error occurred.",
        "data": {}
    }

    try:
        # 1. Call the `view_cart` MCP tool.
        # The tool requires no parameters as per contract.
        tool_response = agent.mcp_runtime.execute_tool(
            server_name="remote_service",
            tool_name="view_cart",
            arguments={}
        )

        # 2. Process the response received from the `view_cart` tool.
        if tool_response is None:
            result["status"] = "FAILED"
            result["message"] = "Failed to retrieve cart information: Empty response from the cart service."
            result["output"] = result["message"]
            return result
        
        # Check for the common API Response Envelope Format: {"data": ..., "error": {...}}
        if "error" in tool_response and tool_response["error"].get("status") is True:
            error_msg = tool_response["error"].get("msg", "Unknown error from cart service.")
            result["status"] = "FAILED"
            result["message"] = f"Failed to retrieve cart information: {error_msg}"
            result["output"] = result["message"]
            return result
        
        # If data is missing, it means the cart is empty
        cart_data_from_tool = tool_response.get("data", {})
        if cart_data_from_tool is None:
            cart_data_from_tool = {}

        # 3. Extract the list of products from the response, mapping them to the `cart_items` output structure.
        # 4. Extract or calculate the `total_cart_price` from the cart data.
        # Assumptions from Skill Contract: The tool's `data` directly contains 'cart_items' and 'total_cart_price'.

        extracted_cart_items: List[Dict[str, Any]] = cart_data_from_tool.get("detail", [])
        extracted_total_cart_price: float = float(tool_response.get("metadata", {}).get("total_harga", 0.0))

        if not isinstance(extracted_cart_items, list):
            result["status"] = "ERROR"
            result["message"] = "Invalid data format for cart items received from the cart service."
            result["output"] = result["message"]
            return result
        
        # Format items to match the output contract's structure and types
        final_cart_items = []
        for item in extracted_cart_items:
            try:
                final_cart_items.append({
                    "cart_procode": str(item.get("cart_procode", "N/A")),
                    "cart_item_name": str(item.get("cart_item_name", "N/A")),
                    "cart_item_quantity": int(item.get("cart_item_qty", 0)),
                    "cart_discounted_price": float(item.get("cart_discounted_price", 0.0)),
                    "cart_total_price": float(item.get("cart_total_price", 0.0))
                })
            except (ValueError, TypeError) as e:
                # Handle cases where item data types are unexpected
                result["status"] = "ERROR"
                result["message"] = f"Error processing cart item data: {e}. Some item data might be malformed."
                result["output"] = result["message"]
                return result

        # 5. Construct the final output message.
        if not final_cart_items:
            message = "Your shopping cart is currently empty."
            output_text = message
            status = "SUCCESS"
        else:
            items_str_list = []
            for item in final_cart_items:
                items_str_list.append(
                    f" - {item['cart_item_name']} ({item['cart_procode']}), "
                    f"Quantity: {item['cart_item_quantity']}, "
                    f"Price per item: {item['cart_discounted_price']:.2f}, "
                    f"Total for item: {item['cart_total_price']:.2f}"
                )
            
            message = "Your shopping cart contains the following items:\n" + "\n".join(items_str_list)
            message += f"\nTotal Cart Price: {extracted_total_cart_price:.2f}"
            output_text = message
            status = "SUCCESS"
            


        result["status"] = status
        result["message"] = message
        result["output"] = output_text
        result["data"] = {
            "cart_items": final_cart_items,
            "total_cart_price": extracted_total_cart_price
        }

    except Exception as e:
        # Catch any unexpected errors during execution
        result["status"] = "ERROR"
        result["message"] = f"An unexpected error occurred while checking your cart: {str(e)}"
        result["output"] = result["message"]

    return result