// Carga el archivo de términos: una línea por término, frecuencia<TAB>término.
// Es la parte de entrada del laboratorio y ya viene hecha.
#ifndef TERMS_IO_H
#define TERMS_IO_H

#include <cstddef>
#include <fstream>
#include <string>
#include <vector>

struct Term {
    std::string text;
    long long weight;
};

// Agrega a terms las líneas del archivo. Devuelve false si no se puede abrir o si una
// línea no tiene la forma esperada.
inline bool load_terms(const std::string& path, std::vector<Term>& terms) {
    std::ifstream file(path);
    if (!file) {
        return false;
    }
    std::string line;
    while (std::getline(file, line)) {
        std::size_t tab = line.find('\t');
        if (tab == std::string::npos || tab == 0 || tab + 1 == line.size()) {
            return false;
        }
        long long weight = 0;
        for (std::size_t i = 0; i < tab; i++) {
            if (line[i] < '0' || line[i] > '9') {
                return false;
            }
            weight = weight * 10 + (line[i] - '0');
        }
        terms.push_back(Term{line.substr(tab + 1), weight});
    }
    return true;
}

#endif
