// Funciones para mostrar autómatas de pila y sus ejecuciones en la terminal.
#ifndef PRINT_H
#define PRINT_H

#include <cstddef>
#include <ostream>
#include <string>
#include <vector>

#include "pda.h"

// Cuántas columnas ocupa un texto en UTF-8: los bytes de continuación no cuentan.
inline std::size_t width_of(const std::string& text) {
    std::size_t width = 0;
    for (unsigned char c : text) {
        if ((c & 0xC0) != 0x80) {
            width++;
        }
    }
    return width;
}

// El texto, completado con espacios a la derecha hasta ocupar width columnas.
inline std::string pad(const std::string& text, std::size_t width) {
    std::size_t used = width_of(text);
    return used >= width ? text : text + std::string(width - used, ' ');
}

inline std::string shown(const std::string& w) {
    return w.empty() ? "ε" : w;
}

// La etiqueta de una transición, como en los diagramas: "lee, saca → pone".
inline std::string label_of(const Step& step) {
    return symbol_shown(step.read) + ", " + symbol_shown(step.pop) + " → " + symbol_shown(step.push);
}

// Una ejecución como tabla: una fila por configuración, con la transición que llevó a ella.
// La pila se escribe con la cima a la izquierda.
inline void print_run(std::ostream& out, const std::string& w, const std::vector<Step>& run) {
    std::size_t state_width = 6;
    std::size_t rest_width = 10;
    for (const Step& step : run) {
        state_width = std::max(state_width, width_of(step.config.state));
        rest_width = std::max(rest_width, w.size() - step.config.pos);
    }
    out << "  paso  transición  " << pad("estado", state_width) << "  " << pad("falta leer", rest_width) << "  pila\n";
    for (std::size_t i = 0; i < run.size(); i++) {
        const Step& step = run[i];
        std::string number = std::to_string(i);
        out << "  " << std::string(4 - std::min<std::size_t>(4, number.size()), ' ') << number << "  "
            << pad(i == 0 ? "" : label_of(step), 10) << "  " << pad(step.config.state, state_width) << "  "
            << pad(shown(w.substr(step.config.pos)), rest_width) << "  " << shown(step.config.stack) << '\n';
    }
}

#endif
