// Comprueba si una secuencia de fichas es una solución de una instancia de PCP.
//   pcp_check instancia.pcp i1 i2 ... ik      (las fichas se numeran desde 1)
// Muestra, ficha por ficha, lo que se lee arriba y abajo.
#include <cstdlib>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include "pcp.h"

int main(int argc, char** argv) {
    if (argc < 3) {
        std::cerr << "uso: pcp_check instancia.pcp i1 i2 ... ik\n";
        return 2;
    }
    try {
        std::ifstream file(argv[1]);
        if (!file) throw std::runtime_error(std::string("no se pudo abrir ") + argv[1]);
        const std::vector<Domino> dominoes = read_pcp(file);
        std::vector<int> sequence;
        for (int i = 2; i < argc; ++i) {
            const int index = std::atoi(argv[i]);
            if (index < 1 || index > static_cast<int>(dominoes.size())) {
                throw std::runtime_error(std::string("no existe la ficha ") + argv[i]);
            }
            sequence.push_back(index - 1);
        }
        std::string top_pieces;
        std::string bottom_pieces;
        for (int i : sequence) {
            top_pieces += " " + dominoes[i].top;
            bottom_pieces += " " + dominoes[i].bottom;
        }
        const std::string top = concatenate(dominoes, sequence, true);
        const std::string bottom = concatenate(dominoes, sequence, false);
        std::cout << "arriba:" << top_pieces << "  =  " << top << "\n";
        std::cout << "abajo: " << bottom_pieces << "  =  " << bottom << "\n";
        if (is_solution(dominoes, sequence)) {
            std::cout << "es una solución (" << sequence.size() << " fichas, " << top.size() << " símbolos)\n";
            return 0;
        }
        std::size_t common = 0;
        while (common < top.size() && common < bottom.size() && top[common] == bottom[common]) ++common;
        if (common == top.size() || common == bottom.size()) {
            const bool top_ahead = top.size() > bottom.size();
            std::cout << "no es una solución: " << (top_ahead ? "arriba" : "abajo") << " sobra "
                      << (top_ahead ? top.substr(common) : bottom.substr(common)) << "\n";
        } else {
            std::cout << "no es una solución: las cadenas difieren en la posición " << common + 1 << "\n";
        }
        return 1;
    } catch (const std::exception& error) {
        std::cerr << "error: " << error.what() << "\n";
        return 2;
    }
}
