// Convierte una gramática a forma normal de Chomsky:
//   to_chomsky ARCHIVO.cfg                        escribe el resultado en formato .cfg
//   to_chomsky ARCHIVO.cfg --pasos                muestra la gramática después de cada paso
//   to_chomsky ARCHIVO.cfg --unitarias-primero    el orden equivocado: paso 3 antes que el paso 2
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>

#include "cfg.h"
#include "chomsky.h"

// Las reglas de g, una línea por variable, como en el archivo pero sin el encabezado.
static void print_rules(const Cfg& g) {
    for (const std::string& name : g.variables) {
        std::string line;
        for (const Rule& rule : g.rules) {
            if (rule.head == name) {
                line += (line.empty() ? name + " -> " : " | ") + body_text(rule.body);
            }
        }
        if (!line.empty()) {
            std::cout << "  " << line << '\n';
        }
    }
}

static void report(const std::string& title, const Cfg& g) {
    std::cout << title << " (" << g.rules.size() << " reglas)\n";
    print_rules(g);
}

int main(int argc, char** argv) {
    if (argc < 2 || argc > 3) {
        std::cerr << "uso: to_chomsky ARCHIVO.cfg [--pasos | --unitarias-primero]\n";
        return 2;
    }
    try {
        Cfg g = load_cfg(argv[1]);
        std::string option = (argc == 3) ? argv[2] : "";
        if (option.empty()) {
            std::cout << "# " << argv[1] << " en forma normal de Chomsky.\n";
            write_cfg(std::cout, to_chomsky(g));
            return 0;
        }
        if (option != "--pasos" && option != "--unitarias-primero") {
            throw std::runtime_error("opción desconocida: " + option);
        }
        report("La gramática original", g);
        Cfg result = with_new_start(g);
        report("\nPaso 1: variable inicial nueva", result);
        if (option == "--pasos") {
            result = without_epsilon_rules(result);
            report("\nPaso 2: sin reglas ε", result);
            result = without_unit_rules(result);
            report("\nPaso 3: sin reglas unitarias", result);
        } else {
            result = without_unit_rules(result);
            report("\nPaso 3 antes de tiempo: sin reglas unitarias", result);
            result = without_epsilon_rules(result);
            report("\nPaso 2, tarde: sin reglas ε", result);
        }
        result = with_short_rules(result);
        report("\nPaso 4: reglas de a lo sumo dos símbolos, y terminales solos", result);
        std::string why = why_not_chomsky(result);
        if (why.empty()) {
            std::cout << "\nEstá en forma normal de Chomsky.\n";
        } else {
            std::cout << "\nNo está en forma normal de Chomsky. " << why << ".\n";
        }
    } catch (const std::exception& error) {
        std::cerr << "error: " << error.what() << '\n';
        return 1;
    }
}
