"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.perTrackIndex = perTrackIndex;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const adapter_utils_1 = require("./adapter-utils");
const config_utils_1 = require("./config-utils");
const indexing_utils_1 = require("./indexing-utils");
const validators_1 = require("./validators");
async function perTrackIndex(flags) {
    const { out, target, tracks, assemblies, attributes, quiet, force, exclude, prefixSize, } = flags;
    const outFlag = target || out || '.';
    const isDir = fs_1.default.lstatSync(outFlag).isDirectory();
    const confFilePath = isDir ? path_1.default.join(outFlag, 'config.json') : outFlag;
    const outLocation = path_1.default.dirname(confFilePath);
    const config = (0, config_utils_1.readConf)(confFilePath);
    const configTracks = config.tracks || [];
    const trixDir = path_1.default.join(outLocation, 'trix');
    if (!fs_1.default.existsSync(trixDir)) {
        fs_1.default.mkdirSync(trixDir);
    }
    (0, validators_1.validateAssembliesForPerTrack)(assemblies);
    const confs = (0, config_utils_1.getTrackConfigs)(confFilePath, tracks?.split(','));
    if (!confs.length) {
        throw new Error('Tracks not found in config.json, please add track configurations before indexing.');
    }
    for (const trackConfig of confs) {
        const { textSearching, trackId, assemblyNames } = trackConfig;
        if (textSearching?.textSearchAdapter && !force) {
            console.log(`Note: ${trackId} has already been indexed with this configuration, use --force to overwrite this track. Skipping for now`);
            continue;
        }
        console.log(`Indexing track ${trackId}...`);
        await (0, indexing_utils_1.indexDriver)({
            trackConfigs: [trackConfig],
            attributes: attributes.split(','),
            outLocation,
            quiet,
            name: trackId,
            typesToExclude: exclude.split(','),
            assemblyNames,
            prefixSize,
        });
        if (!textSearching?.textSearchAdapter) {
            // modifies track with new text search adapter
            const index = configTracks.findIndex(track => trackId === track.trackId);
            if (index !== -1) {
                configTracks[index] = {
                    ...trackConfig,
                    textSearching: {
                        ...textSearching,
                        textSearchAdapter: (0, adapter_utils_1.createPerTrackTrixAdapter)(trackId, assemblyNames),
                    },
                };
            }
            else {
                console.log("Error: can't find trackId");
            }
        }
        (0, config_utils_1.writeConf)({ ...config, tracks: configTracks }, confFilePath);
    }
}
