#include "language.hpp"
#include <cstdio>

namespace terminal
{
    bool EnvironmentFile::parse(Engine& engine, const std::string& contents,
                                std::string& error) const
    {
        error.clear();
        if (contents.size() > 65536)
        {
            error = "Environment file exceeds 65536 bytes";
            return false;
        }
        const std::map<std::string, std::string> saved = engine.variables_;
        unsigned number = 0;
        for (std::size_t begin = 0; begin < contents.size();)
        {
            ++number;
            std::size_t end = contents.find('\n', begin);
            if (end == std::string::npos) end = contents.size();
            std::string line = contents.substr(begin, end - begin);
            begin = end + 1;
            if (!line.empty() && line[line.size() - 1] == '\r')
                line.erase(line.size() - 1);
            if (number == 1 && line.compare(0, 3, "\xef\xbb\xbf") == 0)
                line.erase(0, 3);
            std::size_t first = line.find_first_not_of(" \t");
            if (first == std::string::npos || line[first] == '#') continue;
            line.erase(0, first);
            if (line.compare(0, 7, "export ") == 0) line.erase(0, 7);
            bool legacy = line.compare(0, 4, "set ") == 0;
            if (legacy) line.erase(0, 4);
            std::size_t split = legacy ? line.find_first_of(" \t") : line.find('=');
            std::string name = line.substr(0, split);
            Arguments words, commands;
            std::string detail;
            bool valid = split != std::string::npos && variableName(name)
                && splitCommands(line.substr(split + 1), commands, detail)
                && commands.size() <= 1;
            if (valid)
                valid = engine.tokenize(line.substr(split + 1), words, detail)
                    && words.size() <= 1
                    && engine.set(name, words.empty() ? "" : words[0]);
            if (!valid)
            {
                engine.variables_ = saved;
                char n[32];
                std::sprintf(n, "%u", number);
                error = std::string("Vars.com line ") + n + ": invalid variable definition";
                return false;
            }
        }
        return true;
    }

    static std::string lower(std::string text)
    {
        for (std::size_t i = 0; i < text.size(); ++i)
            if (text[i] >= 'A' && text[i] <= 'Z')
                text[i] += 'a' - 'A';
        return text;
    }

    static std::string trim(const std::string& text)
    {
        std::size_t first = text.find_first_not_of(" \t"), last = text.find_last_not_of(" \t");
        return first == std::string::npos ? "" : text.substr(first, last - first + 1);
    }

