import argparse
import itertools
import logging
import logging.config
from pathlib import Path
from typing import List

from . import __url__, __author__, __version__, config, graph
from .slpp import slpp as lua

logger = logging.getLogger(__name__)


class CLI:
    def __init__(self) -> None:
        super().__init__()

    def parse_args(self):
        parser = argparse.ArgumentParser(
            prog="bb",
            description=f"BigBrother v{__version__} by {__author__}.",
            epilog=f"For more information, see <{__url__}>."
        )
        parser.add_argument(
            dest="saved_variables",
            type=lambda s: Path(s),
            help="Path to WTF/Account/<ACCOUNT>/SavedVariables/BigBrother.lua",
        )
        parser.add_argument(
            "-v", "--verbose",
            action="count",
            default=0,
            help="Increase verbosity level. Can be used multiple times."
        )
        return parser.parse_args()

    def select_raid(self, saved_variables: Path) -> List[dict]:
        text = saved_variables.read_text(encoding="utf8")
        db = lua.decode(f"{{{text}}}")  # double-{} since slpp requires all variables to be part of a lua table
        raids = []
        for zone, encounters in itertools.groupby(db["BigBrotherDB"], key=lambda x: (x["zone"], x["date"][:10])):
            raids.append(list(encounters))
        raids.reverse()  # ensure latest raid is first
        for i, raid in enumerate(raids, start=1):
            print(f"{i:3} {raid[0]['date']} {raid[0]['zone']}")
        choice = int(input("Raid: "))
        return raids[choice-1]

    def prompt_delete_saved_variables(self, saved_variables: Path) -> None:
        if input("Delete saved variables BigBrother.lua? [y/N] ").lower() == "y":
            saved_variables.unlink()
            logger.info("%s deleted.", saved_variables)

    def run(self) -> None:
        args = self.parse_args()
        logging.config.dictConfig(config.get_logging_config(level=("WARNING", "INFO", "DEBUG")[min(args.verbose, 2)]))
        logger.debug("Args: %s", args)
        raid = self.select_raid(args.saved_variables)
        graph.graph(raid)
        self.prompt_delete_saved_variables(args.saved_variables)


def main():
    cli = CLI()
    cli.run()


if __name__ == '__main__':
    main()