import argparse
import json
import logging
import sys
from typing import Callable, TYPE_CHECKING, Any, Dict

from app import app, mirror_sites
from app.lists.bridgelines import bridgelines
from app.lists.mirror_mapping import mirror_mapping

if TYPE_CHECKING:
    _SubparserType = argparse._SubParsersAction[argparse.ArgumentParser]
else:
    _SubparserType = Any

lists: Dict[str, Callable[[], Any]] = {
    "mirror_mapping": mirror_mapping,
    "bc2": mirror_sites,
    "bridgelines": bridgelines,
}


def dump(list_f: Callable[[], Any]) -> None:
    json.dump(list_f(), sys.stdout, indent=2)


class ListCliHandler:
    @classmethod
    def add_subparser_to(cls, subparsers: _SubparserType) -> None:
        parser = subparsers.add_parser("list", help="list operations")
        parser.add_argument("--dump", choices=sorted(lists.keys()),
                            help="dump a list in JSON format")
        parser.set_defaults(cls=cls)

    def __init__(self, args: argparse.Namespace) -> None:
        self.args = args

    def run(self) -> None:
        with app.app_context():
            if self.args.dump:
                dump(lists[self.args.dump])
            else:
                logging.error("No action requested")
