// Muestra una máquina de Turing como séptupla y como tabla: show_tm ARCHIVO.tm
// En la tabla, un punto es un par sin transición: ese par lleva a q_reject.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

#include "tm.h"

static std::string pad(const std::string& text, std::size_t width) {
    return text.size() >= width ? text : text + std::string(width - text.size(), ' ');
}

template <typename Items>
static void print_set(const std::string& label, const Items& items) {
    std::cout << label << "{";
    bool first = true;
    for (const auto& item : items) {
        std::cout << (first ? "" : ", ") << item;
        first = false;
    }
    std::cout << "}\n";
}

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "uso: show_tm ARCHIVO.tm\n";
        return 2;
    }
    try {
        Tm m = load_tm(argv[1]);
        print_set("Q = ", m.states);
        print_set("Σ = ", m.alphabet);
        print_set("Γ = ", m.tape);
        std::cout << "q0 = " << m.start << ", q_accept = " << m.accept << ", q_reject = " << m.reject << "\n\n";

        // Una fila por cada estado del que sale alguna transición posible, una columna por símbolo.
        std::size_t name_width = 1;
        std::size_t cell_width = 1;
        for (const std::string& q : m.states) {
            name_width = std::max(name_width, q.size());
        }
        std::vector<std::vector<std::string>> rows;
        for (const std::string& q : m.states) {
            if (q == m.accept || q == m.reject) {
                continue;
            }
            std::vector<std::string> row = {q};
            for (char a : m.tape) {
                auto it = m.delta.find({q, a});
                std::string cell = ".";
                if (it != m.delta.end()) {
                    cell = it->second.state + " " + it->second.write + " " + it->second.move;
                }
                cell_width = std::max(cell_width, cell.size());
                row.push_back(cell);
            }
            rows.push_back(row);
        }
        std::string header = pad("δ", name_width + 1);  // δ ocupa dos bytes y una columna
        for (char a : m.tape) {
            header += "  " + pad(std::string(1, a), cell_width);
        }
        rows.insert(rows.begin(), {header});
        for (const std::vector<std::string>& row : rows) {
            std::string line = pad(row[0], name_width);
            for (std::size_t i = 1; i < row.size(); i++) {
                line += "  " + pad(row[i], cell_width);
            }
            while (!line.empty() && line.back() == ' ') {
                line.pop_back();
            }
            std::cout << line << '\n';
        }
        std::cout << "\ntransiciones escritas: " << m.delta.size() << " de " << (rows.size() - 1) * m.tape.size() << '\n';
    } catch (const std::runtime_error& error) {
        std::cerr << "error: " << error.what() << '\n';
        return 1;
    }
}
