// Lista las derivaciones por la izquierda de una cadena, cada una con su árbol:
//   derive ARCHIVO.cfg CADENA [--pasos N] [--sin-arboles]
// La cadena vacía se pasa como '' en la terminal. --pasos es el tope de pasos de cada
// derivación (40 si no se indica): con reglas ε o unitarias la búsqueda puede no terminar.
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include "cfg.h"

int main(int argc, char** argv) {
    if (argc < 3) {
        std::cerr << "uso: derive ARCHIVO.cfg CADENA [--pasos N] [--sin-arboles]\n";
        return 2;
    }
    try {
        Cfg g = load_cfg(argv[1]);
        std::string w = argv[2];
        std::size_t max_steps = 40;
        bool trees = true;
        for (int i = 3; i < argc; i++) {
            std::string option = argv[i];
            if (option == "--pasos" && i + 1 < argc) {
                max_steps = std::stoul(argv[++i]);
            } else if (option == "--sin-arboles") {
                trees = false;
            } else {
                throw std::runtime_error("opción desconocida: " + option);
            }
        }
        DerivationSearch search = leftmost_derivations(g, w, max_steps, 20);
        std::cout << "w = " << (w.empty() ? "ε" : w) << "\nderivaciones por la izquierda: " << search.found.size();
        if (!search.complete) {
            std::cout << " (la búsqueda se cortó: derivaciones de hasta " << max_steps << " pasos, 20 como máximo)";
        }
        std::cout << '\n';
        for (std::size_t d = 0; d < search.found.size(); d++) {
            std::cout << '\n' << (d + 1) << ". ";
            std::vector<std::vector<std::string>> forms = sentential_forms(g, search.found[d]);
            for (std::size_t i = 0; i < forms.size(); i++) {
                std::cout << (i == 0 ? "" : " ⇒ ") << form_text(g, forms[i]);
            }
            std::cout << "\n   " << search.found[d].size() << " pasos\n";
            if (trees) {
                print_tree(std::cout, tree_of(g, search.found[d]), "   ", "   ");
            }
        }
    } catch (const std::exception& error) {
        std::cerr << "error: " << error.what() << '\n';
        return 1;
    }
}
