// Compara dos expresiones con todas las cadenas cortas: regex_diff EXPRESIÓN1 EXPRESIÓN2 [LONGITUD]
// Lista las cadenas que una describe y la otra no. La longitud máxima por defecto es 8.
// Que no haya diferencias hasta esa longitud no demuestra que sean equivalentes.
#include <cstddef>
#include <iostream>
#include <set>
#include <stdexcept>
#include <string>
#include <vector>

#include "nfa.h"
#include "regex.h"
#include "thompson.h"
#include "words.h"

int main(int argc, char** argv) {
    if (argc < 3 || argc > 4) {
        std::cerr << "uso: regex_diff EXPRESIÓN1 EXPRESIÓN2 [LONGITUD]\n";
        return 2;
    }
    try {
        RegexPtr r1 = parse_regex(argv[1]);
        RegexPtr r2 = parse_regex(argv[2]);
        std::size_t max_len = (argc == 4) ? std::stoul(argv[3]) : 8;
        std::set<char> both;
        collect_symbols(r1, both);
        collect_symbols(r2, both);
        std::vector<char> alphabet(both.begin(), both.end());
        if (alphabet.empty()) {
            throw std::runtime_error("las expresiones no tienen símbolos");
        }
        Nfa n1 = thompson(r1, alphabet);
        Nfa n2 = thompson(r2, alphabet);
        std::vector<std::string> only1;
        std::vector<std::string> only2;
        std::vector<std::string> words = all_strings(alphabet, max_len);
        for (const std::string& w : words) {
            bool in1 = accepts(n1, w);
            bool in2 = accepts(n2, w);
            if (in1 && !in2) {
                only1.push_back(w);
            }
            if (in2 && !in1) {
                only2.push_back(w);
            }
        }
        auto report = [](const std::string& name, const std::vector<std::string>& list) {
            std::cout << "solo en " << name << ": " << list.size();
            if (!list.empty()) {
                std::cout << ". Las más cortas:";
                for (std::size_t i = 0; i < list.size() && i < 6; i++) {
                    std::cout << ' ' << show(list[i]);
                }
            }
            std::cout << '\n';
        };
        std::cout << "R1 = " << to_string(r1) << "\nR2 = " << to_string(r2) << '\n'
                  << words.size() << " cadenas de longitud a lo sumo " << max_len << '\n';
        report("R1", only1);
        report("R2", only2);
        if (only1.empty() && only2.empty()) {
            std::cout << "sin diferencias hasta esa longitud\n";
        }
    } catch (const std::exception& error) {
        std::cerr << "error: " << error.what() << '\n';
        return 1;
    }
}
