#!/usr/bin/env python3

import _add_root_dir_to_path

from logctl._config import load_config
from logctl._configure_logbroker import configure_logbroker
from logctl._configure_logfeller import configure_logfeller
from logctl._configure_push_client import configure_push_client
from lib.logbroker import Logbroker, DryRunLogbroker
from lib.logfeller import Logfeller, DryRunLogfeller
from lib.push_client import PushClient, DryRunPushClient
from lib.repository import (
    ArcRepository as Repository,
    DryRunArcRepository as DryRunRepository,
    temporary_arc_repository as temporary_repository,
    find_repository_root,
)
from lib.fs import temporary_chdir
from pathlib import Path
import argparse


def main():
    args = parse_args()
    if args.operation == "apply":
        app_path = Path(args.path).resolve()
        app_relative_path = app_path.relative_to(find_repository_root(app_path))
        logbroker_cls, logfeller_cls, push_client_cls, repo_cls, auto_confirm = args.traits
        logbroker = logbroker_cls()
        logfeller = logfeller_cls()
        push_client = push_client_cls()
        config = load_config(app_path / "service.yml")
        with temporary_repository(Path.home(), repo_cls) as repo, temporary_chdir(repo.path()):
            repo.create_branch()
            configure_logfeller(logfeller, repo, config, auto_confirm)
            configure_push_client(push_client, repo, config, app_relative_path, auto_confirm)
            configure_logbroker(logbroker, config, auto_confirm)
            if repo.has_commits():
                repo.create_pr("Update logs delivery configuration for {}".format(config["app"]))


def parse_args():
    parser = argparse.ArgumentParser()
    subparser = parser.add_subparsers(dest="operation", help="sub-command help")
    apply_parser = subparser.add_parser("apply")
    apply_parser.add_argument("path", help="path to application dir")
    apply_parser.add_argument(
        "--dry-run",
        action="store_const",
        dest="traits",
        const=(DryRunLogbroker, DryRunLogfeller, DryRunPushClient, DryRunRepository, True),
    )
    apply_parser.set_defaults(traits=(Logbroker, Logfeller, PushClient, Repository, False))
    return parser.parse_args()


if __name__ == "__main__":
    main()
