"""
Auto-generated Skill

Skill ID: view_cart
Version: v1

Inputs:
Not specified.

Outputs:
- Product Name (string)
- Quantity (integer)
- Price (float)

Side Effects:
None

[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


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 required for this skill, so no further validation needed.


def run(inputs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Single entrypoint for this skill.
    """
    result = {
        "status": "ERROR",  # Default to ERROR, will be updated based on logic
        "message": "An unexpected error occurred.",
        "data": {"skill_id": "view_cart", "version": "v1"}
    }

    try:
        validate_inputs(inputs)
    except ValueError as e:
        result["status"] = "ERROR"
        result["message"] = str(e)
        return result

    final_output_message = "Here is your shopping cart list."

    try:
        # Import mcp_runtime INSIDE run() as per pattern
        from agent import mcp_runtime

        # Logic: Call the 'view_cart' tool to retrieve the current shopping cart contents.
        tool_response = mcp_runtime.execute_tool(
            "remote_service",
            "view_cart",
            {}  # No arguments required for view_cart
        )

        # Defensive check for tool execution issues (e.g., network errors, malformed response before JSON parsing)
        if isinstance(tool_response, str):
            result["status"] = "FAILED"
            result["message"] = f"Failed to retrieve cart contents due to a tool execution issue: {tool_response}"
            return result

        # Check the response from the view_cart tool for API errors
        error_field = tool_response.get('error')

        if error_field:  # If 'error' field exists and is not None/empty
            if isinstance(error_field, dict) and error_field.get('status') is True:
                error_msg = error_field.get('msg', "Failed to retrieve cart contents due to an unknown API error.")
                result["status"] = "FAILED"
                result["message"] = f"Failed to view shopping cart: {error_msg}"
                return result
            elif isinstance(error_field, str):  # Handle error as a plain string if the API returns it that way
                result["status"] = "FAILED"
                result["message"] = f"Failed to view shopping cart: {error_field}"
                return result

        # Robust parsing of the data field supporting both dict and list envelopes
        data_field = tool_response.get('data')
        items_list = []
        if isinstance(data_field, list):
            items_list = data_field
        elif isinstance(data_field, dict):
            items_list = data_field.get("detail", [])

        # Prepare table headers
        table_headers = ["Product Name", "Quantity", "Price"]
        table_rows = []

        if not items_list:
            # If the cart is empty
            result["status"] = "SUCCESS"
            result["message"] = final_output_message
            result["output"] = final_output_message
            result["table"] = {
                "headers": table_headers,
                "rows": table_rows
            }
            return result

        # Populate table rows with cart item details supporting dynamic key variations
        for item in items_list:
            if not isinstance(item, dict):
                continue
            
            # Resolve product name
            product_name = item.get('cart_item_name') or item.get('ProductName') or 'N/A'
            product_name = str(product_name)
            
            # Resolve quantity
            quantity = item.get('cart_item_qty') or item.get('Quantity')
            quantity_str = str(quantity) if quantity is not None else 'N/A'

            # Resolve price
            price_raw = item.get('cart_total_price') or item.get('cart_discounted_price') or item.get('Price')
            price_processed = 'N/A'
            if price_raw is not None:
                # Remove currency symbols (e.g., '$') from displayed price values.
                price_str = str(price_raw).replace('$', '').strip()
                try:
                    price_processed = float(price_str)
                except ValueError:
                    price_processed = price_str

            table_rows.append([product_name, quantity_str, price_processed])

        # Set success status and output
        result["status"] = "SUCCESS"
        result["message"] = final_output_message
        result["output"] = final_output_message
        result["table"] = {
            "headers": table_headers,
            "rows": table_rows
        }

    except Exception as e:
        # Catch any unexpected exceptions during the process
        result["status"] = "ERROR"
        result["message"] = f"An unexpected system error occurred while viewing cart: {str(e)}"

    return result