import fs from "node:fs";
import path from "node:path";
import { bobbitConfigDir } from "../bobbit-dir.js";
const DEFAULT_PATH = path.join(bobbitConfigDir(), "tools.json");
/**
 * File-backed tool metadata store. Persists custom overrides
 * (description, group, docs) to .bobbit/config/tools.json.
 * Same load-on-construct, write-on-mutate pattern as other stores.
 */
export class ToolStore {
    tools = new Map();
    filePath;
    constructor(filePath) {
        this.filePath = filePath ?? DEFAULT_PATH;
        this.load();
    }
    load() {
        try {
            const raw = fs.readFileSync(this.filePath, "utf-8");
            const data = JSON.parse(raw);
            if (Array.isArray(data)) {
                for (const item of data) {
                    if (item && typeof item === "object" && item.name) {
                        this.tools.set(item.name, item);
                    }
                }
            }
            else if (data && typeof data === "object" && Array.isArray(data.tools)) {
                // Also accept { tools: [...] } wrapper format
                for (const item of data.tools) {
                    if (item && typeof item === "object" && item.name) {
                        this.tools.set(item.name, item);
                    }
                }
            }
        }
        catch {
            // File doesn't exist or is invalid — start empty
        }
    }
    save() {
        const dir = path.dirname(this.filePath);
        fs.mkdirSync(dir, { recursive: true });
        fs.writeFileSync(this.filePath, JSON.stringify(Array.from(this.tools.values()), null, 2), "utf-8");
    }
    get(name) {
        return this.tools.get(name);
    }
    put(meta) {
        this.tools.set(meta.name, meta);
        this.save();
    }
    getAll() {
        return Array.from(this.tools.values());
    }
}
//# sourceMappingURL=tool-store.js.map