// Pruebas del parser y de la escritura de expresiones regulares (sesión A).
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>

#include "regex.h"

static bool is_malformed(const std::string& text) {
    try {
        parse_regex(text);
    } catch (const std::runtime_error&) {
        return true;
    }
    return false;
}

static void test_precedence() {
    // La estrella liga más que la concatenación, y la concatenación más que la unión.
    assert(to_string_full(parse_regex("ab|c*")) == "((ab)|(c*))");
    assert(to_string_full(parse_regex("ab*")) == "(a(b*))");
    assert(to_string_full(parse_regex("(ab)*")) == "((ab)*)");
    assert(to_string_full(parse_regex("a|bc")) == "(a|(bc))");
    assert(to_string_full(parse_regex("(a|b)c")) == "((a|b)c)");
    assert(to_string_full(parse_regex("(0|1)*1")) == "(((0|1)*)1)");
    assert(to_string_full(parse_regex("0|1*")) == "(0|(1*))");
    // La unión y la concatenación se agrupan hacia la izquierda.
    assert(to_string_full(parse_regex("abc")) == "((ab)c)");
    assert(to_string_full(parse_regex("a|b|c")) == "((a|b)|c)");
    // El árbol de (0|1)*1: la raíz es la concatenación.
    RegexPtr r = parse_regex("(0|1)*1");
    assert(r->kind == Kind::Concat);
    assert(r->left->kind == Kind::Star && r->left->left->kind == Kind::Union);
    assert(r->right->kind == Kind::Symbol && r->right->symbol == '1');
    assert(size(r) == 6);
    assert(tree(parse_regex("ab|c*")) ==
           "unión\n    concatenación\n        a\n        b\n    estrella\n        c\n");
}

static void test_epsilon_and_empty() {
    assert(parse_regex("%")->kind == Kind::Epsilon);
    assert(parse_regex("ε")->kind == Kind::Epsilon);
    assert(parse_regex("@")->kind == Kind::Empty);
    assert(parse_regex("∅")->kind == Kind::Empty);
    assert(to_string(parse_regex("(0|%)1*")) == "(0|ε)1*");
    assert(to_string(parse_regex("(0|ε)1*")) == "(0|ε)1*");
    assert(to_string(parse_regex("@*")) == "∅*");
    assert(to_string(parse_regex(" 0* 1 0* ")) == "0*10*");
}

static void test_round_trip() {
    // Lo que se escribe se vuelve a leer y se escribe igual, con los paréntesis justos.
    std::vector<std::string> expressions = {
        "(0|1)*1",     "((0|1)(0|1))*", "0*10*10*",      "1*(01*01*)*", "(1|01*0)*", "(0|10)*(ε|1)",
        "(0|ε)1*",     "(01)*|(10)*",   "(1|01*01*0)*",  "(ab|a)*",     "(a*)*",     "(a|a)*b",
        "∅*",          "a|b|c",         "(a|b)(c|d)",    "a(b|c)*d",    "0|1*",      "(0|1*)*",
    };
    for (const std::string& text : expressions) {
        RegexPtr r = parse_regex(text);
        assert(to_string(r) == text);
        assert(to_string(parse_regex(to_string(r))) == text);
        assert(to_string(parse_regex(to_string_full(r))) == text);
    }
    // Paréntesis de más: se leen y no se vuelven a escribir.
    assert(to_string(parse_regex("((0)|(1))*")) == "(0|1)*");
    assert(to_string(parse_regex("(a(b))c")) == "abc");
    assert(to_string(parse_regex("a**")) == "(a*)*");
}

static void test_simplified_operations() {
    RegexPtr r = parse_regex("0|1");
    assert(to_string(simple_union(r, empty_set())) == "0|1");
    assert(to_string(simple_union(empty_set(), r)) == "0|1");
    assert(simple_concat(r, empty_set())->kind == Kind::Empty);
    assert(simple_concat(empty_set(), r)->kind == Kind::Empty);
    assert(to_string(simple_concat(r, epsilon())) == "0|1");
    assert(to_string(simple_concat(epsilon(), r)) == "0|1");
    assert(simple_star(empty_set())->kind == Kind::Epsilon);
    assert(simple_star(epsilon())->kind == Kind::Epsilon);
    assert(to_string(simple_star(r)) == "(0|1)*");
}

static std::size_t test_malformed() {
    std::ifstream file("errors/malformed.txt");
    assert(file);
    std::string line;
    std::size_t count = 0;
    while (std::getline(file, line)) {
        if (line.empty() || line[0] == '#') {
            continue;
        }
        assert(is_malformed(line));
        count++;
    }
    assert(count == 9);
    assert(is_malformed(""));
    assert(is_malformed("   "));
    // El mensaje dice dónde está el problema.
    try {
        parse_regex("0|*");
        assert(false);
    } catch (const std::runtime_error& error) {
        assert(std::string(error.what()) == "posición 3: se esperaba un símbolo o un paréntesis, y hay *");
    }
    return count;
}

int main() {
    test_precedence();
    test_epsilon_and_empty();
    test_round_trip();
    test_simplified_operations();
    std::size_t malformed = test_malformed();
    std::printf("test_regex: ok (%zu expresiones mal formadas rechazadas)\n", malformed);
}
