"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.getOrCreateProfile = getOrCreateProfile;
exports.recordContribution = recordContribution;
exports.getProfile = getProfile;
exports.getLeaderboard = getLeaderboard;
exports.getAllBadges = getAllBadges;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const REP_DIR = path.join(os.homedir(), '.fivo', 'cell', 'reputation');
const profiles = new Map();
function ensureDir() { if (!fs.existsSync(REP_DIR))
    fs.mkdirSync(REP_DIR, { recursive: true }); }
function profilePath(deviceId) {
    return path.join(REP_DIR, `${deviceId.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`);
}
function loadProfile(deviceId) {
    try {
        const fp = profilePath(deviceId);
        if (!fs.existsSync(fp))
            return null;
        return JSON.parse(fs.readFileSync(fp, 'utf-8'));
    }
    catch {
        return null;
    }
}
function saveProfile(profile) {
    ensureDir();
    fs.writeFileSync(profilePath(profile.deviceId), JSON.stringify(profile, null, 2), 'utf-8');
    profiles.set(profile.deviceId, profile);
}
function getTier(score) {
    if (score >= 10000)
        return 'diamond';
    if (score >= 5000)
        return 'platinum';
    if (score >= 2000)
        return 'gold';
    if (score >= 500)
        return 'silver';
    return 'bronze';
}
const ALL_BADGES = [
    { id: 'first_accept', name: 'First Acceptance', description: 'Accepted your first pattern suggestion', icon: '🌟', earnedAt: 0 },
    { id: 'ten_accepts', name: 'Pattern Pro', description: 'Accepted 10 patterns', icon: '⭐', earnedAt: 0 },
    { id: 'hundred_accepts', name: 'Century Club', description: 'Accepted 100 patterns', icon: '💯', earnedAt: 0 },
    { id: 'contributor', name: 'Contributor', description: 'Shared a pattern with the community', icon: '🤝', earnedAt: 0 },
    { id: 'team_player', name: 'Team Player', description: 'Joined a team', icon: '👥', earnedAt: 0 },
    { id: 'consistency', name: 'Consistency King', description: 'Active for 30 consecutive days', icon: '🔥', earnedAt: 0 },
    { id: 'diversity', name: 'Language Master', description: 'Contributed patterns in 5+ languages', icon: '🌐', earnedAt: 0 },
    { id: 'expert_typescript', name: 'TypeScript Expert', description: 'Top contributor in TypeScript patterns', icon: '📘', earnedAt: 0, category: 'typescript' },
    { id: 'expert_python', name: 'Python Expert', description: 'Top contributor in Python patterns', icon: '🐍', earnedAt: 0, category: 'python' },
];
function getOrCreateProfile(deviceId, displayName) {
    const existing = loadProfile(deviceId);
    if (existing)
        return existing;
    const profile = {
        deviceId,
        displayName: displayName || `dev-${deviceId.slice(0, 8)}`,
        tier: 'bronze',
        score: 0,
        totalContributions: 0,
        acceptedPatterns: 0,
        categoryStrengths: [],
        badges: [],
        joinedAt: Date.now(),
        updatedAt: Date.now(),
    };
    saveProfile(profile);
    return profile;
}
function recordContribution(deviceId, data) {
    let profile = getOrCreateProfile(deviceId);
    profile.totalContributions++;
    if (data.accepted)
        profile.acceptedPatterns++;
    const points = data.accepted ? 10 : 2;
    profile.score += points;
    if (data.category) {
        const existing = profile.categoryStrengths.find((c) => c.category === data.category);
        if (existing) {
            existing.score += points;
        }
        else {
            profile.categoryStrengths.push({ category: data.category, score: points, rank: 0 });
        }
        profile.categoryStrengths.sort((a, b) => b.score - a.score);
        profile.categoryStrengths.forEach((c, i) => { c.rank = i + 1; });
    }
    // Check badges
    const earnedBadgeIds = new Set(profile.badges.map((b) => b.id));
    if (profile.acceptedPatterns >= 1 && !earnedBadgeIds.has('first_accept')) {
        profile.badges.push({ ...ALL_BADGES.find((b) => b.id === 'first_accept'), earnedAt: Date.now() });
    }
    if (profile.acceptedPatterns >= 10 && !earnedBadgeIds.has('ten_accepts')) {
        profile.badges.push({ ...ALL_BADGES.find((b) => b.id === 'ten_accepts'), earnedAt: Date.now() });
    }
    if (profile.acceptedPatterns >= 100 && !earnedBadgeIds.has('hundred_accepts')) {
        profile.badges.push({ ...ALL_BADGES.find((b) => b.id === 'hundred_accepts'), earnedAt: Date.now() });
    }
    profile.tier = getTier(profile.score);
    profile.updatedAt = Date.now();
    saveProfile(profile);
    return profile;
}
function getProfile(deviceId) {
    return loadProfile(deviceId);
}
function getLeaderboard(limit = 20) {
    ensureDir();
    try {
        const files = fs.readdirSync(REP_DIR).filter((f) => f.endsWith('.json'));
        const all = [];
        for (const f of files) {
            try {
                const p = JSON.parse(fs.readFileSync(path.join(REP_DIR, f), 'utf-8'));
                all.push({
                    deviceId: p.deviceId,
                    displayName: p.displayName,
                    score: p.score,
                    tier: p.tier,
                    totalContributions: p.totalContributions,
                    topCategory: p.categoryStrengths[0]?.category || 'uncategorized',
                });
            }
            catch { }
        }
        return all.sort((a, b) => b.score - a.score).slice(0, limit);
    }
    catch {
        return [];
    }
}
function getAllBadges() {
    return ALL_BADGES;
}
//# sourceMappingURL=reputation.js.map