"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.buildFocusReport = buildFocusReport;
exports.renderFocusMd = renderFocusMd;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
function countRecentFiles(projectPath, days) {
    const cutoff = Date.now() - days * 24 * 60 * 60 * 1000;
    let recent = 0;
    let total = 0;
    let lines = 0;
    const exts = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.go', '.html', '.htm']);
    function walk(dir, depth = 0) {
        if (depth > 6)
            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)) {
                    total++;
                    try {
                        const st = fs.statSync(full);
                        if (st.mtimeMs > cutoff)
                            recent++;
                        const content = fs.readFileSync(full, 'utf-8');
                        lines += content.split('\n').length;
                    }
                    catch { }
                }
            }
        }
    }
    walk(projectPath);
    return { recent, total, lines };
}
function readPkgDesc(projectPath) {
    const pkgPath = path.join(projectPath, 'package.json');
    if (!fs.existsSync(pkgPath))
        return '';
    try {
        const j = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
        return (j.description || '').slice(0, 120);
    }
    catch {
        return '';
    }
}
function lastModified(projectPath) {
    let maxMtime = 0;
    let maxPath = '';
    function walk(dir, depth = 0) {
        if (depth > 6)
            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()) {
                try {
                    const st = fs.statSync(full);
                    if (st.mtimeMs > maxMtime) {
                        maxMtime = st.mtimeMs;
                        maxPath = full;
                    }
                }
                catch { }
            }
        }
    }
    walk(projectPath);
    if (maxMtime === 0)
        return { days: 999, date: 'never' };
    const days = Math.floor((Date.now() - maxMtime) / (24 * 60 * 60 * 1000));
    return { days, date: new Date(maxMtime).toISOString().split('T')[0] };
}
function buildFocusReport(rootDir) {
    const entries = fs.readdirSync(rootDir, { withFileTypes: true });
    const projectDirs = entries
        .filter(e => e.isDirectory() && !e.name.startsWith('.') && !/^(node_modules|dist|build|coverage)$/i.test(e.name))
        .map(e => path.join(rootDir, e.name));
    const projects = [];
    for (const p of projectDirs) {
        try {
            const stat = fs.statSync(p);
            if (!stat.isDirectory())
                continue;
            const lm = lastModified(p);
            const counts = countRecentFiles(p, 14);
            const all = countRecentFiles(p, 99999);
            let status = 'fresh';
            if (lm.days <= 3)
                status = 'active';
            else if (lm.days <= 30)
                status = 'stalled';
            else if (lm.days <= 90)
                status = 'abandoned';
            else
                status = 'abandoned';
            const isEmpty = all.total < 5;
            if (isEmpty)
                status = 'fresh';
            let action = 'keep';
            let reason = '';
            if (status === 'active') {
                action = 'keep';
                reason = `Modified ${lm.days} day(s) ago — actively working on this`;
            }
            else if (status === 'stalled') {
                if (all.total < 5) {
                    action = 'resurrect';
                    reason = `Started ${lm.days} days ago, only ${all.total} files — pick it up or delete`;
                }
                else {
                    action = 'pause';
                    reason = `${all.total} files, last edit ${lm.days}d ago — momentum lost, decide: continue or archive`;
                }
            }
            else if (status === 'abandoned') {
                if (all.total > 100) {
                    action = 'resurrect';
                    reason = `${all.total} files of real work but ${lm.days} days silent — too much sunk cost to delete`;
                }
                else if (all.total > 20) {
                    action = 'archive';
                    reason = `${all.total} files, ${lm.days}d silent — archive (zip + move to cold storage)`;
                }
                else {
                    action = 'delete';
                    reason = `Only ${all.total} files, ${lm.days}d silent — delete or write README "what I learned"`;
                }
            }
            else {
                action = 'resurrect';
                reason = `New project (${lm.days}d old, ${all.total} files) — give it 2 weeks or delete`;
            }
            projects.push({
                name: path.basename(p),
                path: p,
                status,
                lastModifiedDays: lm.days,
                lastModifiedDate: lm.date,
                totalFiles: all.total,
                recentFiles: counts.recent,
                size: { files: all.total, lines: all.lines },
                description: readPkgDesc(p),
                recommendedAction: action,
                reason,
            });
        }
        catch { }
    }
    projects.sort((a, b) => a.lastModifiedDays - b.lastModifiedDays);
    const active = projects.filter(p => p.status === 'active');
    const stalled = projects.filter(p => p.status === 'stalled');
    const abandoned = projects.filter(p => p.status === 'abandoned');
    const fresh = projects.filter(p => p.status === 'fresh');
    const advice = [];
    if (active.length === 0) {
        advice.push('🚨 Tu kisi pe actively kaam nahi kar raha hai. Kisi 1 project ko pick up kar.');
    }
    else if (active.length > 5) {
        advice.push(`⚠️ Tu ${active.length} projects pe active hai — FOCUS nahi hai. Top 1-2 pe focus kar.`);
    }
    else {
        advice.push(`✅ ${active.length} project pe active hai — yeh achha hai.`);
    }
    if (stalled.length >= 3) {
        advice.push(`⚠️ ${stalled.length} projects STALLED hain (1 month+ no edit) — decide: continue ya archive.`);
    }
    if (abandoned.length >= 3) {
        advice.push(`🗑️ ${abandoned.length} projects ABANDONED hain (3+ months) — sunk cost chhod, archive/delete.`);
    }
    if (abandoned.filter(p => p.totalFiles > 100).length > 0) {
        const big = abandoned.filter(p => p.totalFiles > 100);
        advice.push(`💎 ${big.length} abandoned project me 100+ files hain — RESURRECT them, sunk cost zyada hai.`);
    }
    const totalLines = projects.reduce((a, p) => a + p.size.lines, 0);
    advice.push(`📊 Total: ${projects.length} projects · ${(totalLines / 1000).toFixed(0)}K lines · ${active.length} active`);
    return {
        totalProjects: projects.length,
        active: active.length,
        stalled: stalled.length,
        abandoned: abandoned.length,
        fresh: fresh.length,
        topPicks: projects.filter(p => p.recommendedAction === 'keep').slice(0, 5),
        shouldPause: projects.filter(p => p.recommendedAction === 'pause'),
        shouldArchive: projects.filter(p => p.recommendedAction === 'archive'),
        shouldResurrect: projects.filter(p => p.recommendedAction === 'resurrect'),
        overallAdvice: advice,
        generatedAt: new Date().toISOString(),
    };
}
function renderFocusMd(r) {
    const lines = [];
    lines.push('# 🎯 FIVO Cell — Your Focus Report');
    lines.push('');
    lines.push(`> Generated: ${r.generatedAt}`);
    lines.push('');
    lines.push(`## 📊 Summary`);
    lines.push('');
    lines.push(`- **Total projects:** ${r.totalProjects}`);
    lines.push(`- **Active (edited in last 3 days):** ${r.active}`);
    lines.push(`- **Stalled (3-30 days):** ${r.stalled}`);
    lines.push(`- **Abandoned (30+ days):** ${r.abandoned}`);
    lines.push(`- **Fresh (less than 5 files):** ${r.fresh}`);
    lines.push('');
    if (r.topPicks.length > 0) {
        lines.push('## 🔥 Keep doing this');
        for (const p of r.topPicks) {
            lines.push(`- **${p.name}** — ${p.reason}`);
        }
        lines.push('');
    }
    if (r.shouldPause.length > 0) {
        lines.push('## ⏸️ Pause / Decide');
        for (const p of r.shouldPause) {
            lines.push(`- **${p.name}** (${p.lastModifiedDays}d silent) — ${p.reason}`);
        }
        lines.push('');
    }
    if (r.shouldArchive.length > 0) {
        lines.push('## 📦 Archive');
        for (const p of r.shouldArchive) {
            lines.push(`- **${p.name}** (${p.lastModifiedDays}d silent) — ${p.reason}`);
        }
        lines.push('');
    }
    if (r.shouldResurrect.length > 0) {
        lines.push('## 💎 Resurrect');
        for (const p of r.shouldResurrect) {
            lines.push(`- **${p.name}** (${p.lastModifiedDays}d silent) — ${p.reason}`);
        }
        lines.push('');
    }
    return lines.join('\n');
}
//# sourceMappingURL=focus-report.js.map