/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, readFileSync, watchFile, unwatchFile } from 'node:fs';
import { join } from 'node:path';
// ─── Loader ───────────────────────────────────────────────────────────────────
const INDEX_FILENAME = 'sf-metadata-index.json';
let currentIndex = null;
let currentMaps = null;
let indexPath = null;
let onChangeCallback = null;
function buildMaps(index) {
    const byApiName = new Map();
    const byPath = new Map();
    const byType = new Map();
    for (const entry of index.entries) {
        byApiName.set(entry.apiName, entry);
        if (entry.path) {
            byPath.set(entry.path, entry);
        }
        const existing = byType.get(entry.type);
        if (existing) {
            existing.push(entry);
        }
        else {
            byType.set(entry.type, [entry]);
        }
    }
    return { byApiName, byPath, byType };
}
function readAndParse(filePath) {
    if (!existsSync(filePath)) {
        return null;
    }
    try {
        const raw = readFileSync(filePath, 'utf-8');
        const parsed = JSON.parse(raw);
        if (!parsed.entries || !Array.isArray(parsed.entries)) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
export function loadIndex(workspaceRoot) {
    const filePath = join(workspaceRoot, '.setup-agents', INDEX_FILENAME);
    indexPath = filePath;
    const index = readAndParse(filePath);
    if (index) {
        currentIndex = index;
        currentMaps = buildMaps(index);
        return true;
    }
    currentIndex = null;
    currentMaps = null;
    return false;
}
export function watchIndex(workspaceRoot, onChange) {
    const filePath = join(workspaceRoot, '.setup-agents', INDEX_FILENAME);
    indexPath = filePath;
    onChangeCallback = onChange;
    watchFile(filePath, { interval: 2000 }, () => {
        const index = readAndParse(filePath);
        if (index) {
            currentIndex = index;
            currentMaps = buildMaps(index);
        }
        if (onChangeCallback) {
            onChangeCallback();
        }
    });
}
export function unwatchIndex() {
    if (indexPath) {
        unwatchFile(indexPath);
        indexPath = null;
    }
    onChangeCallback = null;
}
// ─── Query API ────────────────────────────────────────────────────────────────
export function isIndexLoaded() {
    return currentIndex !== null && currentMaps !== null;
}
export function getEntry(apiName) {
    return currentMaps?.byApiName.get(apiName);
}
export function getEntriesByType(type) {
    return currentMaps?.byType.get(type) ?? [];
}
export function findByPath(path) {
    return currentMaps?.byPath.get(path);
}
export function getAllEntries() {
    return currentIndex?.entries ?? [];
}
export function getAllApiNames() {
    if (!currentMaps)
        return [];
    return Array.from(currentMaps.byApiName.keys());
}
export function getApiNamesByType(type) {
    return getEntriesByType(type).map((e) => e.apiName);
}
export function searchEntries(prefix) {
    if (!currentMaps)
        return [];
    const lowerPrefix = prefix.toLowerCase();
    const results = [];
    currentMaps.byApiName.forEach((entry, name) => {
        if (name.toLowerCase().startsWith(lowerPrefix)) {
            results.push(entry);
        }
    });
    return results;
}
//# sourceMappingURL=index-loader.js.map