#!/usr/bin/env python
import logging
import subprocess
from typing import Optional

import click
import watchgod
from rich.logging import RichHandler

FORMAT = "%(message)s"
logging.basicConfig(
    level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]
)
log = logging.getLogger("rich")


@click.command()
@click.option("--loop", "-L", is_flag=True)
@click.option("--cmd", type=str, default=None)
@click.argument("path", default=".")
def main(loop: bool, cmd: Optional[str], path: str):
    log.info("Weasel Watching %s (loop=%s)", path, loop)
    for change in watchgod.watch(path):
        mod_files = [f for _, f in change]
        log.info("Modified: %s", ', '.join(mod_files))
        if cmd:
            log.info("Running: %s", cmd)
            subprocess.run(cmd.split())
        if not loop:
            return


if __name__ == "__main__":
    main()
