"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.SemanticDictionaryAgent = void 0;
const AICore_1 = require("../../core/ai/AICore");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class SemanticDictionaryAgent {
    constructor() {
        this.name = "SemanticDictionaryAgent";
        this.description = "Discovers, validates, and resolves conflicts in the project's semantic dictionary.";
        this.personality = "A meticulous terminologist who ensures every term has one precise meaning.";
        this.llmProvider = "github-models";
        this.expertise = ["Semantic Analysis", "Terminology Management", "NLP", "Ontology Design"];
    }
    getAICore() {
        if (!this.ai) {
            try {
                this.ai = AICore_1.AICore.getInstance();
            }
            catch {
                this.ai = AICore_1.AICore.getInstance({
                    workingDirectory: process.cwd(),
                    fallbackEnabled: true,
                });
            }
        }
        return this.ai;
    }
    getContextJson() {
        try {
            const ctxPath = path.join(process.cwd(), ".mycontext", "context.json");
            if (fs.pathExistsSync(ctxPath)) {
                return fs.readJsonSync(ctxPath);
            }
        }
        catch { }
        return {};
    }
    scanSourceFiles(paths) {
        const terms = new Set();
        const extensions = [".ts", ".tsx", ".js", ".jsx", ".json", ".md"];
        for (const scanPath of paths) {
            try {
                const absPath = path.resolve(process.cwd(), scanPath);
                if (!fs.pathExistsSync(absPath))
                    continue;
                const walk = (dir) => {
                    const entries = fs.readdirSync(dir, { withFileTypes: true });
                    for (const entry of entries) {
                        const fullPath = path.join(dir, entry.name);
                        if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
                            walk(fullPath);
                        }
                        else if (entry.isFile() && extensions.some((e) => entry.name.endsWith(e))) {
                            try {
                                const content = fs.readFileSync(fullPath, "utf-8");
                                const camelCaseWords = content.match(/\b[A-Z][a-z]+(?:[A-Z][a-z]+)+\b/g) || [];
                                for (const word of camelCaseWords) {
                                    if (word.length > 3)
                                        terms.add(word);
                                }
                            }
                            catch { }
                        }
                    }
                };
                walk(absPath);
            }
            catch { }
        }
        return Array.from(terms).slice(0, 100);
    }
    async run(input) {
        const context = this.getContextJson();
        const dict = context?.brain?.context?.semanticDictionary || {};
        const existingTerms = dict.entries || {};
        let candidateTerms = input.terms || [];
        if (input.scanPaths && input.scanPaths.length > 0) {
            candidateTerms = [...candidateTerms, ...this.scanSourceFiles(input.scanPaths)];
        }
        const terms = [];
        const conflicts = [];
        const recommendations = [];
        for (const term of candidateTerms) {
            const existing = existingTerms[term];
            let definition = existing?.definition || "";
            let relatedTerms = [];
            if (!definition) {
                try {
                    const aiCore = this.getAICore();
                    const result = await aiCore.generateStructuredText(`Define the term "${term}" in the context of a software project.
Provide a concise definition and 2-3 related terms.`, '{ "definition": "string", "relatedTerms": ["string"] }');
                    definition = result.definition;
                    relatedTerms = result.relatedTerms;
                }
                catch {
                    definition = "(definition pending AI generation)";
                }
            }
            terms.push({
                term,
                definition,
                usageCount: 0,
                relatedTerms,
            });
        }
        for (const [key, entry] of Object.entries(existingTerms)) {
            if (!candidateTerms.includes(key)) {
                terms.push({
                    term: key,
                    definition: entry.definition,
                    usageCount: 0,
                    relatedTerms: [],
                });
            }
        }
        if (candidateTerms.length > 0) {
            const knownKeys = Object.keys(existingTerms);
            const newTerms = candidateTerms.filter((t) => !knownKeys.includes(t));
            if (newTerms.length > 0) {
                recommendations.push(`${newTerms.length} new terms discovered: register them with semantics:define`);
            }
        }
        return {
            termsFound: terms.length,
            terms,
            conflicts,
            recommendations,
        };
    }
    async validate(input) {
        return true;
    }
}
exports.SemanticDictionaryAgent = SemanticDictionaryAgent;
//# sourceMappingURL=SemanticDictionaryAgent.js.map