"""
Auto-generated Skill

Skill ID: foo
Version: v1

Inputs:
- x

Outputs:
- y

Side Effects:
- z

[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
import json


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


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

    # --- Skill Logic ---
    # The skill is designed to sum a list of numbers provided in the input 'x'.
    x_raw = inputs.get('x')

    # Handle cases where input is None, an empty string, or an empty list.
    if not x_raw:
        return {
            "status": "SUCCESS",
            "message": "Operasi berhasil diselesaikan",
            "output": "Tidak ada input yang diberikan, totalnya adalah 0.",
            "data": {"y": 0}
        }

    # Normalize input into a list of items to parse.
    # The input can be a list, a JSON string of a list, a comma-separated string, or a single number.
    items_to_parse = []
    if isinstance(x_raw, list):
        items_to_parse = x_raw
    elif isinstance(x_raw, str):
        try:
            # Attempt to parse as a JSON string first (e.g., "[1, 2, \"3\"]")
            parsed_json = json.loads(x_raw)
            if isinstance(parsed_json, list):
                items_to_parse = parsed_json
            else:
                # Handle cases where the string is a valid JSON but not a list (e.g., "123" or "\"text\"")
                items_to_parse = [parsed_json]
        except json.JSONDecodeError:
            # If not a valid JSON, assume it's a comma-separated string (e.g., "1, 2, 3")
            items_to_parse = [item.strip() for item in x_raw.split(',')]
    else:
        # Handle single numbers or other types
        items_to_parse = [x_raw]

    if not items_to_parse:
         return {
            "status": "SUCCESS",
            "message": "Operasi berhasil diselesaikan",
            "output": "Input tidak berisi item yang dapat diproses, totalnya adalah 0.",
            "data": {"y": 0}
        }

    total_sum = 0.0
    for item in items_to_parse:
        try:
            # Treat empty or whitespace-only strings in the list as 0
            if isinstance(item, str) and item.strip() == "":
                # This handles cases like [1, "", 2] or "1,,2"
                continue
            
            # Convert item to float and add to sum
            total_sum += float(item)
        except (ValueError, TypeError) as e:
            error_message = f"Input tidak valid: '{item}'. Semua item harus berupa nilai numerik."
            return {
                "status": "ERROR",
                "message": error_message,
                "output": f"Kesalahan: Tidak dapat memproses input '{item}'. Pastikan semua nilai adalah angka.",
                "data": {"error": "InvalidInput", "input_field": "x", "invalid_value": item}
            }

    # Construct the successful response
    output_message = "Operation completed successfully" # From contract
    rich_output_message = f"Jumlah dari semua angka adalah {total_sum}."

    result = {
        "status": "SUCCESS",
        "message": output_message,
        "output": rich_output_message,
        "data": {"y": total_sum}  # As per 'Outputs' in the contract
    }

    return result