// Copyright 2024-2025 XMOS LIMITED.
// This Software is subject to the terms of the XMOS Public Licence: Version 1.

#include "options.hpp"

using namespace std;

int main(int argc, char ** argv)
{
    if(argc == 1)
    {
        cout << "Use --help to get the list of options for this application." << endl
        << "Or use --list-commands to print the list of commands and their info." << endl;
        return 0;
    }

    uint8_t instance_id = get_instance_id(&argc, argv); // instanceID can be present anywhere on the cmd line. Get it first

    opt_t * opt = nullptr;
    int cmd_indx = 1;
    string next_cmd = argv[cmd_indx];

    if(next_cmd[0] == '-')
    {
        opt = option_lookup(next_cmd);
        if (opt->long_name == "--help")
        {
            return print_help_menu();
        }
        else if (opt->long_name == "--version")
        {
            cout << current_host_app_version << endl;
            return 0;
        }
    }

    if(next_cmd[0] == '-')
    {
        // This assumes that the next_cmd has not been reassigned
        // Hence opt holds the same option pointer
        if (opt->long_name == "--list-commands")
        {
            return print_command_list();
        }
    }

    int * device_init_info = get_device_init_info();


    Device_USB device(device_init_info);

    Command command(&device, instance_id);

    int arg_indx = cmd_indx + 1;
    next_cmd = argv[cmd_indx];

    if (next_cmd[0] != '-')
    {
        return command.do_command(next_cmd, argv, argc, arg_indx);
    }

    // Program should NEVER get to this point
    cout << "Host application behaved unexpectedly, please report this issue" << endl;
    return -1;
}
