import re
from typing import Any

from a2a.server.agent_execution import RequestContext
from a2a.types import (
    Message,
)

from a2a_acl.protocol_extension import A2A_ACL_PROTOCOL_URI, MIME_TAG


def check_performative_regexpr(p: str) -> bool:
    """A performative starts with a lowercase letter, and contains only lowercase letters and dash '-' character."""
    return bool(re.fullmatch(r"[a-z][a-z-]*", p))


class Performative(str):
    def __init__(self, s):
        super().__init__()
        if not check_performative_regexpr(s):
            raise ValueError("Invalid performative: " + s)


def add_performative(m: Message, p: Performative, codec: str) -> Message:
    """Add a performative to a message with the ACL extension.
    The message is modified."""
    # assert check_performative_regexpr(p)
    if m.extensions is None:
        m.extensions = []
    if m.metadata is None:
        m.metadata = {}
    md: dict[str, Any] = {
        "performative": p,
        "codec": codec,
        "mediaType": MIME_TAG,
    }
    m.extensions.append(A2A_ACL_PROTOCOL_URI)
    m.metadata[A2A_ACL_PROTOCOL_URI] = md
    return m


def extract_performative(context: RequestContext) -> Performative:
    return Performative(context.message.metadata[A2A_ACL_PROTOCOL_URI]["performative"])


def extract_codec(context: RequestContext):
    return context.message.metadata[A2A_ACL_PROTOCOL_URI]["codec"]
