"use strict";
/**
 * Copilot Usage Fetcher
 *
 * Fetches usage/quota data from copilot-api `/usage` endpoint and normalizes it
 * for CLI and dashboard consumers.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCopilotUsage = exports.fetchCopilotUsageFromDaemon = exports.normalizeCopilotUsage = void 0;
const http = __importStar(require("http"));
const percentage_1 = require("../utils/percentage");
function normalizeSnapshot(raw) {
    const entitlement = Number(raw?.entitlement ?? 0);
    const remaining = Number(raw?.remaining ?? 0);
    const safeEntitlement = Number.isFinite(entitlement) && entitlement > 0 ? entitlement : 0;
    const safeRemaining = Number.isFinite(remaining) ? Math.max(0, remaining) : 0;
    const used = Math.max(0, safeEntitlement - safeRemaining);
    const percentRemainingFromApi = raw && typeof raw.percent_remaining === 'number' ? raw.percent_remaining : null;
    const percentRemaining = percentRemainingFromApi !== null
        ? (0, percentage_1.clampPercent)(percentRemainingFromApi)
        : safeEntitlement > 0
            ? (0, percentage_1.clampPercent)((safeRemaining / safeEntitlement) * 100)
            : 0;
    return {
        entitlement: safeEntitlement,
        remaining: safeRemaining,
        used,
        percentRemaining,
        percentUsed: (0, percentage_1.clampPercent)(100 - percentRemaining),
        unlimited: Boolean(raw?.unlimited),
    };
}
function normalizeCopilotUsage(raw) {
    const usage = (raw || {});
    const snapshots = usage.quota_snapshots || {};
    return {
        plan: usage.copilot_plan ?? null,
        quotaResetDate: usage.quota_reset_date ?? null,
        quotas: {
            premiumInteractions: normalizeSnapshot(snapshots.premium_interactions),
            chat: normalizeSnapshot(snapshots.chat),
            completions: normalizeSnapshot(snapshots.completions),
        },
    };
}
exports.normalizeCopilotUsage = normalizeCopilotUsage;
/**
 * Fetch Copilot usage from running copilot-api daemon.
 *
 * @returns normalized usage on success, null on daemon/network/parsing failure
 */
async function fetchCopilotUsageFromDaemon(port) {
    return new Promise((resolve) => {
        const req = http.request({
            hostname: '127.0.0.1',
            port,
            path: '/usage',
            method: 'GET',
            timeout: 5000,
        }, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                if (res.statusCode !== 200 || !data) {
                    resolve(null);
                    return;
                }
                try {
                    const parsed = JSON.parse(data);
                    resolve(normalizeCopilotUsage(parsed));
                }
                catch {
                    resolve(null);
                }
            });
        });
        req.on('error', () => {
            resolve(null);
        });
        req.on('timeout', () => {
            req.destroy();
            resolve(null);
        });
        req.end();
    });
}
exports.fetchCopilotUsageFromDaemon = fetchCopilotUsageFromDaemon;
async function getCopilotUsage(port) {
    return fetchCopilotUsageFromDaemon(port);
}
exports.getCopilotUsage = getCopilotUsage;
//# sourceMappingURL=copilot-usage.js.map