#include <iostream>
#include <limits>
#include <map>

#include "util.h"
#include "argument_set.h"
#include "argv.h"
#include "argument.h"
#include "command.h"
#include "error.h"
#include "file.h"
#include "katom.h"
#include "log.h"
#include "show.h"

int main(int argc, char* argv[])
{
    try {
        set_verbose_level(argc, argv);

        Argv args {};
        args.req("input",    "Klammertext input text", "'text'");
        args.flag("type",    "Show katom types in subscript");
        args.flag("index",   "Show the list index of the katom");
        args.flag("text",    "Show text katoms with selected attributes");
        args.flag("replaced","Show replaced katoms");
        args.flag("ignored", "Show ignored katoms");
        args.flag("all",     "Show all katoms, including katoms replaced or ignored"); // in brackets with selected attributes");
        args.flag("spans",   "Show the beginning and ending katoms of spans");
        args.flag("rewrite", "Show applied rewrite rules");
        args.flag("args",    "Show how the text would be parsed as klammer arguments");
        args.opt("pos",      "Number of positional arguments to parse for --args", "count", "-1", R"(([^\s]+))");
        args.flag("read",    "Process read: @read <filename> @");
        args.flag("eval",    "Process eval: @eval <expression> @");
        args.flag("cond",    "Process cond: @cond <condition> | <if-true> | <if_false> @");
        args.flag("nonascii","Process encoded characters (not ASCII): ^... or ^...^");
        args.flag("literal", "Process literal: ^'...'^");
        args.flag("ignore",  "Process ignored: #, ##, #[...]#");
        args.flag("ws",      "Process whitespace: #-, #+, #/");
        args.flag("klammer", "Process klammer definitions: @@<name> ... @@");
        args.flag("process", "Process all");
        args.opt("v",        "'verbosity'", "degree", "0", "'verbosity'");

        if (show_usage(argc, argv)) {
            args.usage(file_basename(argv[0]));
            exit(1);
        }
        auto p = [&](const std::string& name) { return args.get(name) == "true"; };

        args.parse(argc, argv);
        verbose_level = args.as_int("v");
        if (verbose_level > 0) {
            args.describe();
        }

        if (p("rewrite")) {
            show_rewrite_rules = true;
        }

        Machine machine;
        std::string input = args.as_string("input");
        std::string command = construct_command_pathname(argv[0]);
        katom_list katoms {};
        if (p("process")) {
            katoms = machine.process(input, command);
        } else {
            katoms = machine.process(
                //args.as_string("input"), construct_command_pathname(argv[0]),
                input, command,
                p("nonascii"), p("literal"), p("ignore"), p("ws"), p("klammer"),
                p("eval"), p("cond"), p("read"));
        }
        if (p("spans")) {
            describe_spans(katoms);
        } else {
            if (p("ignored")) std::cout << kignored;
            if (p("type")) std::cout << ktype;
            if (p("index")) std::cout << kindex;
            if (p("text")) std::cout << kall;
            if (p("all")) std::cout << kall << kreplaced << kignored;
            if (p("replaced")) std::cout << kreplaced;
            std::cout << katoms << "\n";
        }

        if (p("args")) {
            int req_count = args.as_int("pos");
            bool limit_req = req_count != -1;
            if (req_count == -1) {
                req_count = std::numeric_limits<int>::max();
            }
            auto [required, optional, rest] =
                argument_split(katoms.begin(), katoms.end(), req_count);
            std::stringstream ss {};
            ss << "required";
            if (limit_req) {
                ss << " (" << req_count << ")";
            }
            ss << ":";
            std::string req_label = ss.str();
            auto label_width = req_label.size() + 2;
            std::cout << std::setfill(' ')
                      << std::right << std::setw(label_width) << req_label << "  " << required << "\n"
                      << std::right << std::setw(label_width) << "optional:" << "  " << optional << "\n";
            if (limit_req) {
                std::cout << std::right << std::setw(label_width) << "rest:" << "  " << rest << "\n";
            }
        }
    }
    catch (Error& e) {
        std::string advice = "";
        if (e.m_type == "target")
            advice = "To include the Standard Klammer Set, add flag \"--sks\".";
        e.print_message(advice);
    }
    std::cout << black;
    return 0;
}