    bool variableName(const std::string& name)
    {
        if (name.empty() || name.size() > 64)
            return false;
        for (std::size_t i = 0; i < name.size(); ++i)
        {
            char c = name[i];
            if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'
                  || (i && c >= '0' && c <= '9')))
                return false;
        }
        return true;
    }

    bool splitCommands(const std::string& line, Arguments& result, std::string& error)
    {
        result.clear();
        if (line.size() > 4095)
        {
            error = "Line exceeds 4095 bytes";
            return false;
        }
        char        quote  = 0;
        bool        escape = false, boundary = true;
        std::size_t begin = 0;
        for (std::size_t i = 0; i < line.size(); ++i)
        {
            unsigned char c = static_cast<unsigned char>(line[i]);
            if ((c < 32 && c != '\t') || c == 127)
            {
                error = "Invalid control character";
                return false;
            }
            if (escape)
            {
                escape   = false;
                boundary = false;
                continue;
            }
            if (c == '\\' && quote != '\'')
            {
                escape   = true;
                boundary = false;
                continue;
            }
            if (quote)
            {
                if (c == quote)
                    quote = 0;
                continue;
            }
            if (c == '\'' || c == '"')
            {
                quote    = static_cast<char>(c);
                boundary = false;
                continue;
            }
            if (c == '#' && boundary)
            {
                std::string tail = trim(line.substr(begin, i - begin));
                if (!tail.empty())
                    result.push_back(tail);
                if (result.size() > 32)
                {
                    error = "At most 32 commands per line";
                    return false;
                }
                return true;
            }
            if (c == ';')
            {
                std::string part = trim(line.substr(begin, i - begin));
                if (!part.empty())
                    result.push_back(part);
                if (result.size() > 32)
                {
                    error = "At most 32 commands per line";
                    return false;
                }
                begin    = i + 1;
                boundary = true;
            }
            else
                boundary = c == ' ' || c == '\t';
        }
        if (escape || quote)
        {
            error = escape ? "Trailing escape" : "Unclosed quote";
            return false;
        }
        std::string tail = trim(line.substr(begin));
        if (!tail.empty())
            result.push_back(tail);
        if (result.size() > 32)
        {
            error = "At most 32 commands per line";
            return false;
        }
        return true;
    }

    Engine::Engine(Backend& backend, Output& output)
        : backend_(backend)
        , output_(output)
        , cwd_("/")
        , previous_("/")
        , nextHistory_(1)
        , budget_(0)
        , status_(0)
        , exit_(false)
    {
    }

    bool Engine::registerCommand(const Command& command)
    {
        if (!variableName(command.name) || !command.handler || commands_.size() == 64)
            return false;
        for (std::size_t i = 0; i < commands_.size(); ++i)
            if (commands_[i].name == lower(command.name))
                return false;
        Command stored = command;
        stored.name    = lower(stored.name);
        commands_.push_back(stored);
        return true;
    }

    const std::vector<Command>& Engine::commands() const
    {
        return commands_;
    }

    const std::vector<HistoryEntry>& Engine::history() const
    {
        return history_;
    }

    bool Engine::busy() const
    {
        return !jobs_.empty();
    }

    bool Engine::exiting() const
    {
        return exit_;
    }

    void Engine::exit()
    {
        exit_ = true;
        jobs_.clear();
    }

    int Engine::status() const
    {
        return status_;
    }

    const std::string& Engine::cwd() const
    {
        return cwd_;
    }

    Backend& Engine::backend()
    {
        return backend_;
    }

    Output& Engine::output()
    {
        return output_;
    }

    void Engine::line(const std::string& text)
    {
        output_.print(text + "\n");
    }

    const std::map<std::string, std::string>& Engine::variables() const
    {
        return variables_;
    }

    bool Engine::variable(const std::string& name, std::string& value) const
    {
        if (name == "PWD")
        {
            value = cwd_;
            return true;
        }
        if (name == "STATUS")
        {
            char n[32];
            std::sprintf(n, "%d", status_);
            value = n;
            return true;
        }
        std::map<std::string, std::string>::const_iterator found = variables_.find(name);
        if (found == variables_.end())
            return false;
        value = found->second;
        return true;
    }

    bool Engine::set(const std::string& name, const std::string& value)
    {
        if (!variableName(name) || name == "PWD" || name == "STATUS" || value.size() > 4095)
            return false;
        std::size_t size = value.size();
        for (std::map<std::string, std::string>::const_iterator i = variables_.begin();
             i != variables_.end();
             ++i)
            if (i->first != name)
                size += i->second.size();
        if (size > 65536 || (!variables_.count(name) && variables_.size() == 128))
            return false;
        variables_[name] = value;
        return true;
    }

    bool Engine::unset(const std::string& name)
    {
        return variables_.erase(name) != 0;
    }

    std::string Engine::path(const std::string& input) const
    {
        if (input.size() > 2048)
            return "";
        std::string joined = input.empty() ? cwd_ : input[0] == '/' ? input : cwd_ + "/" + input;
        Arguments   parts;
        for (std::size_t pos = 0; pos < joined.size();)
        {
            std::size_t end = joined.find('/', pos);
            if (end == std::string::npos)
                end = joined.size();
            std::string part = joined.substr(pos, end - pos);
            if (part == "..")
            {
                if (!parts.empty())
                    parts.pop_back();
            }
            else if (!part.empty() && part != ".")
            {
                for (std::size_t i = 0; i < part.size(); ++i)
                    if (static_cast<unsigned char>(part[i]) < 32 || part[i] == ':'
                        || part[i] == '\\' || part[i] == 127)
                        return "";
                parts.push_back(part);
            }
            pos = end + 1;
        }
        std::string result;
        for (std::size_t i = 0; i < parts.size(); ++i)
            result += "/" + parts[i];
        return result.empty() ? "/" : result.size() > 2048 ? "" : result;
    }

    int Engine::changeDirectory(const std::string& input)
    {
        std::string target = input == "-" ? previous_ : input.empty() ? "/" : path(input);
        if (target.empty())
            return -22;
        int result = backend_.changeDirectory(target);
        if (result == 0)
        {
            previous_ = cwd_;
            cwd_      = target;
        }
        return result;
    }

    bool Engine::tokenize(const std::string& line, Arguments& arguments, std::string& error) const
    {
        char        quote = 0;
        std::string word;
        bool        started = false;
        arguments.clear();
        for (std::size_t i = 0; i < line.size(); ++i)
        {
            char c = line[i];
            if (!quote && (c == ' ' || c == '\t'))
            {
                if (started)
                {
                    arguments.push_back(word);
                    word.clear();
                    started = false;
                }
                continue;
            }
            if (!quote && c == '#' && !started)
                break;
            started = true;
            if (c == '\\' && quote != '\'')
            {
                if (++i == line.size())
                {
                    error = "Trailing escape";
                    return false;
                }
                word += line[i];
            }
            else if ((c == '\'' || c == '"') && (!quote || quote == c))
            {
                quote = quote ? 0 : c;
            }
            else if (c == '$' && quote != '\'')
            {
                std::string name;
                if (i + 1 < line.size() && line[i + 1] == '{')
                {
                    std::size_t end = line.find('}', i + 2);
                    if (end == std::string::npos)
                    {
                        error = "Unclosed variable expansion";
                        return false;
                    }
                    name = line.substr(i + 2, end - i - 2);
                    i    = end;
                    if (!variableName(name))
                    {
                        error = "Invalid variable name";
                        return false;
                    }
                }
                else
                {
                    std::size_t end = i + 1;
                    while (end < line.size()
                           && ((line[end] >= 'A' && line[end] <= 'Z')
                               || (line[end] >= 'a' && line[end] <= 'z') || line[end] == '_'
                               || (end > i + 1 && line[end] >= '0' && line[end] <= '9')))
                        ++end;
                    name = line.substr(i + 1, end - i - 1);
                    if (name.empty())
                    {
                        word += '$';
                        continue;
                    }
                    i = end - 1;
                }
                std::string value;
                if (!variable(name, value))
                {
                    error = "Undefined variable: " + name;
                    return false;
                }
                word += value;
            }
            else
                word += c;
            if (word.size() > 4095)
            {
                error = "Expanded argument exceeds 4095 bytes";
                return false;
            }
            if (arguments.size() > 32)
            {
                error = "Too many arguments";
                return false;
            }
        }
        if (quote)
        {
            error = "Unclosed quote";
            return false;
        }
        if (started)
            arguments.push_back(word);
        if (arguments.size() > 32)
        {
            error = "Too many arguments";
            return false;
        }
        return true;
    }

    bool Engine::submit(const std::string& input)
    {
        if (busy())
        {
            line("Command batch still running");
            return false;
        }
        std::string text = trim(input);
        if (text == "!!" || (!text.empty() && text[0] == '!' && text.size() > 1))
        {
            unsigned id = 0;
            if (text == "!!")
                id = history_.empty() ? 0 : history_.back().id;
            else
                for (std::size_t i = 1; i < text.size(); ++i)
                {
                    if (text[i] < '0' || text[i] > '9' || id > 100000000)
                    {
                        id = 0;
                        break;
                    }
                    id = id * 10 + text[i] - '0';
                }
            bool found = false;
            for (std::size_t i = 0; i < history_.size(); ++i)
                if (history_[i].id == id)
                {
                    text  = history_[i].line;
                    found = true;
                    break;
                }
            if (!found)
            {
                status_ = -2;
                line("History entry not found");
                return false;
            }
            line(text);
        }
        Arguments   commands;
        std::string error;
        if (!splitCommands(text, commands, error))
        {
            status_ = -22;
            line(error);
            return false;
        }
        if (commands.empty())
            return true;
        HistoryEntry entry;
        entry.id   = nextHistory_++;
        entry.line = text;
        history_.push_back(entry);
        if (history_.size() > 64)
            history_.erase(history_.begin());
        budget_ = 2048;
        jobs_.push_back(Job(commands, 1));
        return true;
    }

    bool Engine::repeat(unsigned count, const std::string& text)
    {
        Arguments   commands;
        std::string error;
        if (!count || count > 1000 || jobs_.size() >= 16 || !splitCommands(text, commands, error)
            || commands.empty())
            return false;
        jobs_.push_front(Job(commands, count));
        return true;
    }

    void Engine::tick()
    {
        if (jobs_.empty() || exit_)
            return;
        if (!budget_--)
        {
            jobs_.clear();
            status_ = -27;
            line("Batch stopped: 2048-command budget exceeded");
            return;
        }
        Job&        job     = jobs_.front();
        std::string command = job.commands[job.index++];
        if (job.index == job.commands.size())
        {
            job.index = 0;
            if (!--job.remaining)
                jobs_.pop_front();
        }
        Arguments   arguments;
        std::string error;
        // Prefix assignments are visible during expansion and the handler only.
        struct Restore
        {
            std::map<std::string, std::string>& target;
            std::map<std::string, std::string> saved;
            bool active;
            Restore(std::map<std::string, std::string>& vars)
                : target(vars), saved(vars), active(true) {}
            ~Restore() { if (active) target = saved; }
        } restore(variables_);
        bool prefixed = false;
        while (!command.empty())
        {
            std::size_t equal = command.find('=');
            if (equal == std::string::npos || !variableName(command.substr(0, equal))) break;
            prefixed = true;
            char quote = 0;
            bool escape = false;
            std::size_t end = equal + 1;
            for (; end < command.size(); ++end)
            {
                char c = command[end];
                if (escape) { escape = false; continue; }
                if (c == '\\' && quote != '\'') { escape = true; continue; }
                if ((c == '\'' || c == '"') && (!quote || quote == c))
                    quote = quote ? 0 : c;
                else if (!quote && (c == ' ' || c == '\t')) break;
            }
            Arguments value;
            if (!tokenize(command.substr(equal + 1, end - equal - 1), value, error)
                || !set(command.substr(0, equal), value.empty() ? "" : value[0]))
            {
                status_ = -22;
                jobs_.clear();
                line(error.empty() ? "Invalid assignment" : error);
                return;
            }
            command = trim(command.substr(end));
        }
        if (command.empty())
        {
            restore.active = false;
            status_ = 0;
            return;
        }
        // With no prefixes, ordinary commands retain their variable changes.
        restore.active = prefixed;
        if (!tokenize(command, arguments, error))
        {
            status_ = -22;
            jobs_.clear();
            line(error);
            return;
        }
        if (arguments.empty())
            return;
        std::string name    = lower(arguments[0]);
        Handler     handler = 0;
        for (std::size_t i = 0; i < commands_.size(); ++i)
            if (commands_[i].name == name)
            {
                handler = commands_[i].handler;
                break;
            }
        if (!handler)
        {
            status_ = -2;
            jobs_.clear();
            line("Unknown command: " + name + " (try help)");
            return;
        }
        status_ = handler(*this, arguments);
        if (status_ != 0)
        {
            jobs_.clear();
            char text[64];
            std::sprintf(text, "Command failed (%d)", status_);
            line(text);
        }
    }
}  // namespace terminal
