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

from __future__ import annotations

import copy

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.snailed.ez_compose.plugins.module_utils.common import (
    State,
    get_compose,
    new_state,
    write_compose,
)


def generate(state: State) -> State:
    params = state.module.params
    compose = copy.deepcopy(state.before)

    services = compose.get("services", {})

    container = services.get(params["name"], {})
    container.update(
        {
            "image": params["image"],
        }
    )

    services.update({params["name"]: container})

    return state.model_copy(update={"after": compose})


def main():
    module = AnsibleModule(
        argument_spec={
            "state": {
                "type": "str",
                "default": "present",
                "choices": ["present", "absent"],
            },
            "name": {
                "type": "str",
                "required": True,
            },
            "project_name": {
                "type": "str",
                "required": True,
            },
            "image": {
                "type": "str",
            },
            "settings": {
                "type": "dict",
                "required": True,
            },
        },
        supports_check_mode=True,
    )

    state = new_state(module)

    get_compose(state)

    generate(state)

    if module.check_mode:
        module.exit_json(**state.result)  # type: ignore[reportUnkownMemberType]

    write_compose(state)

    module.exit_json(**state.result)  # type: ignore[reportUnkownMemberType]


if __name__ == "__main__":
    main()