"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MutationLogger = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const diff_1 = require("diff");
const chalk_1 = __importDefault(require("chalk"));
class MutationLogger {
    constructor(contextDir) {
        this.mutationsDir = path_1.default.join(contextDir, ".mycontext", "mutations");
        this.ensureMutationsDir();
    }
    ensureMutationsDir() {
        if (!fs_1.default.existsSync(this.mutationsDir)) {
            fs_1.default.mkdirSync(this.mutationsDir, { recursive: true });
        }
    }
    getComponentMutationsDir(componentName) {
        const componentDir = path_1.default.join(this.mutationsDir, componentName);
        if (!fs_1.default.existsSync(componentDir)) {
            fs_1.default.mkdirSync(componentDir, { recursive: true });
        }
        return componentDir;
    }
    generateMutationId() {
        const timestamp = Date.now();
        const random = Math.random().toString(36).substring(2, 8);
        return `mutation-${timestamp}-${random}`;
    }
    async logMutation(mutation) {
        const id = this.generateMutationId();
        const timestamp = new Date().toISOString();
        const fullMutation = {
            ...mutation,
            id,
            timestamp,
        };
        const componentDir = this.getComponentMutationsDir(mutation.componentPath);
        const mutationFile = path_1.default.join(componentDir, `${id}.json`);
        fs_1.default.writeFileSync(mutationFile, JSON.stringify(fullMutation, null, 2));
        console.log(chalk_1.default.green(`✅ Mutation logged: ${id}`));
        return id;
    }
    async getMutationHistory(componentPath) {
        const componentDir = this.getComponentMutationsDir(componentPath);
        if (!fs_1.default.existsSync(componentDir)) {
            return [];
        }
        const files = fs_1.default
            .readdirSync(componentDir)
            .filter((file) => file.endsWith(".json"))
            .sort();
        const mutations = [];
        for (const file of files) {
            try {
                const content = fs_1.default.readFileSync(path_1.default.join(componentDir, file), "utf8");
                const mutation = JSON.parse(content);
                mutations.push(mutation);
            }
            catch (error) {
                console.warn(chalk_1.default.yellow(`⚠️  Failed to parse mutation file: ${file}`));
            }
        }
        return mutations;
    }
    async getLastApprovedVersion(componentPath) {
        const mutations = await this.getMutationHistory(componentPath);
        // Find the most recent applied mutation
        const appliedMutations = mutations
            .filter((m) => m.status === "applied")
            .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
        return appliedMutations[0] || null;
    }
    async getLastProposedVersion(componentPath) {
        const mutations = await this.getMutationHistory(componentPath);
        // Find the most recent proposed mutation
        const proposedMutations = mutations
            .filter((m) => m.status === "proposed")
            .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
        return proposedMutations[0] || null;
    }
    async updateMutationStatus(mutationId, status, reason) {
        const mutations = await this.getAllMutations();
        const mutation = mutations.find((m) => m.id === mutationId);
        if (!mutation) {
            throw new Error(`Mutation ${mutationId} not found`);
        }
        mutation.status = status;
        if (status === "applied") {
            mutation.appliedAt = new Date().toISOString();
        }
        else if (status === "rejected") {
            mutation.rejectedAt = new Date().toISOString();
            mutation.rejectionReason = reason;
        }
        const componentDir = this.getComponentMutationsDir(mutation.componentPath);
        const mutationFile = path_1.default.join(componentDir, `${mutationId}.json`);
        fs_1.default.writeFileSync(mutationFile, JSON.stringify(mutation, null, 2));
        console.log(chalk_1.default.green(`✅ Mutation ${mutationId} status updated to: ${status}`));
    }
    async getAllMutations() {
        if (!fs_1.default.existsSync(this.mutationsDir)) {
            return [];
        }
        const allMutations = [];
        const componentDirs = fs_1.default.readdirSync(this.mutationsDir);
        for (const componentDir of componentDirs) {
            const componentPath = path_1.default.join(this.mutationsDir, componentDir);
            if (fs_1.default.statSync(componentPath).isDirectory()) {
                const mutations = await this.getMutationHistory(componentDir);
                allMutations.push(...mutations);
            }
        }
        return allMutations;
    }
    async createMutationFromRefinement(componentPath, before, after, chainOfThought, confidence, riskFlags = []) {
        const diff = (0, diff_1.createPatch)(componentPath, before, after);
        const mutation = {
            componentPath,
            actor: "ai",
            before,
            after,
            diff,
            patch: diff,
            chainOfThought,
            confidence,
            riskFlags,
            tests: {
                unit: [],
                lint: [],
                typecheck: [],
                results: {
                    unit: { passed: 0, failed: 0, details: [] },
                    lint: { passed: false, details: [] },
                    typecheck: { passed: false, details: [] },
                },
            },
            status: "proposed",
        };
        return await this.logMutation(mutation);
    }
    async getMutationById(mutationId) {
        const mutations = await this.getAllMutations();
        return mutations.find((m) => m.id === mutationId) || null;
    }
    async deleteMutation(mutationId) {
        const mutations = await this.getAllMutations();
        const mutation = mutations.find((m) => m.id === mutationId);
        if (!mutation) {
            throw new Error(`Mutation ${mutationId} not found`);
        }
        const componentDir = this.getComponentMutationsDir(mutation.componentPath);
        const mutationFile = path_1.default.join(componentDir, `${mutationId}.json`);
        if (fs_1.default.existsSync(mutationFile)) {
            fs_1.default.unlinkSync(mutationFile);
            console.log(chalk_1.default.green(`✅ Mutation ${mutationId} deleted`));
        }
    }
}
exports.MutationLogger = MutationLogger;
//# sourceMappingURL=MutationLogger.js.map