"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.createPackage = createPackage;
exports.getPackage = getPackage;
exports.getAllPackages = getAllPackages;
exports.searchPackages = searchPackages;
exports.downloadPackage = downloadPackage;
exports.ratePackage = ratePackage;
exports.getReviews = getReviews;
exports.getMarketplaceStats = getMarketplaceStats;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const PKG_DIR = path.join(os.homedir(), '.fivo', 'cell', 'marketplace');
const reviews = [];
function ensureDir() { if (!fs.existsSync(PKG_DIR))
    fs.mkdirSync(PKG_DIR, { recursive: true }); }
function pkgPath(id) { return path.join(PKG_DIR, `${id.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); }
function createPackage(data) {
    ensureDir();
    const pkg = {
        ...data,
        id: data.name.toLowerCase().replace(/[^a-z0-9-]/g, '-'),
        version: 1,
        rating: 0,
        ratingCount: 0,
        downloads: 0,
        createdAt: Date.now(),
        updatedAt: Date.now(),
    };
    fs.writeFileSync(pkgPath(pkg.id), JSON.stringify(pkg, null, 2), 'utf-8');
    return pkg;
}
function getPackage(id) {
    try {
        const fp = pkgPath(id);
        return fs.existsSync(fp) ? JSON.parse(fs.readFileSync(fp, 'utf-8')) : null;
    }
    catch {
        return null;
    }
}
function getAllPackages() {
    ensureDir();
    try {
        return fs.readdirSync(PKG_DIR).filter((f) => f.endsWith('.json'))
            .map((f) => { try {
            return JSON.parse(fs.readFileSync(path.join(PKG_DIR, f), 'utf-8'));
        }
        catch {
            return null;
        } })
            .filter((p) => p !== null);
    }
    catch {
        return [];
    }
}
function searchPackages(query) {
    const q = query.toLowerCase();
    return getAllPackages().filter((p) => p.name.toLowerCase().includes(q) || p.description.toLowerCase().includes(q) || p.tags.some((t) => t.includes(q)));
}
function downloadPackage(id) {
    const pkg = getPackage(id);
    if (pkg) {
        pkg.downloads++;
        fs.writeFileSync(pkgPath(id), JSON.stringify(pkg, null, 2), 'utf-8');
    }
    return pkg;
}
function ratePackage(packageId, author, rating, comment) {
    if (rating < 1 || rating > 5)
        return null;
    const pkg = getPackage(packageId);
    if (!pkg)
        return null;
    pkg.rating = ((pkg.rating * pkg.ratingCount) + rating) / (pkg.ratingCount + 1);
    pkg.ratingCount++;
    if (comment)
        reviews.push({ packageId, author, rating, comment, createdAt: Date.now() });
    fs.writeFileSync(pkgPath(packageId), JSON.stringify(pkg, null, 2), 'utf-8');
    return pkg;
}
function getReviews(packageId) {
    return reviews.filter((r) => r.packageId === packageId);
}
function getMarketplaceStats() {
    const pkgs = getAllPackages();
    const tagCount = new Map();
    for (const p of pkgs) {
        for (const t of p.tags)
            tagCount.set(t, (tagCount.get(t) || 0) + 1);
    }
    return {
        totalPackages: pkgs.length,
        totalDownloads: pkgs.reduce((s, p) => s + p.downloads, 0),
        topTags: Array.from(tagCount.entries()).sort((a, b) => b[1] - a[1]).slice(0, 20).map(([tag, count]) => ({ tag, count })),
    };
}
//# sourceMappingURL=marketplace.js.map