import re

from ..conf import devicehub_settings


def build_topic(type_name, device_id, message_type="data", template=None):
    """Build an MQTT topic string."""
    if template is None:
        template = "{prefix}/{type_name}/{device_id}/{message_type}"
    return template.format(
        prefix=devicehub_settings.TOPIC_PREFIX,
        type_name=type_name.lower(),
        device_id=device_id,
        message_type=message_type,
    )


def parse_topic(topic):
    """Parse an MQTT topic into (type_name, device_id, message_type) or None."""
    prefix = re.escape(devicehub_settings.TOPIC_PREFIX)
    pattern = rf"^{prefix}/(\w+)/([^/]+)/(data|status|cmd)$"
    match = re.match(pattern, topic)
    if match:
        return match.groups()
    return None


def build_subscribe_pattern(type_name, message_type="+"):
    """Build an MQTT topic pattern with + wildcard for device_id."""
    return build_topic(type_name, "+", message_type)
