# 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


from typing import Any


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

    prefix = f"traefik.{proxy_type}.services.{service_name}"

    labels: dict[str, Any] = {}

    if port:
        labels[f"{prefix}.loadbalancer.server.port"] = str(port)

    update = {
        "labels": labels,
    }

    return service.update(state, update)


def main():
    extra_args = {
        "proxy_type": {"type": "str"},
        "service_name": {"type": "string"},
        "port": {"type": "int"},
    }
    label.run(extra_args, helper)


if __name__ == "__main__":
    main()