"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.ConflictDetector = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class ConflictDetector {
    voteStorePath;
    constructor(cellDir) {
        this.voteStorePath = path.join(cellDir, 'team', 'votes.json');
    }
    detectConflicts(patterns) {
        const conflicts = [];
        const categoryMap = new Map();
        for (const pattern of patterns) {
            if (!categoryMap.has(pattern.category)) {
                categoryMap.set(pattern.category, []);
            }
            categoryMap.get(pattern.category).push(pattern);
        }
        for (const [, categoryPatterns] of categoryMap) {
            for (let i = 0; i < categoryPatterns.length; i++) {
                for (let j = i + 1; j < categoryPatterns.length; j++) {
                    const a = categoryPatterns[i];
                    const b = categoryPatterns[j];
                    if (a.from !== b.from || a.to !== b.to) {
                        if (a.confidence.mean > 0.5 && b.confidence.mean > 0.5) {
                            conflicts.push([a, b]);
                        }
                    }
                }
            }
        }
        return conflicts;
    }
    resolveConflict(patternA, patternB, bugData, codebaseStats, leadPreference) {
        if (bugData && bugData.patternA_bugs + bugData.patternB_bugs >= 30) {
            const winner = bugData.patternA_bugs <= bugData.patternB_bugs ? patternA : patternB;
            return {
                patternA,
                patternB,
                resolved: true,
                winner,
                resolutionMethod: 'data_driven',
                reason: `Lower bug rate: ${Math.min(bugData.patternA_bugs, bugData.patternB_bugs)} vs ${Math.max(bugData.patternA_bugs, bugData.patternB_bugs)} bugs`,
            };
        }
        if (codebaseStats) {
            const totalUsage = codebaseStats.patternA_usage + codebaseStats.patternB_usage;
            if (totalUsage > 0) {
                const aPct = codebaseStats.patternA_usage / totalUsage;
                if (aPct >= 0.6) {
                    return {
                        patternA,
                        patternB,
                        resolved: true,
                        winner: patternA,
                        resolutionMethod: 'codebase_majority',
                        reason: `${Math.round(aPct * 100)}% of codebase uses this pattern`,
                    };
                }
                if (aPct <= 0.4) {
                    return {
                        patternA,
                        patternB,
                        resolved: true,
                        winner: patternB,
                        resolutionMethod: 'codebase_majority',
                        reason: `${Math.round((1 - aPct) * 100)}% of codebase uses this pattern`,
                    };
                }
            }
        }
        if (leadPreference) {
            const winner = leadPreference === 'A' ? patternA : patternB;
            return {
                patternA,
                patternB,
                resolved: true,
                winner,
                resolutionMethod: 'lead_decision',
                reason: 'Team lead decided',
            };
        }
        return {
            patternA,
            patternB,
            resolved: false,
            winner: null,
            resolutionMethod: 'unresolved',
            reason: 'Requires team vote',
        };
    }
    createVote(patternA, patternB, totalMembers, durationHours = 48) {
        const session = {
            patternId: `${patternA.patternId}_vs_${patternB.patternId}`,
            title: `${patternA.description} vs ${patternB.description}`,
            optionA: patternA.description,
            optionB: patternB.description,
            votes: {},
            startedAt: new Date().toISOString(),
            deadline: new Date(Date.now() + durationHours * 3600000).toISOString(),
            quorum: Math.ceil(totalMembers * 0.5),
            totalMembers,
        };
        this.saveVoteSession(session);
        return session;
    }
    castVote(sessionId, username, vote) {
        const sessions = this.loadVoteSessions();
        const session = sessions.find((s) => s.patternId === sessionId);
        if (!session)
            return null;
        if (new Date(session.deadline) < new Date())
            return null;
        session.votes[username] = vote;
        this.saveAllSessions(sessions);
        return session;
    }
    tallyVote(session) {
        if (new Date(session.deadline) >= new Date()) {
            return { winner: null, resolved: false };
        }
        const votes = Object.values(session.votes);
        const totalVoted = votes.length;
        if (totalVoted < session.quorum) {
            return { winner: null, resolved: false };
        }
        const aVotes = votes.filter((v) => v === 'A').length;
        const bVotes = votes.filter((v) => v === 'B').length;
        if (aVotes > bVotes)
            return { winner: 'A', resolved: true };
        if (bVotes > aVotes)
            return { winner: 'B', resolved: true };
        return { winner: null, resolved: false };
    }
    getVoteStatus(session) {
        const votes = Object.values(session.votes);
        const totalVoted = votes.length;
        const hoursLeft = Math.max(0, Math.round((new Date(session.deadline).getTime() - Date.now()) / 3600000));
        return `Team vote open: ${session.title}. ${totalVoted}/${session.totalMembers} voted. ${hoursLeft}h left.`;
    }
    saveVoteSession(session) {
        const sessions = this.loadVoteSessions();
        const idx = sessions.findIndex((s) => s.patternId === session.patternId);
        if (idx >= 0) {
            sessions[idx] = session;
        }
        else {
            sessions.push(session);
        }
        this.saveAllSessions(sessions);
    }
    loadVoteSessions() {
        if (!fs.existsSync(this.voteStorePath))
            return [];
        try {
            return JSON.parse(fs.readFileSync(this.voteStorePath, 'utf-8'));
        }
        catch {
            return [];
        }
    }
    saveAllSessions(sessions) {
        const dir = path.dirname(this.voteStorePath);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }
        fs.writeFileSync(this.voteStorePath, JSON.stringify(sessions, null, 2), 'utf-8');
    }
}
exports.ConflictDetector = ConflictDetector;
//# sourceMappingURL=conflict-detector.js.map