"""
Auto-generated Skill

Skill ID: add_cart_item
Version: v1

Inputs:
- `item number` (string): The unique product code for the item to be added to the cart. This maps to `cart_procode`.
- `quantity` (integer): The number of units of the product to add to the cart. This maps to `cart_item_qty`.

Outputs:
- `status` (boolean): Indicates if the operation was successful (`True`) or failed (`False`).
- `message` (string): A confirmation message on success or an error message on failure.
- `error_code` (integer, optional): An error code if the operation failed.

Side Effects:
- Modifies the user's shopping cart by adding a specified product and quantity in the Century e-member system via the `add_to_cart` MCP tool.

[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")

    item_number_raw = inputs.get('item_number')
    if item_number_raw is None or str(item_number_raw).strip() == '':
        raise ValueError("Input 'item_number' must be a non-empty string.")

    quantity_str = inputs.get('quantity')
    if quantity_str is None:
        raise ValueError("Input 'quantity' is required.")

    try:
        quantity = int(quantity_str)
        if quantity <= 0:
            raise ValueError("Input 'quantity' must be a positive integer.")
    except (ValueError, TypeError):
        raise ValueError("Input 'quantity' must be a valid positive integer.")


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

    item_number = str(inputs['item_number'])
    quantity = int(inputs['quantity']) # Already validated and castable in validate_inputs

    result: Dict[str, Any] = {
        "status": "ERROR",
        "message": "An unexpected error occurred.",
        "data": {
            "skill_id": "add_cart_item",
            "version": "v1"
        }
    }

    try:
        from agent import mcp_runtime

        # Call the add_to_cart MCP tool
        tool_arguments = {
            "cart_procode": item_number,
            "cart_item_qty": quantity
        }
        
        mcp_response = mcp_runtime.execute_tool(
            server_name="remote_service",
            tool_name="add_to_cart",
            arguments=tool_arguments
        )

        # Handle the response based on the API Response Envelope Format
        error_data = mcp_response.get("error", {})
        error_status = error_data.get("status")
        error_msg = error_data.get("msg")
        error_code = error_data.get("code")

        if error_status is False:
            result["status"] = "SUCCESS"
            result["message"] = "successfully add item to cart"
            result["output"] = result["message"] # For UI display
        else:
            result["status"] = "FAILED"
            result["message"] = f"Failed to add item to cart. Error: {error_msg}"
            if error_code is not None:
                result["message"] += f" (Code: {error_code})"
                result["data"]["error_code"] = error_code
            result["output"] = result["message"] # For UI display

    except ValueError as ve:
        result["status"] = "ERROR"
        result["message"] = str(ve)
    except RuntimeError as re:
        result["status"] = "ERROR"
        result["message"] = str(re)
    except Exception as e:
        result["status"] = "ERROR"
        result["message"] = f"An unexpected error occurred: {str(e)}"

    return result