"use strict";
/**
 * 📊 STACKTISTICS - Stack Discovery & Collection
 * Powered by TURBO-CAT intelligence catalyst
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StacktisticsEngine = void 0;
exports.listStacks = listStacks;
exports.scanCurrentProject = scanCurrentProject;
exports.exportForGallery = exportForGallery;
const fs_1 = require("fs");
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
const turbo_cat_1 = require("../utils/turbo-cat");
const color_utils_1 = require("../utils/color-utils");
class StacktisticsEngine {
    stacksDir;
    discoveredPath;
    constructor() {
        this.stacksDir = path_1.default.join(os_1.default.homedir(), '.faf', 'stacktistics');
        this.discoveredPath = path_1.default.join(this.stacksDir, 'discovered.json');
    }
    /**
     * Ensure stacktistics directory exists
     */
    async ensureStacksDir() {
        try {
            await fs_1.promises.mkdir(this.stacksDir, { recursive: true });
        }
        catch {
            // Directory already exists
        }
    }
    /**
     * Scan current project and discover stack
     */
    async scanProject(projectPath = process.cwd()) {
        const turboCat = new turbo_cat_1.TurboCat();
        const analysis = await turboCat.discoverFormats(projectPath);
        if (!analysis.stackSignature || analysis.stackSignature === 'unknown-stack') {
            return null;
        }
        // Generate human-readable name from signature
        const name = this.generateStackName(analysis.stackSignature);
        const stackSig = {
            id: analysis.stackSignature,
            name,
            signature: analysis.stackSignature,
            detectedAt: new Date(),
            projectPath,
            frameworks: Object.keys(analysis.frameworkConfidence),
            confidence: Math.min(analysis.totalIntelligenceScore, 100)
        };
        return stackSig;
    }
    /**
     * Generate human-readable stack name
     */
    generateStackName(signature) {
        // Simple name generation - can be enhanced later
        const nameMap = {
            'next-tailwind-vercel': 'The Vercel Speedster',
            'svelte5-tailwind': 'Svelte 5 Reactive',
            'fastapi-postgres': 'Python API Master',
            'fastapi-sqlite': 'FastAPI Lightweight',
            'node-express-ts': 'Node.js TypeScript Classic'
        };
        return nameMap[signature] || signature.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' + ');
    }
    /**
     * Add stack to personal collection
     */
    async collectStack(stack) {
        await this.ensureStacksDir();
        let discovered = [];
        try {
            const data = await fs_1.promises.readFile(this.discoveredPath, 'utf-8');
            discovered = JSON.parse(data);
        }
        catch {
            // File doesn't exist yet
        }
        // Check if already collected
        const existing = discovered.find(s => s.id === stack.id);
        if (!existing) {
            discovered.push(stack);
            await fs_1.promises.writeFile(this.discoveredPath, JSON.stringify(discovered, null, 2));
        }
    }
    /**
     * Get discovered stacks
     */
    async getDiscoveredStacks() {
        try {
            const data = await fs_1.promises.readFile(this.discoveredPath, 'utf-8');
            return JSON.parse(data);
        }
        catch {
            return [];
        }
    }
}
exports.StacktisticsEngine = StacktisticsEngine;
/**
 * List discovered stacks
 */
async function listStacks() {
    const engine = new StacktisticsEngine();
    const stacks = await engine.getDiscoveredStacks();
    if (stacks.length === 0) {
        console.log(color_utils_1.colors.info('📊 No stacks discovered yet!'));
        console.log(color_utils_1.colors.dim('   Run: faf stacks --scan to discover your current project stack'));
        return;
    }
    console.log(color_utils_1.colors.highlight(`📊 Discovered Stacks (${stacks.length})`));
    console.log('');
    stacks.forEach((stack, index) => {
        console.log(`${color_utils_1.colors.highlight(`${index + 1}.`)} ${color_utils_1.colors.success(stack.name)}`);
        console.log(`   ${color_utils_1.colors.dim('Signature:')} ${stack.signature}`);
        console.log(`   ${color_utils_1.colors.dim('Frameworks:')} ${stack.frameworks.join(', ')}`);
        console.log(`   ${color_utils_1.colors.dim('Confidence:')} ${stack.confidence}%`);
        console.log('');
    });
}
/**
 * Scan and discover current project stack
 */
async function scanCurrentProject() {
    console.log(color_utils_1.colors.info('🔍 Scanning project for stack signature...'));
    const engine = new StacktisticsEngine();
    const stack = await engine.scanProject();
    if (!stack) {
        console.log(color_utils_1.colors.warning('⚠️  Could not determine stack signature'));
        console.log(color_utils_1.colors.dim('   Project may be too simple or missing key configuration files'));
        return;
    }
    console.log('');
    console.log(color_utils_1.colors.success('✨ Stack discovered!'));
    console.log(`   ${color_utils_1.colors.highlight('Name:')} ${stack.name}`);
    console.log(`   ${color_utils_1.colors.highlight('Signature:')} ${stack.signature}`);
    console.log(`   ${color_utils_1.colors.highlight('Frameworks:')} ${stack.frameworks.join(', ')}`);
    console.log(`   ${color_utils_1.colors.highlight('Confidence:')} ${stack.confidence}%`);
    console.log('');
    // Auto-collect the stack
    await engine.collectStack(stack);
    console.log(color_utils_1.colors.success('🎉 Stack added to your collection!'));
    console.log(color_utils_1.colors.dim('   View collection: faf stacks'));
}
/**
 * Export stacks for Gallery-Svelte
 */
async function exportForGallery() {
    const engine = new StacktisticsEngine();
    const stacks = await engine.getDiscoveredStacks();
    const exportDir = path_1.default.join(os_1.default.homedir(), '.faf', 'stacktistics', 'exports');
    await fs_1.promises.mkdir(exportDir, { recursive: true });
    const exportPath = path_1.default.join(exportDir, 'gallery-stacks.json');
    // Transform for Gallery-Svelte format
    const galleryData = stacks.map(stack => ({
        signature: stack,
        cardArt: {
            gradient: ['#00bf63', '#00a856'], // FAF green theme
            pattern: 'modern',
            holographic: stack.confidence > 90
        },
        stats: {
            discovered: stack.detectedAt,
            timesEncountered: 1,
            projectsUsing: [path_1.default.basename(stack.projectPath)]
        }
    }));
    await fs_1.promises.writeFile(exportPath, JSON.stringify(galleryData, null, 2));
    console.log(color_utils_1.colors.success('📤 Exported stacks for Gallery-Svelte'));
    console.log(color_utils_1.colors.dim(`   Location: ${exportPath}`));
    console.log(color_utils_1.colors.dim(`   Stacks exported: ${stacks.length}`));
}
//# sourceMappingURL=stacks.js.map