import logging
import sys
from argparse import ArgumentParser
from pathlib import Path

from .check_snippets import check_formatting, check_output
from .config import AnkiConfig, DirectoryConfig, get_anki_config, get_directory_config
from .repository import AnkiRepository, DirectoryRepository, Repository

parser = ArgumentParser()
parser.add_argument("-v", "--verbose", action="store_true", help="Enable debug logging.")
parser.add_argument("--anki", "-a", action="store_true", help="Check anki instead of a directory.")
mode = parser.add_mutually_exclusive_group()
mode.add_argument("-c", "--check", action="store_const", const="check", dest="mode", help="Check and report failures (default).")
mode.add_argument(
    "-i",
    "--interactive",
    action="store_const",
    const="interactive",
    dest="mode",
    help="Prompt user to fix, ignore in future, or leave as is.",
)
mode.add_argument("-f", "--fix", action="store_const", const="fix", dest="mode", help="Automatically fix fixable failures.")
parser.set_defaults(mode="check")
parser.add_argument("command", choices=["output", "format"], help="Command to run.")
parser.add_argument("target", help="Directory or anki tag of the questions to check.")


def app() -> int:
    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig()
        logging.getLogger("snippet_checker").setLevel(logging.DEBUG)

    repository: Repository
    config: DirectoryConfig | AnkiConfig
    if args.anki:
        config = get_anki_config()
        repository = AnkiRepository(config, args.target)
    else:
        dir = Path(args.target)
        config = get_directory_config(dir)
        repository = DirectoryRepository(config, dir)

    func = check_output if args.command == "output" else check_formatting
    return func(repository, args.mode)


if __name__ == "__main__":
    sys.exit(app())
