"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.usageTerminal = void 0;
exports.queryUsage = queryUsage;
exports.clearUsageCache = clearUsageCache;
const https = __importStar(require("https"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
const child_process_1 = require("child_process");
const logger_1 = require("./logger");
const log = (0, logger_1.modLogger)('adapter');
const CACHE_TTL_MS = 5 * 60000;
let memCache = null;
function getHashedServiceName(homeDir) {
    const configDir = path.join(homeDir, '.claude');
    const normalized = configDir.replace(/\\/g, '/').toLowerCase();
    const hash = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 8);
    return `Claude Code-credentials-${hash}`;
}
function tryKeychainService(serviceName) {
    try {
        const raw = (0, child_process_1.execFileSync)('/usr/bin/security', ['find-generic-password', '-s', serviceName, '-w'], { timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
        if (!raw)
            return null;
        const data = JSON.parse(raw);
        const token = data.claudeAiOauth?.accessToken;
        if (!token)
            return null;
        const expiresAt = data.claudeAiOauth?.expiresAt;
        if (expiresAt && expiresAt < Date.now())
            return null;
        return { accessToken: token, subscriptionType: data.claudeAiOauth?.subscriptionType };
    }
    catch {
        return null;
    }
}
function readCredentials() {
    const homeDir = os.homedir();
    // Try hashed service name (Claude Code 2.x)
    const hashed = tryKeychainService(getHashedServiceName(homeDir));
    if (hashed)
        return hashed;
    // Try legacy service name
    const legacy = tryKeychainService('Claude Code-credentials');
    if (legacy)
        return legacy;
    // Fall back to .credentials.json
    try {
        const credPath = path.join(homeDir, '.claude', '.credentials.json');
        const data = JSON.parse(fs.readFileSync(credPath, 'utf-8'));
        const token = data.claudeAiOauth?.accessToken;
        if (!token)
            return null;
        return { accessToken: token, subscriptionType: data.claudeAiOauth?.subscriptionType };
    }
    catch {
        return null;
    }
}
function fetchApi(accessToken) {
    return new Promise((resolve, reject) => {
        const req = https.request({
            hostname: 'api.anthropic.com',
            path: '/api/oauth/usage',
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${accessToken}`,
                'anthropic-beta': 'oauth-2025-04-20',
                'User-Agent': 'claude-code/2.1',
            },
        }, (res) => {
            let body = '';
            res.on('data', (chunk) => { body += chunk.toString(); });
            res.on('end', () => {
                if (res.statusCode !== 200) {
                    reject(new Error(`HTTP ${res.statusCode}: ${body}`));
                    return;
                }
                try {
                    resolve(JSON.parse(body));
                }
                catch {
                    reject(new Error('Invalid JSON response'));
                }
            });
        });
        req.setTimeout(15000, () => { req.destroy(); reject(new Error('Timeout')); });
        req.on('error', reject);
        req.end();
    });
}
const PLAN_NAMES = {
    pro: 'Pro',
    max: 'Max',
    max_5x: 'Max 5×',
    max_20x: 'Max 20×',
    claude_max: 'Max',
    free: 'Free',
};
function getPlanName(subscriptionType) {
    if (!subscriptionType)
        return undefined;
    const key = subscriptionType.toLowerCase();
    return PLAN_NAMES[key] ?? (subscriptionType.charAt(0).toUpperCase() + subscriptionType.slice(1));
}
function clamp(v) {
    if (v == null || !Number.isFinite(v))
        return undefined;
    return Math.round(Math.max(0, Math.min(100, v)));
}
// ── Public API ──────────────────────────────────────────────────────────────
let queryInProgress = null;
async function queryUsage() {
    if (memCache && Date.now() - memCache.at < CACHE_TTL_MS)
        return memCache.data;
    if (queryInProgress)
        return queryInProgress;
    queryInProgress = _fetch().finally(() => { queryInProgress = null; });
    return queryInProgress;
}
async function _fetch() {
    const creds = readCredentials();
    if (!creds) {
        log.warn({ api: 'usage' }, 'no claude credentials found');
        return {};
    }
    try {
        const resp = await fetchApi(creds.accessToken);
        function toBucket(b) {
            if (!b || b.utilization == null)
                return undefined;
            return { utilization: clamp(b.utilization), resetAt: b.resets_at ?? undefined };
        }
        const info = {
            planName: getPlanName(creds.subscriptionType),
            fiveHour: toBucket(resp.five_hour),
            sevenDay: toBucket(resp.seven_day),
            sevenDaySonnet: toBucket(resp.seven_day_sonnet),
            sevenDayOpus: toBucket(resp.seven_day_opus),
        };
        memCache = { data: info, at: Date.now() };
        log.debug({ api: 'usage', planName: info.planName }, 'usage fetched');
        return info;
    }
    catch (err) {
        log.warn({ err, api: 'usage' }, 'usage fetch failed');
        return {};
    }
}
function clearUsageCache() {
    memCache = null;
}
// Legacy export for compatibility
exports.usageTerminal = { queryUsage, clearUsageCache };
//# sourceMappingURL=usage-terminal.js.map