/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { SixthUserCache } from './sixthUserCache.js';
import { TokenUsageTracker } from './tokenUsageTracker.js';
import { SIXTH_AUTH_CONFIG } from './sixthAuth.js';
import { debugLogger } from '../utils/debugLogger.js';
import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import * as os from 'node:os';
const SIXTH_DIR = path.join(os.homedir(), '.sixth');
const JWT_CACHE_FILE = path.join(SIXTH_DIR, 'jwt.json');
export class SubscriptionManager {
    /**
     * Cache JWT token for re-authentication
     */
    static async cacheJWT(token, expiresInHours = 24) {
        try {
            await fs.mkdir(SIXTH_DIR, { recursive: true });
            const jwtCache = {
                token,
                expiresAt: Date.now() + (expiresInHours * 60 * 60 * 1000),
            };
            await fs.writeFile(JWT_CACHE_FILE, JSON.stringify(jwtCache, null, 2), 'utf8');
            debugLogger.log('JWT token cached');
        }
        catch (error) {
            debugLogger.error('Failed to cache JWT:', error);
        }
    }
    /**
     * Get cached JWT token
     */
    static async getCachedJWT() {
        try {
            const data = await fs.readFile(JWT_CACHE_FILE, 'utf8');
            const jwtCache = JSON.parse(data);
            // Check if token is expired
            if (Date.now() > jwtCache.expiresAt) {
                debugLogger.log('Cached JWT token expired');
                await this.clearJWT();
                return null;
            }
            return jwtCache.token;
        }
        catch {
            return null;
        }
    }
    /**
     * Clear cached JWT
     */
    static async clearJWT() {
        try {
            await fs.unlink(JWT_CACHE_FILE);
            debugLogger.log('JWT cache cleared');
        }
        catch {
            // File might not exist, which is fine
        }
    }
    /**
     * Refresh user info from API using cached JWT
     */
    static async refreshUserInfo() {
        try {
            const jwt = await this.getCachedJWT();
            if (!jwt) {
                debugLogger.warn('No cached JWT available for refresh');
                return null;
            }
            const response = await fetch(SIXTH_AUTH_CONFIG.apiUrl, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${jwt}`,
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok) {
                debugLogger.error(`Failed to refresh user info: ${response.statusText}`);
                return null;
            }
            const userInfo = await response.json();
            // Validate and cache updated user info
            if (userInfo.id && userInfo.email && userInfo.fullname) {
                await SixthUserCache.cacheUserInfo(userInfo);
                debugLogger.log('User info refreshed and cached');
                return userInfo;
            }
            return null;
        }
        catch (error) {
            debugLogger.error('Failed to refresh user info:', error);
            return null;
        }
    }
    /**
     * Get complete subscription status
     */
    static async getSubscriptionStatus() {
        const userInfo = await SixthUserCache.getUserInfo();
        const hasExceededLimit = await TokenUsageTracker.hasExceededLimit();
        const totalTokensUsed = (await TokenUsageTracker.getUsage()).totalTokensUsed;
        const remainingTokens = await TokenUsageTracker.getRemainingTokens();
        const usagePercentage = await TokenUsageTracker.getUsagePercentage();
        const isSubscriber = userInfo?.subscriber ?? false;
        const shouldBlock = hasExceededLimit && !isSubscriber;
        return {
            isSubscriber,
            hasExceededLimit,
            shouldBlock,
            totalTokensUsed,
            remainingTokens,
            usagePercentage,
            userInfo,
        };
    }
    /**
     * Add token usage and check if user should be blocked
     */
    static async addTokenUsageAndCheck(tokens) {
        await TokenUsageTracker.addTokenUsage(tokens);
        return this.getSubscriptionStatus();
    }
    /**
     * Open pricing page in browser
     */
    static async openPricingPage() {
        try {
            const { default: open } = await import('open');
            const pricingUrl = 'https://app.trysixth.com/pricing?referrer=vscode';
            await open(pricingUrl);
            debugLogger.log(`Opened pricing page: ${pricingUrl}`);
        }
        catch (error) {
            debugLogger.error('Failed to open pricing page:', error);
        }
    }
    /**
     * Handle subscription upgrade flow
     */
    static async handleSubscriptionUpgrade() {
        // Open pricing page
        await this.openPricingPage();
        // Return false to indicate user needs to complete payment
        // The UI should then wait for user to press enter and call refreshUserInfo()
        return false;
    }
    /**
     * Check if user needs to be warned about approaching limit
     */
    static async shouldWarnUser() {
        const status = await this.getSubscriptionStatus();
        // Warn when user hits 80% of free trial and is not a subscriber
        return !status.isSubscriber && status.usagePercentage >= 80;
    }
    /**
     * Get warning message for approaching limit
     */
    static async getWarningMessage() {
        const status = await this.getSubscriptionStatus();
        const percentage = Math.round(status.usagePercentage);
        return `⚠️  You've used ${percentage}% of your free trial (${status.totalTokensUsed.toLocaleString()} tokens). Consider upgrading to continue using Sixth CLI without interruption.`;
    }
}
//# sourceMappingURL=subscriptionManager.js.map