#!/usr/bin/env python
from pathlib import Path
from ursus.utils import import_class, load_config, get_files_in_path
from ursus.config import config
from watchdog.observers import Observer
import argparse
import coloredlogs
import time


def build(watch_for_changes: bool = False):
    """Runs ursus and builds a static website

    Args:
        watch_for_changes (bool, optional): Keep running, and rebuild when content or templates change
    """
    generator = import_class(config.generator)()
    generator.generate()

    if watch_for_changes:
        observer = Observer()

        for path in generator.get_watched_paths():
            observer.schedule(generator.get_observer_event_handler(), path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        finally:
            observer.stop()
            observer.join()


def lint():
    """Lints the content for errors"""
    linters = [import_class(linter_path)() for linter_path in config.linters]

    for file_path in sorted(get_files_in_path(config.content_path)):
        for linter in linters:
            linter.lint(file_path, fix_errors=False)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        prog='ursus',
        description='Static site generator',
        epilog='Made with ❤️ in Berlin'
    )
    parser.add_argument(
        'action',
        nargs='?',
        default='build',
        choices=('build', 'lint'),
        help='Action to perform.'
    )
    parser.add_argument(
        '-c', '--config',
        help="Path to a Python config file or module. The `config` variable will be imported from that file."
    )
    parser.add_argument(
        '-w', '--watch', action='store_true',
        help="Regenerate files when <content_path> and <templates_path> change."
    )
    parser.add_argument(
        '-f', '--fast', action='store_true',
        help="Fast rebuilds. Prefer faster page rebuilds to completeness. Related pages might not be reloaded."
    )
    args = parser.parse_args()

    if args.config:
        load_config(args.config)
    elif Path('./ursus_config.py').exists():
        load_config('ursus_config.py')

    if args.fast:
        config.fast_rebuilds = True

    coloredlogs.install(**config.logging)

    if args.action == 'build':
        build(args.watch)
    elif args.action == 'lint':
        lint()
