// Grafo dirigido con un nodo de partida: G = (V, E) y un nodo s.
// Es la entrada de la geografía generalizada y de PATH. Formato .graph de la semana:
//
//     # comentario
//     nodes: a b c d
//     start: a
//     edges:
//     a b
//     b c
//
// Después de `edges:` va una arista por línea, `origen destino`.
#ifndef GRAPH_H
#define GRAPH_H

#include <cstddef>
#include <fstream>
#include <istream>
#include <map>
#include <ostream>
#include <stdexcept>
#include <string>
#include <vector>

#include "fields.h"

struct Graph {
    std::vector<std::string> nodes;       // V: los nombres, en el orden del archivo
    std::vector<std::vector<int>> edges;  // E: edges[u] son los destinos de las aristas que salen de u
    int start = 0;                        // s, como posición en nodes
};

inline std::size_t edge_count(const Graph& g) {
    std::size_t m = 0;
    for (const std::vector<int>& out : g.edges) {
        m += out.size();
    }
    return m;
}

// La posición de un nodo por su nombre. Lanza std::runtime_error si no existe.
inline int node_index(const Graph& g, const std::string& name) {
    for (std::size_t i = 0; i < g.nodes.size(); i++) {
        if (g.nodes[i] == name) {
            return static_cast<int>(i);
        }
    }
    throw std::runtime_error("el nodo " + name + " no está en nodes");
}

inline Graph read_graph(std::istream& in) {
    Graph g;
    g.nodes = read_field(in, "nodes");
    if (g.nodes.empty()) {
        throw std::runtime_error("el grafo no tiene nodos");
    }
    std::map<std::string, int> index;
    for (std::size_t i = 0; i < g.nodes.size(); i++) {
        if (index.count(g.nodes[i]) != 0) {
            throw std::runtime_error("el nodo " + g.nodes[i] + " está repetido");
        }
        index[g.nodes[i]] = static_cast<int>(i);
    }
    g.edges.assign(g.nodes.size(), {});
    std::vector<std::string> start = read_field(in, "start");
    if (start.size() != 1 || index.count(start[0]) == 0) {
        throw std::runtime_error("start: lleva un nodo de nodes");
    }
    g.start = index[start[0]];
    if (!read_field(in, "edges").empty()) {
        throw std::runtime_error("después de edges: las aristas van una por línea");
    }
    std::string line;
    while (next_line(in, line)) {
        std::vector<std::string> words = split_words(line);
        if (words.size() != 2 || index.count(words[0]) == 0 || index.count(words[1]) == 0) {
            throw std::runtime_error("arista mal escrita: \"" + line + "\"");
        }
        g.edges[index[words[0]]].push_back(index[words[1]]);
    }
    return g;
}

inline Graph load_graph(const std::string& path) {
    std::ifstream in(path);
    if (!in) {
        throw std::runtime_error(path + ": no se pudo abrir");
    }
    try {
        return read_graph(in);
    } catch (const std::runtime_error& e) {
        throw std::runtime_error(path + ": " + e.what());
    }
}

inline void write_graph(std::ostream& out, const Graph& g) {
    out << "nodes:";
    for (const std::string& name : g.nodes) {
        out << ' ' << name;
    }
    out << "\nstart: " << g.nodes[g.start] << "\nedges:\n";
    for (std::size_t u = 0; u < g.nodes.size(); u++) {
        for (int v : g.edges[u]) {
            out << g.nodes[u] << ' ' << g.nodes[v] << '\n';
        }
    }
}

#endif
