import logging
import os

import click
from rich.logging import RichHandler

from .environment import Environment
from .environment import LOG_LEVEL_MAP
from .environment import LogLevel
from .environment import pass_env


@click.group(help="Command line tools for MakerRepo")
@click.option(
    "-l",
    "--log-level",
    type=click.Choice(
        list(map(lambda key: key.value, LOG_LEVEL_MAP.keys())), case_sensitive=False
    ),
    default=lambda: os.environ.get("LOG_LEVEL", "INFO"),
)
@click.option(
    "--log-format",
    type=str,
    default="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    help="logging format (only used when rich log is disabled)",
)
@click.option(
    "--disable-rich-log",
    is_flag=True,
    help="disable rich log handler",
)
@click.version_option(prog_name="mr", package_name="mr")
@pass_env
def cli(
    env: Environment,
    log_level: str,
    log_format: str,
    disable_rich_log: bool,
):
    env.log_level = LogLevel(log_level)

    if disable_rich_log:
        logging.basicConfig(
            level=LOG_LEVEL_MAP[env.log_level],
            format=log_format,
            force=True,
        )
    else:
        FORMAT = "%(message)s"
        logging.basicConfig(
            level=LOG_LEVEL_MAP[env.log_level],
            format=FORMAT,
            datefmt="[%X]",
            handlers=[RichHandler()],
            force=True,
        )
