import argparse
import json
from pathlib import Path


class ActionConfig:

    def __init__(self, validator=None):
        self.validator = validator

    def __call__(self, file_or_string):
        path = Path(file_or_string)
        try:
            if path.exists():
                with path.open() as f:
                    config = json.load(f)
            else:
                config = json.loads(file_or_string)
        except json.JSONDecodeError as exc:
            raise argparse.ArgumentTypeError(f"Could not parse {file_or_string}\n{exc}")

        if self.validator:
            try:
                self.validator(config)
            except Exception as exc:
                raise argparse.ArgumentTypeError(f"Invalid action config:\n{exc}")

        return config

    @classmethod
    def add_to_parser(cls, parser, help="Config for action", validator=None):
        parser.add_argument(
            "--config",
            required=True,
            help=help,
            type=cls(validator),
        )


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    ActionConfig.add_to_parser(parser)
    print(parser.parse_args())