# This is the entry point for the AI terminal assistant program.  It outlines the main program flow and calls other files at a high level.

# Package execution
from . import apiHandler
from . import userInterface
from . import historyManager
from . import chatBot
from . import configHandler
from . import riskAssessment

import argparse
import sys

def parse_args():
    """Parse command line arguments for gptautocli"""
    parser = argparse.ArgumentParser(
        description="gptautocli - Provides a conversational interface to the terminal, allowing users to run commands and perform tasks using natural language.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
    gptautocli                            # Start a new chat with default settings
    gptautocli -m your-model-name         # Start a new chat with the model of your choice (e.g. gpt-4, gpt-3.5-turbo, etc.)
    gptautocli --risk-level 3             # Set the risk tolerance to 3
    gptautocli -h                         # Display this help message
    gptautocli -v                         # Display the version number
        """) 
    
    parser.add_argument("-v", "--version", action="store_true", help="Display the version number")
    parser.add_argument("-m", "--model", type=str, help="Specify the model to use for the chat")
    parser.add_argument("-r", "--risk-level", type=int, help="Specify the risk tolerance level for commands generated by the AI")
    return parser.parse_args()
                                    

def main():
    """Main program flow"""
    # parse command line arguments
    args = parse_args()
    if args.version:
        # Read the version from the VERSION file
        with open("VERSION") as version_file:
            version = version_file.read().strip()
        print(f"gptautocli version {version}")
        sys.exit()
    model_name = "gpt-4o"

    if args.model:
        model_name = args.model
    risk_level = -1
    if args.risk_level is not None:
        risk_level = args.risk_level
    # initialize the UI
    user_interface = userInterface.UserInterface()
    # initialize config
    configHandler.ConfigHandler(user_interface)
    # initialize the API handler
    api_handler = apiHandler.ApiHandler(user_interface)
    # risk assessment tool
    riskAssessmentTool = riskAssessment.RiskAssessment(user_interface, api_handler, risk_level)
    risk_level = riskAssessmentTool.risk_tolerance
    # welcome the user
    user_interface.welcome(model_name, risk_level)
    # initialize the history manager
    history_manager = historyManager.HistoryManager()
    # load chat history
    all_chat_history = history_manager.load_chat_history()
    # choose either a new chat or a previous chat
    history = user_interface.choose_chat_history(all_chat_history)
    
    # initialize the agent manager
    agent_manager = chatBot.ChatBot(user_interface, api_handler, riskAssessmentTool, model_name, history)

    # begin the conversation loop
    agent_manager.conversation_loop()
    # close the shell
    agent_manager.shell.close()
    # once the conversation is over, save the chat history to a new file
    history_manager.save_chat_history(agent_manager.conversation_history)


if __name__ == '__main__':
    try:
        # attempt to run the main program
        main()
    except Exception as e:
        print("An error occurred: ", e)
        input("Press enter to exit.")
