import { read_config } from "../config/config.js";
import { error, info } from "../log.js";
import { save_tagsets } from "./util.js";

import path from "path";
import fs from "fs";

export default function run() {
    const CONFIG = read_config("install/compare");
    if (!CONFIG.use.tags) {
        error("install/config", "Cannot run install for a project that has disabled tagsets");
        return;
    }
    const TAGSET_FOLDER = path.join(process.cwd(), CONFIG.folder.tags);

    info("install/compare", "Reading tagset folder");
    const ALREADY_HAS: string[] = [];
    fs.readdirSync(TAGSET_FOLDER).forEach((file_name: string) => {
        if (!file_name.endsWith(".js")) return;
        ALREADY_HAS.push(file_name.slice(0, -(".js".length)));
    });

    info("install/compare", "Comparing required tagsets with already installed ones");
    const NEEDS_FETCH: string[] = [];
    CONFIG.tags.forEach((tag_name: string) => {
        if (ALREADY_HAS.includes(tag_name)) return;
        NEEDS_FETCH.push(tag_name);
    });

    save_tagsets("install/fetch", NEEDS_FETCH, CONFIG);
}