# 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

EXTRA_ARGS = {
    "archive": {"type": "path"},
    "backup_volumes": {"type": "list", "elements": "str", "required": True},
    "docker_socket_proxy": {"type": "str"},
}


def helper(state: State, params: dict[str, Any]) -> dict[str, Any]:
    project_name: str = state.params["name"]
    archive: str | None = params.get("archive")
    backup_volumes: list[str] | None = params["backup_volumes"]
    socket_proxy: str | None = params.get("docker_socket_proxy")

    volumes: list[dict[str, Any]] = [
        {
            "type": "volume",
            "source": volume,
            "target": f"/backup/{volume}",
            "read_only": True,
        }
        for volume in (backup_volumes or [])
    ]

    environment = {
        "BACKUP_FILENAME": f"{project_name}-%Y-%m-%dT%H-%M-%S.{'{{ .Extension }}'}",
        "BACKUP_LATEST_SYMLINK": f"{project_name}-latest",
        "BACKUP_PRUNING_PREFIX": f"{project_name}-",
        "BACKUP_STOP_DURING_BACKUP_LABEL": project_name,
        # "DOCKER_HOST": f"tcp://{project_name}_{service_name}_socket_proxy:2375",
    }

    if socket_proxy:
        environment["DOCKER_HOST"] = f"tcp://{socket_proxy}:2375"
    else:
        volumes.append(
            {
                "type": "bind",
                "source": "/var/run/docker.sock",
                "target": "/var/run/docker.sock",
                "read_only": False,
            },
        )

    if archive:
        environment["BACKUP_ARCHIVE"] = "/archive"
        volumes.append(
            {
                "type": "bind",
                "source": f"{archive}/{project_name}",
                "target": "/archive",
                "bind": {"create_host_path": True},
            },
        )

    return {"environment": environment, "volumes": volumes, "networks": {"internal": {}}}