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

from __future__ import annotations

from typing import TYPE_CHECKING

import ansible_collections.snailed.ez_compose.plugins.module_utils.label.common as label
import ansible_collections.snailed.ez_compose.plugins.module_utils.service.common as service

if TYPE_CHECKING:
    from ansible_collections.snailed.ez_compose.plugins.module_utils.common import State


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

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

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

    update = {
        "labels": labels,
    }

    return service.update(state, update)


def main():
    extra_args = {
        "proxy_type": {"type": "str"},
        "middleware_name": {"type": "string"},
        "middleware": {"type": "str", "required": True},
        "settings": {"type": "list", "required": True},
    }
    label.run(extra_args, helper)


if __name__ == "__main__":
    main()