"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.analyzeProject = analyzeProject;
exports.buildUserProfile = buildUserProfile;
exports.saveUserProfile = saveUserProfile;
exports.loadUserProfile = loadUserProfile;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const FEATURE_SIGNALS = [
    { feature: 'authentication', signals: { deps: ['passport', 'jsonwebtoken', 'jwt', 'bcrypt', 'auth0', 'next-auth', 'lucia', 'express-session', '@auth/core'] } },
    { feature: 'database', signals: { deps: ['pg', 'postgres', 'mysql', 'sqlite', 'mongodb', 'mongoose', 'prisma', 'drizzle', 'knex', 'sequelize', 'typeorm', 'redis', 'better-sqlite3'] } },
    { feature: 'api', signals: { deps: ['express', 'fastify', 'koa', 'hapi', 'hono', 'restify', '@nestjs/core', 'graphql', '@apollo/server', 'trpc'] } },
    { feature: 'ui', signals: { deps: ['react', 'vue', 'svelte', 'solid', 'preact', 'lit', 'next', 'nuxt', 'remix', 'astro'] } },
    { feature: 'validation', signals: { deps: ['zod', 'yup', 'joi', 'valibot', 'arktype'] } },
    { feature: 'testing', signals: { deps: ['jest', 'vitest', 'mocha', 'chai', 'playwright', 'cypress', 'ava', 'tap'] } },
    { feature: 'build-tool', signals: { deps: ['vite', 'webpack', 'parcel', 'rollup', 'esbuild', 'turbopack', 'tsup', 'swc'] } },
    { feature: 'styling', signals: { deps: ['tailwindcss', 'styled-components', 'emotion', 'sass', 'less', 'css-modules', 'panda', 'vanilla-extract', 'linaria', 'stitches'] } },
    { feature: 'state-management', signals: { deps: ['redux', 'mobx', 'zustand', 'jotai', 'recoil', 'pinia', 'xstate', '@tanstack/react-query', 'swr'] } },
    { feature: 'real-time', signals: { deps: ['socket.io', 'ws', 'pusher', 'ably', 'centrifugo', 'bullmq', 'mqtt'] } },
    { feature: 'background-jobs', signals: { deps: ['bullmq', 'bull', 'bee-queue', 'agenda', 'celery', 'sidekiq'] } },
    { feature: 'orm', signals: { deps: ['prisma', 'drizzle-orm', 'typeorm', 'sequelize', 'knex', 'mikro-orm'] } },
    { feature: 'logging', signals: { deps: ['winston', 'pino', 'bunyan', 'loglevel', 'consola'] } },
    { feature: 'monitoring', signals: { deps: ['sentry', '@sentry/node', 'datadog', 'newrelic', 'bugsnag', 'posthog'] } },
    { feature: 'ai-integration', signals: { deps: ['openai', 'anthropic', '@anthropic-ai/sdk', 'cohere-ai', 'langchain', 'llamaindex', 'ai', '@ai-sdk/openai', '@ai-sdk/anthropic'] } },
    { feature: 'email', signals: { deps: ['nodemailer', 'sendgrid', 'mailgun', 'resend', 'postmark', '@sendgrid/mail'] } },
    { feature: 'storage', signals: { deps: ['aws-sdk', '@aws-sdk/client-s3', 'multer', 'sharp', 'cloudinary', 'uploadthing'] } },
    { feature: 'payments', signals: { deps: ['stripe', 'razorpay', 'paypal', 'square', 'lemonsqueezy', 'paddle'] } },
    { feature: 'i18n', signals: { deps: ['i18next', 'next-intl', 'react-intl', 'lingui', '@formatjs/intl'] } },
    { feature: 'admin-panel', signals: { deps: ['adminjs', 'react-admin', 'payload', 'keystone', 'strapi', 'directus'] } },
    { feature: 'monorepo', signals: { deps: ['turbo', 'nx', 'lerna', 'rush', 'pnpm-workspace'] } },
    { feature: 'type-system', signals: { deps: ['typescript', 'zod', 'yup', 'valibot'] } },
    { feature: 'websocket', signals: { deps: ['socket.io', 'ws', 'graphql-ws', 'centrifugo'] } },
    { feature: 'caching', signals: { deps: ['redis', 'memcached', 'lru-cache', 'node-cache', 'keyv'] } },
    { feature: 'search', signals: { deps: ['elasticsearch', '@elastic/elasticsearch', 'meilisearch', 'algoliasearch', 'typesense', 'orama'] } },
    { feature: 'cli', signals: { deps: ['commander', 'yargs', 'oclif', 'inquirer', 'meow', 'cac'] } },
    { feature: 'desktop', signals: { deps: ['electron', 'tauri', 'neutralino'] } },
    { feature: 'mobile', signals: { deps: ['react-native', 'expo', '@capacitor/core', 'ionic', 'flutter'] } },
];
const FILE_SIGNALS = [
    { feature: 'authentication', patterns: [/[\\/](auth|login|signup|signin|session|token)[\\/]/i, /\b(auth|login|signup|signin)\.(ts|js|py|tsx|jsx)$/i] },
    { feature: 'database', patterns: [/[\\/](db|database|migrations|schema|models|entities)[\\/]/i, /\.(sql|prisma|db)$/i] },
    { feature: 'api', patterns: [/[\\/](api|routes|controllers|endpoints|handlers)[\\/]/i, /\b(route|controller|endpoint|handler)\.(ts|js|py)$/i] },
    { feature: 'ui', patterns: [/[\\/](components|pages|views|screens|app)[\\/]/i, /\.(tsx|jsx|vue|svelte)$/i] },
    { feature: 'testing', patterns: [/[\\/](test|tests|__tests__|spec|specs)[\\/]/i, /\.(test|spec)\.(ts|js|py|tsx|jsx)$/i] },
    { feature: 'background-jobs', patterns: [/[\\/](jobs|workers|queues|tasks|crons)[\\/]/i] },
    { feature: 'admin-panel', patterns: [/[\\/](admin|dashboard|backstage)[\\/]/i] },
    { feature: 'cli', patterns: [/[\\/](cli|bin|commands|scripts)[\\/]/i] },
    { feature: 'docs', patterns: [/\.(md|mdx|rst|txt)$/i, /[\\/](docs?|documentation)[\\/]/i] },
    { feature: 'docker', patterns: [/Dockerfile$/i, /docker-compose\.(yml|yaml)$/i] },
    { feature: 'ci-cd', patterns: [/[\\/](.github[\\/]workflows|\.circleci|\.gitlab-ci)[\\/]/i] },
];
function getStackPurpose(dep) {
    const map = {
        'express': 'web server',
        'fastify': 'web server',
        'koa': 'web server',
        '@nestjs/core': 'backend framework',
        'next': 'React framework',
        'react': 'UI library',
        'vue': 'UI framework',
        'typescript': 'type system',
        'zod': 'validation',
        'prisma': 'ORM',
        'drizzle-orm': 'ORM',
        'better-sqlite3': 'database driver',
        'pg': 'database driver',
        'mongoose': 'ODM',
        'vite': 'build tool',
        'webpack': 'build tool',
        'tailwindcss': 'CSS framework',
        'jest': 'test framework',
        'vitest': 'test framework',
        'playwright': 'e2e tests',
        'socket.io': 'real-time',
        'stripe': 'payments',
        'passport': 'auth',
        'jsonwebtoken': 'auth',
        'bcrypt': 'auth',
        'winston': 'logging',
        'pino': 'logging',
        'sentry': 'monitoring',
        'openai': 'AI integration',
        'anthropic': 'AI integration',
        'resend': 'email',
        'turbo': 'monorepo',
        'commander': 'CLI',
    };
    return map[dep] || 'library';
}
function detectLanguage(projectPath) {
    const hasTs = fs.existsSync(path.join(projectPath, 'tsconfig.json'));
    const hasJs = fs.existsSync(path.join(projectPath, 'package.json')) && !hasTs;
    const hasPy = fs.existsSync(path.join(projectPath, 'requirements.txt')) || fs.existsSync(path.join(projectPath, 'pyproject.toml'));
    const hasGo = fs.existsSync(path.join(projectPath, 'go.mod'));
    const langs = [hasTs && 'typescript', hasJs && 'javascript', hasPy && 'python', hasGo && 'go'].filter(Boolean);
    if (langs.length === 0)
        return 'unknown';
    if (langs.length > 1)
        return 'mixed';
    return langs[0];
}
function readPackageJson(projectPath) {
    const pkgPath = path.join(projectPath, 'package.json');
    if (!fs.existsSync(pkgPath))
        return { name: '', description: '', deps: {}, devDeps: {} };
    try {
        const j = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
        return {
            name: j.name || '',
            description: j.description || '',
            deps: j.dependencies || {},
            devDeps: j.devDependencies || {},
        };
    }
    catch {
        return { name: '', description: '', deps: {}, devDeps: {} };
    }
}
function readPythonDeps(projectPath) {
    const reqPath = path.join(projectPath, 'requirements.txt');
    if (!fs.existsSync(reqPath))
        return [];
    try {
        return fs.readFileSync(reqPath, 'utf-8')
            .split('\n')
            .map(line => line.trim())
            .filter(line => line && !line.startsWith('#'))
            .slice(0, 50)
            .map(line => {
            const m = line.match(/^([a-zA-Z0-9_.-]+)\s*([>=<~!\s\d.*]+)?/);
            return m ? { name: m[1], version: m[2]?.trim() || '*' } : { name: line, version: '*' };
        });
    }
    catch {
        return [];
    }
}
function detectFeatures(projectPath, pkg, pyDeps) {
    const allDeps = new Set([...Object.keys(pkg.deps), ...Object.keys(pkg.devDeps), ...pyDeps.map(d => d.name.toLowerCase())]);
    const features = new Set();
    for (const fs_signal of FEATURE_SIGNALS) {
        for (const dep of fs_signal.signals.deps || []) {
            if (allDeps.has(dep)) {
                features.add(fs_signal.feature);
                break;
            }
        }
    }
    const filesToCheck = [];
    function walk(dir, depth = 0) {
        if (depth > 5)
            return;
        if (filesToCheck.length > 500)
            return;
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const e of entries) {
            if (e.name === 'node_modules' || e.name.startsWith('.') || e.name === 'dist' || e.name === 'build')
                continue;
            const full = path.join(dir, e.name);
            if (e.isDirectory()) {
                walk(full, depth + 1);
            }
            else if (e.isFile()) {
                filesToCheck.push(full);
            }
        }
    }
    walk(projectPath);
    for (const fileSignal of FILE_SIGNALS) {
        for (const pattern of fileSignal.patterns) {
            if (filesToCheck.some(f => pattern.test(f))) {
                features.add(fileSignal.feature);
                break;
            }
        }
    }
    const hasDocker = filesToCheck.some(f => /Dockerfile$|docker-compose\.(yml|yaml)$/i.test(f));
    const hasCI = filesToCheck.some(f => /\.github[\\/]workflows[\\/]|\.circleci|\.gitlab-ci/.test(f));
    return { features: Array.from(features), hasDocker, hasCI };
}
function countSize(projectPath) {
    let files = 0;
    let lines = 0;
    const exts = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.go']);
    function walk(dir, depth = 0) {
        if (depth > 6)
            return;
        if (files > 5000)
            return;
        let entries;
        try {
            entries = fs.readdirSync(dir, { withFileTypes: true });
        }
        catch {
            return;
        }
        for (const e of entries) {
            if (e.name === 'node_modules' || e.name.startsWith('.') || e.name === 'dist' || e.name === 'build' || e.name === 'coverage')
                continue;
            const full = path.join(dir, e.name);
            if (e.isDirectory()) {
                walk(full, depth + 1);
            }
            else if (e.isFile()) {
                const ext = path.extname(e.name).toLowerCase();
                if (exts.has(ext)) {
                    files++;
                    try {
                        const content = fs.readFileSync(full, 'utf-8');
                        lines += content.split('\n').length;
                    }
                    catch { }
                }
            }
        }
    }
    walk(projectPath);
    return { files, lines };
}
function analyzeProject(projectPath) {
    const pkg = readPackageJson(projectPath);
    const pyDeps = readPythonDeps(projectPath);
    const { features, hasDocker, hasCI } = detectFeatures(projectPath, pkg, pyDeps);
    const size = countSize(projectPath);
    const stack = [];
    for (const [name, version] of Object.entries(pkg.deps)) {
        stack.push({ name, version: version.replace(/^[\^~]/, ''), purpose: getStackPurpose(name) });
    }
    for (const dep of pyDeps.slice(0, 20)) {
        stack.push({ name: dep.name, version: dep.version, purpose: getStackPurpose(dep.name) });
    }
    return {
        name: pkg.name || path.basename(projectPath),
        path: projectPath,
        description: pkg.description || '',
        language: detectLanguage(projectPath),
        stack,
        features,
        hasTests: features.includes('testing'),
        hasCI,
        hasDocker,
        hasAuth: features.includes('authentication'),
        hasDatabase: features.includes('database') || features.includes('orm'),
        hasAPI: features.includes('api'),
        hasUI: features.includes('ui'),
        hasWebSocket: features.includes('websocket') || features.includes('real-time'),
        size,
    };
}
function extractProductBase(name) {
    const cleaned = name.replace(/\s*-\s*Copy\s*$/i, '');
    const m = cleaned.match(/^([A-Za-z][A-Za-z0-9]+?)(?:-V\d+|-Old|-cell-|-cell|-Connect|-Web|DOC|-DOC|-WEB|-RESEARCH|$)/);
    if (m)
        return m[1];
    const words = cleaned.split(/[\s\-_]+/);
    if (words[0] && /^[A-Z]/.test(words[0]))
        return words[0];
    return cleaned;
}
function extractVersion(name) {
    const m = name.match(/-V(\d+)/);
    if (m)
        return `V${m[1]}`;
    if (/-RESEARCH$/i.test(name))
        return 'RESEARCH';
    if (/-Old$/i.test(name))
        return 'OLD';
    if (/-Copy$/i.test(name))
        return 'COPY';
    if (/-cell-/.test(name) || /-cell$/.test(name))
        return 'CELL';
    if (/-Connect$/.test(name))
        return 'CONNECT';
    if (/-Web$/.test(name))
        return 'WEB';
    if (/ DOC$/i.test(name))
        return 'DOC';
    if (/-cloud$/.test(name))
        return 'CLOUD';
    return 'main';
}
function latestVersion(versions) {
    const numericVersions = versions
        .map(v => {
        const m = v.match(/^V(\d+)$/);
        return m ? { v, n: parseInt(m[1]) } : null;
    })
        .filter(Boolean);
    if (numericVersions.length > 0) {
        return numericVersions.sort((a, b) => b.n - a.n)[0].v;
    }
    return versions[0] || 'main';
}
function buildUserProfile(rootDir) {
    const entries = fs.readdirSync(rootDir, { withFileTypes: true });
    const projectDirs = entries
        .filter(e => e.isDirectory() && !e.name.startsWith('.'))
        .map(e => path.join(rootDir, e.name));
    const projects = projectDirs
        .filter(p => fs.existsSync(path.join(p, 'package.json')) || fs.existsSync(path.join(p, 'requirements.txt')) || fs.existsSync(path.join(p, 'go.mod')) || fs.statSync(p).isDirectory())
        .map(analyzeProject);
    const familyMap = new Map();
    for (const p of projects) {
        const base = extractProductBase(path.basename(p.path));
        if (!familyMap.has(base))
            familyMap.set(base, []);
        familyMap.get(base).push(p);
    }
    const products = [];
    for (const [name, projs] of familyMap) {
        const versions = projs.map(p => extractVersion(path.basename(p.path)));
        const descCounts = new Map();
        for (const p of projs) {
            if (p.description) {
                const key = p.description.split(/[.!?]/)[0].trim().slice(0, 80);
                if (key)
                    descCounts.set(key, (descCounts.get(key) || 0) + 1);
            }
        }
        const description = Array.from(descCounts.entries()).sort((a, b) => b[1] - a[1])[0]?.[0] || projs[0]?.description?.split(/[.!?]/)[0] || '';
        const stackCounts = new Map();
        for (const p of projs) {
            for (const s of p.stack) {
                stackCounts.set(s.name, (stackCounts.get(s.name) || 0) + 1);
            }
        }
        const commonStack = Array.from(stackCounts.entries())
            .map(([n, c]) => ({ name: n, count: c }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 10);
        const featureCounts = new Map();
        for (const p of projs) {
            for (const f of p.features) {
                featureCounts.set(f, (featureCounts.get(f) || 0) + 1);
            }
        }
        const commonFeatures = Array.from(featureCounts.entries())
            .filter(([_, c]) => c >= Math.max(2, Math.floor(projs.length * 0.4)))
            .map(([n, c]) => ({ name: n, projectCount: c, confidence: c / projs.length }))
            .sort((a, b) => b.confidence - a.confidence);
        products.push({
            name,
            projects: projs.map(p => path.basename(p.path)),
            versions,
            latestVersion: latestVersion(versions),
            description,
            commonStack,
            commonFeatures: commonFeatures.map(f => f.name),
            evolution: projs
                .filter(p => p.description)
                .map(p => `${path.basename(p.path)}: ${p.description.split(/[.!?]/)[0].trim()}`)
                .slice(0, 5),
        });
    }
    const stackAcrossAll = new Map();
    const featureAcrossAll = new Map();
    for (const p of projects) {
        for (const s of p.stack) {
            stackAcrossAll.set(s.name, (stackAcrossAll.get(s.name) || 0) + 1);
        }
        for (const f of p.features) {
            featureAcrossAll.set(f, (featureAcrossAll.get(f) || 0) + 1);
        }
    }
    const goToStack = Array.from(stackAcrossAll.entries())
        .filter(([_, c]) => c >= Math.max(2, Math.floor(projects.length * 0.3)))
        .map(([name, count]) => ({
        name,
        confidence: count / projects.length,
        reason: `Used in ${count}/${projects.length} of your projects`,
    }))
        .sort((a, b) => b.confidence - a.confidence)
        .slice(0, 15);
    const commonFeatures = Array.from(featureAcrossAll.entries())
        .filter(([_, c]) => c >= Math.max(2, Math.floor(projects.length * 0.3)))
        .map(([name, count]) => ({
        name,
        projectCount: count,
        confidence: count / projects.length,
    }))
        .sort((a, b) => b.confidence - a.confidence);
    const COMMON_BUT_MISSING = [
        { name: 'payments', deps: ['stripe', 'razorpay', 'paypal'] },
        { name: 'i18n', deps: ['i18next', 'next-intl'] },
        { name: 'email', deps: ['resend', 'nodemailer', 'sendgrid'] },
        { name: 'background-jobs', deps: ['bullmq', 'bull', 'celery'] },
        { name: 'real-time', deps: ['socket.io', 'ws'] },
        { name: 'admin-panel', deps: ['adminjs', 'react-admin', 'payload'] },
        { name: 'mobile', deps: ['react-native', 'expo', 'tauri'] },
        { name: 'caching', deps: ['redis', 'memcached'] },
        { name: 'search', deps: ['meilisearch', 'algoliasearch', 'orama'] },
        { name: 'monitoring', deps: ['sentry', 'posthog', 'datadog'] },
        { name: 'cli', deps: ['commander', 'yargs', 'oclif'] },
        { name: 'docker', deps: ['docker-compose.yml', 'Dockerfile'] },
        { name: 'ci-cd', deps: ['.github/workflows'] },
    ];
    const missingFeatures = [];
    for (const cand of COMMON_BUT_MISSING) {
        const usedIn = cand.deps.filter(d => stackAcrossAll.has(d) || [...stackAcrossAll.keys()].some(k => k === d)).length;
        if (usedIn === 0) {
            const suggestions = {
                'payments': "Agar tu SaaS banata hai to Stripe/Razorpay add kar — Fivo/PULSE ke paid tiers ke liye zaroori.",
                'i18n': "Tere products global scale pe hain (Fivo + PULSE). i18n add karna hai to ab soch.",
                'email': "Kisi bhi product me transactional email (welcome, password reset) chahiye hote hain — Resend easy hai.",
                'background-jobs': "Tere long-running tasks ke liye BullMQ/Redis add kar.",
                'real-time': "Fivo-Connect jaisa data gateway real-time events se aur strong hoga.",
                'admin-panel': "Backend hai to admin panel (Payload/AdminJS) banao — customer ko dashboard dena hota hai.",
                'mobile': "Web pe strong ho, ab mobile pe jao (Expo/React Native).",
                'caching': "Performance ke liye Redis caching add kar.",
                'search': "Users ko fast search chahiye — Meilisearch easy hai.",
                'monitoring': "Production crash hote hain, Sentry se pakdo.",
                'cli': "Agar developer-facing tool hai to CLI banao (commander.js).",
                'docker': "Deployment easy karne ke liye Dockerfile add kar.",
                'ci-cd': "GitHub Actions se auto-test + auto-deploy set kar.",
            };
            missingFeatures.push({
                name: cand.name,
                reason: `None of your ${projects.length} projects use this`,
                suggestion: suggestions[cand.name] || 'Consider adding this to your next project.',
            });
        }
    }
    return {
        name: '',
        products: products.sort((a, b) => b.projects.length - a.projects.length),
        goToStack,
        commonFeatures,
        missingFeatures: missingFeatures.slice(0, 8),
        workStyle: {
            isSolo: projects.length === 1 || !projects.some(p => p.hasCI),
            doesRAndD: products.some(p => p.versions.includes('RESEARCH') || p.versions.includes('OLD')),
            shipsVersions: products.some(p => p.versions.filter(v => /^V\d+/.test(v)).length >= 2),
            buildsCloud: projects.some(p => /cloud/i.test(p.name) || p.features.includes('authentication') && p.features.includes('database')),
            buildsWeb: projects.some(p => /web|site|landing/i.test(p.name) || p.features.includes('ui')),
        },
        generatedAt: new Date().toISOString(),
    };
}
function saveUserProfile(profile) {
    const dir = path.join(os.homedir(), '.fivo', 'cell');
    if (!fs.existsSync(dir))
        fs.mkdirSync(dir, { recursive: true });
    const filePath = path.join(dir, 'user-profile.json');
    fs.writeFileSync(filePath, JSON.stringify(profile, null, 2), 'utf-8');
    const mdPath = path.join(dir, 'user-profile.md');
    const md = renderUserProfileMd(profile);
    fs.writeFileSync(mdPath, md, 'utf-8');
    return filePath;
}
function loadUserProfile() {
    const filePath = path.join(os.homedir(), '.fivo', 'cell', 'user-profile.json');
    if (!fs.existsSync(filePath))
        return null;
    try {
        return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    catch {
        return null;
    }
}
function renderUserProfileMd(p) {
    const lines = [];
    lines.push('# 🧠 FIVO Cell — Your Profile');
    lines.push('');
    lines.push(`> Generated: ${p.generatedAt}`);
    lines.push('');
    lines.push('## 🏷️ Your Products');
    lines.push('');
    for (const prod of p.products) {
        lines.push(`### ${prod.name} (${prod.projects.length} projects, latest: ${prod.latestVersion})`);
        lines.push('');
        if (prod.description)
            lines.push(`> ${prod.description}`);
        lines.push('');
        lines.push(`- **Projects**: ${prod.projects.join(', ')}`);
        if (prod.commonStack.length > 0) {
            lines.push(`- **Stack**: ${prod.commonStack.slice(0, 6).map(s => s.name).join(', ')}`);
        }
        if (prod.commonFeatures.length > 0) {
            lines.push(`- **Features**: ${prod.commonFeatures.join(', ')}`);
        }
        if (prod.evolution.length > 0) {
            lines.push('');
            lines.push('**Evolution:**');
            for (const e of prod.evolution)
                lines.push(`- ${e}`);
        }
        lines.push('');
    }
    lines.push('## 📦 Your Go-To Stack');
    lines.push('');
    for (const s of p.goToStack) {
        lines.push(`- **${s.name}** — ${s.reason} (${Math.round(s.confidence * 100)}% confidence)`);
    }
    lines.push('');
    lines.push('## ✨ Features you build in every project');
    lines.push('');
    for (const f of p.commonFeatures) {
        lines.push(`- **${f.name}** — ${f.projectCount} projects (${Math.round(f.confidence * 100)}% match)`);
    }
    lines.push('');
    lines.push('## 💡 Features you might want to add');
    lines.push('');
    for (const m of p.missingFeatures) {
        lines.push(`### ${m.name}`);
        lines.push(`> ${m.reason}`);
        lines.push('');
        lines.push(m.suggestion);
        lines.push('');
    }
    return lines.join('\n');
}
//# sourceMappingURL=user-intelligence.js.map