#ifndef GASPARD_TERMINAL_LANGUAGE_HPP
#define GASPARD_TERMINAL_LANGUAGE_HPP
#include <stdint.h>
#include <deque>
#include <map>
#include <string>
#include <vector>

namespace terminal
{
    typedef std::vector<std::string> Arguments;

    class Output
    {
    public:
        virtual ~Output()
        {
        }

        virtual void print(const std::string& text) = 0;
        virtual void clear()                        = 0;
    };

    // The language never calls native syscalls. A backend supplies filesystem
    // and asynchronous process services, allowing deterministic host tests.
    class Backend
    {
    public:
        virtual ~Backend()
        {
        }

        virtual int directory(const std::string& path)                          = 0;
        virtual int changeDirectory(const std::string& path) { return path == "/" ? 0 : directory(path); }
        virtual int list(const std::string& path)                               = 0;
        virtual int launch(const std::string& path, const Arguments& arguments) = 0;
    };
    class Engine;
    typedef int (*Handler)(Engine&, const Arguments&);

    struct Command
    {
        std::string name, usage, description;
        Handler     handler;

        Command(const std::string& n, const std::string& u, const std::string& d, Handler h)
            : name(n), usage(u), description(d), handler(h)
        {
        }
    };

    struct HistoryEntry
    {
        unsigned    id;
        std::string line;
    };

    // LANGUAGE CONTRACT:
    // - A line contains commands separated by ';', except inside quotes.
    // - Space/tab separate arguments. Single quotes are literal; double quotes
    //   expand $NAME and ${NAME}. Backslash quotes the following character.
    // - Expansion produces ONE argument: no field splitting, globbing, pipes,
    //   command substitution or implicit execution. Undefined variables fail.
    // - '#' starts a comment at a token boundary, outside quotes.
    // - Command names ignore ASCII case; variable names are case-sensitive.
    // - A failed command cancels its remaining batch. $STATUS is the previous
    //   command status; $PWD is the current directory. Both are read-only.
    // - Commands are registered descriptors, not branches in the parser.
    // - tick executes at most one command. Repeat is queued, never recursive.
    class Engine
    {
        friend class EnvironmentFile;
        struct Job
        {
            Arguments commands;
            unsigned  index, remaining;

            Job(const Arguments& lines, unsigned count)
                : commands(lines), index(0), remaining(count)
            {
            }
        };

        Backend&                           backend_;
        Output&                            output_;
        std::vector<Command>               commands_;
        std::map<std::string, std::string> variables_;
        std::vector<HistoryEntry>          history_;
        std::deque<Job>                    jobs_;
        std::string                        cwd_, previous_;
        unsigned                           nextHistory_, budget_;
        int                                status_;
        bool                               exit_;
        Engine(const Engine&);
        Engine& operator=(const Engine&);
        bool    tokenize(const std::string& line, Arguments& arguments, std::string& error) const;

    public:
        Engine(Backend& backend, Output& output);
        bool                             registerCommand(const Command& command);
        const std::vector<Command>&      commands() const;
        const std::vector<HistoryEntry>& history() const;
        bool                             submit(const std::string& line);
        void                             tick();
        bool                             busy() const;
        bool                             exiting() const;
        void                             exit();
        int                              status() const;
        const std::string&               cwd() const;
        std::string                      path(const std::string& input) const;
        int                              changeDirectory(const std::string& input);
        bool variable(const std::string& name, std::string& value) const;
        bool set(const std::string& name, const std::string& value);
        bool unset(const std::string& name);
        const std::map<std::string, std::string>& variables() const;
        bool     repeat(unsigned count, const std::string& command);
        Backend& backend();
        Output&  output();
        void     line(const std::string& text);
    };

    // Parses variable definitions only; never executes commands from a file.
    class EnvironmentFile
    {
    public:
        bool parse(Engine& engine, const std::string& contents, std::string& error) const;
    };

    bool splitCommands(const std::string& line, Arguments& commands, std::string& error);
    bool variableName(const std::string& name);
    void registerCoreCommands(Engine& engine);
    void registerFileCommands(Engine& engine);
    void registerProcessCommands(Engine& engine);
    void registerDefaultCommands(Engine& engine);
}  // namespace terminal
#endif
