from pathlib import Path
import sys
import argparse
from loguru import logger

from gitchat import __version__
from gitchat.core import add_user, Chat

def main():
    parser = argparse.ArgumentParser(description="GitChat cli app")
    subparsers = parser.add_subparsers(dest="command", help="Available commands")

    conf_parser = subparsers.add_parser(
        "config", aliases=["cfg"], help="Configure git repo for chatting"
    )
    conf_parser.add_argument("--username", "-u", dest="username", help="Username for chat")
    conf_parser.add_argument("--repo", "-r", dest="repo", help="Path to clonned git repo")

    chat_parser = subparsers.add_parser(
        "chat", aliases=["ch"], help="Start chatting"
    )
    chat_parser.add_argument("--username", "-u", dest="username", help="Username for chat")
    chat_parser.add_argument("--repo", "-r", dest="repo", help="Path to clonned git repo")
    chat_parser.add_argument(
        "--delay", "-d", dest="delay", default=1.0, type=float, help="Delay between new messages checks"
    )

    subparsers.add_parser("version", aliases=["v"], help="Get project version")

    args = parser.parse_args()

    

    if args.command in ["config", "cfg"]:
        if not args.username:
            logger.error("Please, provide username via -u flag!")
            exit(-1)
        if not args.repo:
            logger.error("Please, specify repo path!")
            exit(-1)
        handle_config(args)
    elif args.command in ["chat", "ch"]:
        if not args.username:
            logger.error("Please, provide username via -u flag!")
            exit(-1)
        if not args.repo:
            logger.error("Please, specify repo path!")
            exit(-1)
        handle_chat(args)
    elif args.command in ["version", "v"]:
        print(f"Current version is `{__version__}`")
    else:
        parser.print_help()
        sys.exit(1)


def handle_config(args):
    logger.debug(f"Initialization for username `{args.username}` ...")
    if not (Path(args.repo) / ".git").exists():
        logger.error(f"Can not find git repo in `{args.repo}` - ensure that you clonned it!")
        exit(-1)
    # Adding user to repo
    try:
        add_user(username=args.username, cwd=args.repo)
    except Exception as e:
        logger.error(f"Failed to register new user in repo: {e}")
        exit(-1)
    logger.success(f"User `{args.username}` successfully added to repo")


def handle_chat(args):
    logger.debug(f"Starting chat for `{args.username}` ...")
    chat = Chat(username=args.username, delay=args.delay, cwd=args.repo)
    chat.start()

if __name__ == "__main__":
    main()
