"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.QAReplayAgent = void 0;
const AICore_1 = require("../../core/ai/AICore");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class QAReplayAgent {
    constructor() {
        this.name = "QAReplayAgent";
        this.description = "Replays QA test sessions to validate feature regressions and acceptance criteria.";
        this.personality = "A disciplined QA automation engineer who never skips a test case.";
        this.llmProvider = "github-models";
        this.expertise = ["QA Automation", "Regression Testing", "Acceptance Validation", "Test Reporting"];
    }
    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 {};
    }
    getTestFiles() {
        const testDirs = [
            path.join(process.cwd(), "tests"),
            path.join(process.cwd(), "__tests__"),
            path.join(process.cwd(), "src", "__tests__"),
        ];
        const files = [];
        for (const dir of testDirs) {
            if (fs.pathExistsSync(dir)) {
                const walk = (d) => {
                    const entries = fs.readdirSync(d, { withFileTypes: true });
                    for (const entry of entries) {
                        const fullPath = path.join(d, entry.name);
                        if (entry.isDirectory())
                            walk(fullPath);
                        else if (entry.name.endsWith(".test.ts") || entry.name.endsWith(".spec.ts")) {
                            files.push(fullPath);
                        }
                    }
                };
                walk(dir);
            }
        }
        return files;
    }
    async run(input) {
        const context = this.getContextJson();
        const features = context?.features || [];
        const testFiles = this.getTestFiles();
        const results = [];
        let passed = 0;
        let failed = 0;
        const targetFeatures = input.featureIds
            ? features.filter((f) => input.featureIds.includes(f.id))
            : features;
        for (const feature of targetFeatures) {
            const criteria = feature.acceptanceCriteria || [];
            if (criteria.length === 0) {
                results.push({
                    id: `ac-${feature.id}-none`,
                    name: `${feature.name || feature.id}: no acceptance criteria`,
                    status: "skipped",
                    expected: "Acceptance criteria defined",
                    actual: "None found",
                    duration: 0,
                });
                continue;
            }
            for (let i = 0; i < criteria.length; i++) {
                const criterion = criteria[i];
                const testId = `ac-${feature.id}-${i}`;
                const matchingTests = testFiles.filter((f) => {
                    const content = fs.readFileSync(f, "utf-8");
                    return content.includes(feature.id) || content.includes(feature.name);
                });
                if (matchingTests.length > 0) {
                    passed++;
                    results.push({
                        id: testId,
                        name: criterion.substring(0, 60),
                        status: "pass",
                        expected: criterion,
                        actual: `Covered by ${matchingTests.length} test file(s)`,
                        duration: 0,
                    });
                }
                else {
                    failed++;
                    results.push({
                        id: testId,
                        name: criterion.substring(0, 60),
                        status: "fail",
                        expected: criterion,
                        actual: "No matching test found",
                        duration: 0,
                    });
                }
            }
        }
        const totalTests = results.length;
        const summary = `${passed}/${totalTests} acceptance criteria covered by tests. ${failed} gap(s) detected.`;
        return {
            totalTests,
            passed,
            failed,
            results,
            summary,
        };
    }
    async validate(input) {
        return true;
    }
}
exports.QAReplayAgent = QAReplayAgent;
//# sourceMappingURL=QAReplayAgent.js.map