import json
from collections.abc import Mapping, Iterable
from textwrap import indent

def summarize_variable(var, name="var"):
    """
    Summarize a variable and its contents.
    Args:
        var: The variable to summarize.
        name: The name of the variable.
    Returns:
        A string summarizing the variable and its contents.
    """
    def get_class_path(obj):
        klass = obj.__class__
        mod = klass.__module__
        if mod == 'builtins':
            return klass.__name__
        return f"{mod}.{klass.__name__}"

    def summarize_mapping(mapping, depth=1, max_depth=2):
        if depth > max_depth:
            return indent("... (max depth reached)", " " * (depth * 4))
        lines = []
        for k, v in mapping.items():
            line = f"{repr(k)}:"
            if isinstance(v, Mapping):
                nested = summarize_mapping(v, depth + 1, max_depth)
                line += "\n" + indent(nested, " " * 4)
            elif isinstance(v, list) and v and isinstance(v[0], Mapping):
                line += f" [list of dicts, length {len(v)}]"
                # Optionally show structure of first item
                nested = summarize_mapping(v[0], depth + 1, max_depth)
                line += "\n" + indent(nested, " " * 4)
            elif isinstance(v, list):
                line += f" [list of {type(v[0]).__name__ if v else 'unknown'}, length {len(v)}]"
            else:
                line += f" {type(v).__name__}"
            lines.append(line)
        return "\n".join(lines)

    def safe_len(obj):
        try:
            return len(obj)
        except Exception:
            return "N/A"

    def is_json_serializable(obj):
        try:
            json.dumps(obj)
            return True
        except Exception:
            return False

    type_name = type(var).__name__
    class_path = get_class_path(var)
    var_len = safe_len(var)

    output = []
    output.append("============== VAR SUMMARY ================")
    output.append(f"Name: {name}")
    output.append(f"Type: {type_name}")
    output.append(f"Class: {class_path}")
    output.append(f"Length: {var_len}")

    if isinstance(var, Mapping):
        output.append("Key structure:")
        output.append(summarize_mapping(var))
    elif isinstance(var, list) and var and isinstance(var[0], Mapping):
        output.append(f"List of dicts structure (showing first item):")
        output.append(summarize_mapping(var[0]))
    elif isinstance(var, Iterable) and not isinstance(var, (str, bytes)):
        output.append("Iterable of:")
        output.append(f"  {type(var[0]).__name__}" if var else "  unknown")
    else:
        output.append("Contents:")
        preview = repr(var)
        if len(preview) > 500:
            preview = preview[:500] + "... (truncated)"
        output.append(indent(preview, "  "))

    output.append("===========================================")
    print("\n".join(output))
