"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.ContextDriftAgent = void 0;
const AICore_1 = require("../../core/ai/AICore");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class ContextDriftAgent {
    constructor() {
        this.name = "ContextDriftAgent";
        this.description = "Detects code-to-brain drift by comparing implementation against Living Context specifications.";
        this.personality = "A vigilant architecture guardian who spots every deviation between code and specification.";
        this.llmProvider = "github-models";
        this.expertise = ["Architecture Validation", "Code Review", "Specification Compliance", "Drift Detection"];
    }
    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 {};
    }
    async run(input) {
        const context = this.getContextJson();
        const brain = context?.brain || {};
        const specs = context?.specs || [];
        const features = context?.features || [];
        const drifts = [];
        const targetFeatures = input.featureIds
            ? features.filter((f) => input.featureIds.includes(f.id))
            : features;
        for (const feature of targetFeatures) {
            if (feature.spec) {
                for (const [key, expected] of Object.entries(feature.spec)) {
                    drifts.push({
                        file: `context.json → features[${feature.id}].spec.${key}`,
                        severity: "medium",
                        expected: String(expected),
                        actual: "(not verified — requires code inspection)",
                        contextPath: `features[${feature.id}].spec.${key}`,
                        recommendation: `Verify implementation matches spec: ${key} = ${expected}`,
                    });
                }
            }
            if (feature.status === "completed" && feature.acceptanceCriteria) {
                drifts.push({
                    file: `features[${feature.id}]`,
                    severity: "low",
                    expected: `${feature.acceptanceCriteria.length} acceptance criteria met`,
                    actual: "Manual verification required",
                    contextPath: `features[${feature.id}].acceptanceCriteria`,
                    recommendation: "Run QA replay to validate acceptance criteria",
                });
            }
        }
        if (brain?.designSystem?.tokens) {
            drifts.push({
                file: "context.json → brain.designSystem.tokens",
                severity: "low",
                expected: `${Object.keys(brain.designSystem.tokens).length} tokens defined`,
                actual: "Scan codebase to verify token usage",
                contextPath: "brain.designSystem.tokens",
                recommendation: "Run `mycontext tidy` to scan token usage",
            });
        }
        const aiCore = this.getAICore();
        let summary = "";
        try {
            const result = await aiCore.generateStructuredText(`You are analyzing a drift report between a codebase and its Living Context.
Context has ${features.length} features, ${specs.length} specs.
${drifts.length} potential drifts were detected.
Write a 2-3 sentence executive summary.`, '{ "summary": "string" }');
            summary = result.summary;
        }
        catch {
            summary = `${drifts.length} potential drifts across ${targetFeatures.length} features. Manual review recommended for high-severity items.`;
        }
        return { total: drifts.length, drifts, summary };
    }
    async validate(input) {
        return true;
    }
}
exports.ContextDriftAgent = ContextDriftAgent;
//# sourceMappingURL=ContextDriftAgent.js.map