/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
import { debugLogger } from '../utils/debugLogger.js';
const SIXTH_DIR = path.join(os.homedir(), '.sixth');
const USAGE_CACHE_FILE = path.join(SIXTH_DIR, 'usage.json');
const FREE_TRIAL_LIMIT = 100000; // 100k tokens for testing
export class TokenUsageTracker {
    /**
     * Get current token usage
     */
    static async getUsage() {
        try {
            // Use a quick timeout to prevent hanging
            const data = await Promise.race([
                fs.readFile(USAGE_CACHE_FILE, 'utf8'),
                new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), 1000))
            ]);
            const usage = JSON.parse(data);
            return usage;
        }
        catch {
            // Return default if file doesn't exist or times out
            return {
                totalTokensUsed: 0,
                lastUpdated: Date.now(),
            };
        }
    }
    /**
     * Add tokens to usage count
     */
    static async addTokenUsage(tokens) {
        try {
            // Ensure directory exists
            await fs.mkdir(SIXTH_DIR, { recursive: true });
            const currentUsage = await this.getUsage();
            const updatedUsage = {
                totalTokensUsed: currentUsage.totalTokensUsed + tokens,
                lastUpdated: Date.now(),
                resetDate: currentUsage.resetDate,
            };
            await fs.writeFile(USAGE_CACHE_FILE, JSON.stringify(updatedUsage, null, 2), 'utf8');
            debugLogger.log(`Token usage updated: +${tokens} tokens (total: ${updatedUsage.totalTokensUsed})`);
        }
        catch (error) {
            debugLogger.error('Failed to update token usage:', error);
        }
    }
    /**
     * Check if user has exceeded free trial limit
     */
    static async hasExceededLimit() {
        const usage = await this.getUsage();
        return usage.totalTokensUsed >= FREE_TRIAL_LIMIT;
    }
    /**
     * Get remaining tokens in free trial
     */
    static async getRemainingTokens() {
        const usage = await this.getUsage();
        return Math.max(0, FREE_TRIAL_LIMIT - usage.totalTokensUsed);
    }
    /**
     * Get usage percentage (0-100)
     */
    static async getUsagePercentage() {
        const usage = await this.getUsage();
        return Math.min(100, (usage.totalTokensUsed / FREE_TRIAL_LIMIT) * 100);
    }
    /**
     * Reset usage (for testing or admin purposes)
     */
    static async resetUsage() {
        try {
            const resetUsage = {
                totalTokensUsed: 0,
                lastUpdated: Date.now(),
                resetDate: Date.now(),
            };
            await fs.mkdir(SIXTH_DIR, { recursive: true });
            await fs.writeFile(USAGE_CACHE_FILE, JSON.stringify(resetUsage, null, 2), 'utf8');
            debugLogger.log('Token usage reset');
        }
        catch (error) {
            debugLogger.error('Failed to reset token usage:', error);
        }
    }
    /**
     * Clear usage cache
     */
    static async clearUsage() {
        try {
            await fs.unlink(USAGE_CACHE_FILE);
            debugLogger.log('Token usage cache cleared');
        }
        catch {
            // File might not exist, which is fine
            debugLogger.log('Token usage cache was already clear');
        }
    }
}
//# sourceMappingURL=tokenUsageTracker.js.map