#!/usr/bin/env python

import logging
import subprocess

import click
from rich.logging import RichHandler
from watchgod import watch

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


@click.command()
@click.option("--once", is_flag=True, default=False, help="exit after changed once")
@click.argument("path", type=str)
@click.argument("command", type=str, nargs=-1)
def main(once, path, command):
    """CLI

    Example
    -------
    $ ifchange . -- echo changed
    $ ifchange *.md -- make
    """
    for changes in watch(path):
        log.info("MODIFIED: %s", ",".join(f for (_, f) in changes))
        proc = subprocess.run(command, capture_output=True)
        log.info("STDOUT:")
        log.info(proc.stdout.decode().rstrip())
        log.info("STDERR:")
        log.info(proc.stderr.decode().rstrip())
        if once:
            return


if __name__ == "__main__":
    main()
