"""Реализация Key-value хранилища"""

from argparse import ArgumentParser
from json import dumps, loads
from os import path, remove
from tempfile import gettempdir
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Dict, List, Optional

STORAGE_PATH: "str" = path.join(gettempdir(), "storage.data")


def get_data() -> "Dict[str,List[str]]":
    """Получение всех данных из хранилища"""

    result: "Dict[str,List[str]]" = {}

    if path.exists(STORAGE_PATH):
        with open(STORAGE_PATH, "r", encoding="utf-8") as des:
            raw_data: "str" = des.read()

            if raw_data:
                result = loads(raw_data)

    return result


def put(key: "str", value: "str") -> "None":
    """Запись значения по ключу"""

    data: "Dict[str,List[str]]" = get_data()

    if key in data:
        data[key].append(value)

    else:
        data[key] = [
            value,
        ]

    with open(STORAGE_PATH, "w", encoding="utf-8") as des:
        des.write(dumps(data))


def get(key) -> "Optional[str]":
    """Получение данных по ключу"""

    data: "Dict[str,List[str]]" = get_data()

    return None if not key in data else ", ".join(data.get(key))


if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument("--key", help="Key")
    parser.add_argument("--val", help="Value")
    parser.add_argument("--clear", action="store_true", help="Clear")

    args = parser.parse_args()

    if args.clear:
        remove(STORAGE_PATH)

    elif args.key and args.val:
        put(args.key, args.val)

    elif args.key:
        print(get(args.key))

    else:
        print("Wrong command")
