// ─────────────────────────────────────────────────────────────────────────────
// Nexus Prime Licensing — Platform Currency Unit (PCU) Meter
//
// Reads existing metrics from across the system to produce a snapshot of
// current consumption. Does NOT create new tracking — reads from SQLite
// tables and runtime state that already exist.
// ─────────────────────────────────────────────────────────────────────────────
import fs from 'fs';
import path from 'path';
import os from 'os';
import { getSharedLicenseManager } from './license-manager.js';
function pct(current, limit) {
    if (!Number.isFinite(limit) || limit <= 0)
        return 0;
    return Math.min(100, Math.round((current / limit) * 100));
}
function readInstallId() {
    try {
        const p = path.join(os.homedir(), '.nexus-prime', 'install-id');
        if (fs.existsSync(p))
            return fs.readFileSync(p, 'utf8').trim();
    }
    catch { /* ignore */ }
    return 'unknown';
}
function countWorkspaces() {
    try {
        const wsDir = path.join(os.homedir(), '.nexus-prime', 'workspaces');
        if (!fs.existsSync(wsDir))
            return 0;
        return fs.readdirSync(wsDir).filter(d => {
            try {
                return fs.statSync(path.join(wsDir, d)).isDirectory();
            }
            catch {
                return false;
            }
        }).length;
    }
    catch {
        return 0;
    }
}
/**
 * Produce a PCU snapshot using whatever runtime objects are available.
 * All parameters are optional — pass what you have.
 */
export function snapshotPCU(opts) {
    const status = getSharedLicenseManager().getStatus();
    const caps = status.caps;
    const memCurrent = opts?.memoryTotal ?? 0;
    const projCurrent = countWorkspaces();
    const opCurrent = opts?.operativeCount ?? 0;
    return {
        tier: status.tier,
        memory: {
            current: memCurrent,
            limit: caps.maxMemoryEntries,
            pct: pct(memCurrent, caps.maxMemoryEntries),
        },
        projects: {
            current: projCurrent,
            limit: caps.maxProjects,
            pct: pct(projCurrent, caps.maxProjects),
        },
        operatives: {
            current: opCurrent,
            limit: caps.maxOperatives,
            pct: pct(opCurrent, caps.maxOperatives),
        },
        skillProfile: {
            current: caps.skillProfile,
            allowed: caps.skillProfile,
        },
        darwin: {
            enabled: caps.darwinEnabled,
            scope: caps.darwinScope,
        },
        tokensSaved: opts?.tokensSaved ?? 0,
        usdSaved: opts?.usdSaved ?? 0,
        orchestrations: opts?.orchestrations ?? 0,
        sessions: opts?.sessions ?? 0,
        installId: readInstallId(),
    };
}
/**
 * Format PCU snapshot as a CLI-friendly string with progress bars.
 */
export function formatPCUStatus(pcu) {
    const bar = (p) => {
        const filled = Math.round(p / 10);
        return '\u2588'.repeat(filled) + '\u2591'.repeat(10 - filled);
    };
    const fmtLimit = (n) => Number.isFinite(n) ? n.toLocaleString() : '\u221E';
    const fmtUsd = (n) => `$${n.toFixed(2)}`;
    const lines = [
        `\u2554${'═'.repeat(44)}\u2557`,
        `\u2551  NEXUS PRIME \u00B7 ${pcu.tier.toUpperCase()} Plan${' '.repeat(Math.max(0, 25 - pcu.tier.length))}\u2551`,
        `\u2560${'═'.repeat(44)}\u2563`,
        `\u2551 Memory      ${bar(pcu.memory.pct)}  ${pcu.memory.current.toLocaleString()} / ${fmtLimit(pcu.memory.limit)}${' '.repeat(Math.max(0, 10))} \u2551`,
        `\u2551 Projects    ${bar(pcu.projects.pct)}  ${pcu.projects.current} / ${fmtLimit(pcu.projects.limit)}${' '.repeat(Math.max(0, 16))} \u2551`,
        `\u2551 Operatives  ${bar(pcu.operatives.pct)}  ${pcu.operatives.current} / ${fmtLimit(pcu.operatives.limit)}${' '.repeat(Math.max(0, 16))} \u2551`,
        `\u2551 Skills      ${pcu.skillProfile.allowed}${' '.repeat(Math.max(0, 31 - pcu.skillProfile.allowed.length))} \u2551`,
        `\u2551 Darwin      ${pcu.darwin.enabled ? pcu.darwin.scope : 'off'}${' '.repeat(Math.max(0, 31 - (pcu.darwin.enabled ? pcu.darwin.scope.length : 3)))} \u2551`,
        `\u2560${'─'.repeat(44)}\u2563`,
        `\u2551 Value Delivered${' '.repeat(28)} \u2551`,
        `\u2551 Tokens saved   ${pcu.tokensSaved.toLocaleString()} (${fmtUsd(pcu.usdSaved)})${' '.repeat(Math.max(0, 10))} \u2551`,
        `\u2551 Orchestrations ${pcu.orchestrations.toLocaleString()}${' '.repeat(Math.max(0, 25))} \u2551`,
        `\u2551 Sessions       ${pcu.sessions.toLocaleString()}${' '.repeat(Math.max(0, 25))} \u2551`,
        `\u2560${'─'.repeat(44)}\u2563`,
        `\u2551 Install ID  ${pcu.installId.slice(0, 12)}...${' '.repeat(Math.max(0, 20))} \u2551`,
        `\u2551 Dashboard   http://127.0.0.1:3377${' '.repeat(9)} \u2551`,
        `\u2551 Upgrade     nexus-prime.cfd/account${' '.repeat(8)} \u2551`,
        `\u255A${'═'.repeat(44)}\u255D`,
    ];
    return lines.join('\n');
}
