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

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from ansible_collections.ssnailed.ez_compose.plugins.module_utils.service import (  # type: ignore[reportMissingTypeStubs]
    common as service,
)

if TYPE_CHECKING:
    from ansible_collections.ssnailed.ez_compose.plugins.module_utils.common import (  # type: ignore[reportMissingTypeStubs]
        State,
    )

EXTRA_ARGS = {
    "archive": {"type": "str"},
    "backup_volumes": {"type": "list", "elements": "str"},
}


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

    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,
        "BACKUP_ARCHIVE": "/archive",
        "DOCKER_HOST": f"tcp://{project_name}_{service_name}_socket_proxy:2375",
    }

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

    update = {
        "environment": environment,
        "volumes": volumes,
    }

    return service.update(params["name"], state, update)