"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.TUIBrainService = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const ContextSyncer_1 = require("../services/ContextSyncer");
const ExecutionHistory_1 = require("../services/ExecutionHistory");
const ALLOWED_TOP_LEVEL_KEYS = new Set([
    "version",
    "generated_at",
    "project_name",
    "metadata",
    "project",
    "projectType",
    "capabilities",
    "brain",
    "prd",
    "features",
    "flows",
    "specifications",
    "components",
    "actions",
    "routes",
    "context",
]);
class TUIBrainService {
    constructor(projectRoot = process.cwd()) {
        this.projectRoot = projectRoot;
        this.brainPath = path.join(projectRoot, ".mycontext", "context.json");
        this.syncer = new ContextSyncer_1.ContextSyncer(projectRoot);
        this.history = new ExecutionHistory_1.ExecutionHistory(projectRoot);
    }
    async exists() {
        return fs.pathExists(this.brainPath);
    }
    async load() {
        if (!(await this.exists())) {
            throw new Error("Living Brain context.json not found");
        }
        return fs.readJson(this.brainPath);
    }
    async previewMutation(title, currentBrain, delta) {
        const errors = this.validateDelta(delta);
        if (errors.length > 0) {
            throw new Error(`Invalid Living Brain delta: ${errors.join("; ")}`);
        }
        const proposedBrain = this.mergeBrain(currentBrain, delta);
        const brainErrors = this.validateBrain(proposedBrain);
        if (brainErrors.length > 0) {
            throw new Error(`Invalid Living Brain result: ${brainErrors.join("; ")}`);
        }
        return {
            title,
            summary: this.summarizeDelta(delta),
            delta,
            proposedBrain,
        };
    }
    async applyMutation(preview) {
        const start = Date.now();
        const errors = this.validateBrain(preview.proposedBrain);
        if (errors.length > 0) {
            return { success: false, errors };
        }
        await fs.ensureDir(path.dirname(this.brainPath));
        await fs.writeJson(this.brainPath, preview.proposedBrain, { spaces: 2 });
        await this.syncer.refreshMarkdownViews(preview.proposedBrain);
        const historyId = await this.history.record({
            type: "brain-update",
            action: preview.title,
            params: { delta: preview.delta },
            result: { summary: preview.summary },
            status: "success",
            duration: Date.now() - start,
        });
        return { success: true, historyId, errors: [] };
    }
    validateDelta(delta) {
        const errors = [];
        const keys = Object.keys(delta);
        if (keys.length === 0) {
            errors.push("delta is empty");
        }
        for (const key of keys) {
            if (!ALLOWED_TOP_LEVEL_KEYS.has(key)) {
                errors.push(`top-level key "${key}" is not allowed`);
            }
        }
        if (Array.isArray(delta.features)) {
            for (const feature of delta.features) {
                if (!feature || typeof feature !== "object") {
                    errors.push("features entries must be objects");
                    continue;
                }
                for (const required of ["id", "name", "description", "priority", "dependencies"]) {
                    if (!(required in feature)) {
                        errors.push(`feature is missing "${required}"`);
                    }
                }
                if (feature.priority &&
                    !["high", "medium", "low"].includes(feature.priority)) {
                    errors.push(`feature "${feature.id || "unknown"}" has invalid priority`);
                }
                if (feature.dependencies && !Array.isArray(feature.dependencies)) {
                    errors.push(`feature "${feature.id || "unknown"}" dependencies must be an array`);
                }
            }
        }
        return errors;
    }
    validateBrain(brain) {
        const errors = [];
        if (!brain || typeof brain !== "object") {
            return ["brain must be an object"];
        }
        if (!brain.brain && !brain.metadata && !brain.project && !brain.prd) {
            errors.push("brain is missing recognizable project metadata");
        }
        if (brain.features && !Array.isArray(brain.features)) {
            errors.push("features must be an array");
        }
        if (Array.isArray(brain.features)) {
            const ids = new Set();
            for (const feature of brain.features) {
                if (!feature.id || ids.has(feature.id)) {
                    errors.push(`duplicate or missing feature id: ${feature.id || "unknown"}`);
                }
                ids.add(feature.id);
            }
        }
        return errors;
    }
    mergeBrain(target, delta) {
        const output = { ...target };
        for (const [key, value] of Object.entries(delta)) {
            if (key === "features" && Array.isArray(value)) {
                output.features = this.mergeById(output.features || [], value);
                continue;
            }
            if (this.isPlainObject(value) && this.isPlainObject(output[key])) {
                output[key] = this.mergeBrain(output[key], value);
            }
            else {
                output[key] = value;
            }
        }
        return output;
    }
    mergeById(existing, incoming) {
        const byId = new Map();
        for (const item of existing) {
            if (item?.id)
                byId.set(item.id, item);
        }
        for (const item of incoming) {
            if (!item?.id)
                continue;
            const current = byId.get(item.id) || {};
            byId.set(item.id, this.mergeBrain(current, item));
        }
        return Array.from(byId.values());
    }
    isPlainObject(value) {
        return !!value && typeof value === "object" && !Array.isArray(value);
    }
    summarizeDelta(delta) {
        const summary = [];
        if (Array.isArray(delta.features)) {
            for (const feature of delta.features) {
                summary.push(`Feature: ${feature.name || feature.id}`);
            }
        }
        const context = delta.context;
        const questionCount = context?.questions?.nodes?.length;
        if (typeof questionCount === "number") {
            summary.push(`Question graph: ${questionCount} total question(s)`);
        }
        for (const key of Object.keys(delta)) {
            if (key !== "features" && key !== "context") {
                summary.push(`Updated ${key}`);
            }
        }
        return summary.length > 0 ? summary : ["Living Brain metadata update"];
    }
}
exports.TUIBrainService = TUIBrainService;
//# sourceMappingURL=TUIBrainService.js.map