# Copyright: (c) 2025, Luca Bilke <luca@bil.ke>
# MIT License (see LICENSE)

from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
    from ansible_collections.snailed.ez_docker.plugins.module_utils.models import State

DOCUMENTATION = """
traefik_middleware:
    description:
        - Configuration for traefik_middleware labels.
    type: list
    elements: dict
    suboptions:
        name:
            description:
                - Name of the middleware.
            type: string
        middleware:
            description:
                - The name of the traefik middleware to use.
            type: str
            required: true
        proxy_type:
            description:
                - Traefik proxy type.
            type: str
            choices: [http, tcp, udp]
            default: http
        settings:
            description:
                - Middleware options.
            type: dict
            required: true
"""

EXTRA_ARGS = {
    "name": {"type": "str"},
    "middleware": {"type": "str", "required": True},
    "proxy_type": {"type": "str", "default": "http"},
    "settings": {"type": "dict", "required": True},
}


def helper(state: State, service_name: str, params: dict[str, Any]) -> dict[str, Any]:
    project_name: str = state.params["name"]
    middleware: str = params["middleware"]
    settings: dict[str, str] = params["settings"]
    proxy_type: str = params["proxy_type"]
    name: str = (
        params.get("name", f"{project_name}_{service_name}_{proxy_type}_{middleware.lower()}")
    )

    prefix = f"traefik.{proxy_type}.middlewares.{name}"

    labels = {f"{prefix}.{middleware}.{key}": var for key, var in settings.items()}

    return {
        "labels": labels,
    }