"""Content block type definitions for rich content in messages."""

from __future__ import annotations

from typing import Any


# Known block types and their expected schema
BLOCK_TYPES: dict[str, dict[str, Any]] = {
    "text": {
        "description": "Plain text fallback",
        "fields": {"text": "str"},
    },
    "markdown": {
        "description": "Markdown formatted text",
        "fields": {"markdown": "str"},
    },
    "html": {
        "description": "Sanitized HTML content",
        "fields": {"html": "str"},
    },
    "image": {
        "description": "Image attachment",
        "fields": {"url": "str", "alt": "str", "width": "int?"},
    },
    "audio": {
        "description": "Audio file",
        "fields": {"url": "str", "duration": "int?", "waveform": "list?"},
    },
    "video": {
        "description": "Video file",
        "fields": {"url": "str", "duration": "int?", "thumbnail": "str?"},
    },
    "file": {
        "description": "Generic file attachment",
        "fields": {"url": "str", "name": "str", "size": "int?"},
    },
    "action_card": {
        "description": "Interactive card with buttons",
        "fields": {
            "title": "str",
            "body": "str",
            "actions": "list[dict]",  # [{label, action, type}]
        },
    },
    "contact_card": {
        "description": "Contact reference card",
        "fields": {"contact_id": "str", "name": "str"},
    },
    "miniapp": {
        "description": "Embedded mini-app",
        "fields": {"app_id": "str", "config": "dict?"},
    },
}


def validate_block(block_type: str, block_data: dict[str, Any]) -> bool:
    """Validate that a block has the required fields for its type.

    Returns True if valid, False otherwise.
    Unknown block types are allowed (forward-compatible) but logged.
    """
    if block_type not in BLOCK_TYPES:
        # Unknown types are allowed — forward compatible
        return True

    required_fields = BLOCK_TYPES[block_type].get("fields", {})
    for field_name, field_type in required_fields.items():
        if field_type.endswith("?"):
            continue  # Optional field
        if field_name not in block_data:
            return False

    return True


def list_block_types() -> list[dict[str, Any]]:
    """List all known block types for frontend reference."""
    return [
        {"block_type": bt, "description": info["description"], "fields": info["fields"]}
        for bt, info in BLOCK_TYPES.items()
    ]
