/**
 * Subscription gate — blocks the agent when the subscription has expired.
 *
 * Follows the same pattern as onboarding-gate.ts:
 *  1. Show the payment prompt (inline keyboard with plans) to the owner
 *  2. Poll heartbeat every 10s (no Claude API calls)
 *  3. Once status is "active" or "skip", return so the agent can resume
 *
 * The agent never checks Stripe directly — it trusts the backend's
 * `subscriptionStatus` field in the heartbeat response.
 */
import { loadOwnerConfig, buildPricingUrl } from "../config/index.js";
import { getAgentState } from "./state.js";
import { logger } from "../logger.js";
import { t, resolveLocale } from "../i18n/index.js";
const GATE_POLL_INTERVAL_MS = 10_000;
/**
 * Run the subscription gate. Blocks until the subscription is renewed
 * (status returns to "active" or "skip").
 *
 * Called from the main loop when `heartbeat.lastSubscriptionStatus === "expired"`.
 */
export async function runSubscriptionGate(config, channelManager, heartbeat) {
    const ownerConfig = loadOwnerConfig();
    const locale = resolveLocale(ownerConfig.language);
    const agentState = getAgentState();
    agentState.gated = true;
    try {
        logger.system("Subscription expired — entering subscription gate (no Claude API calls)");
        // Notify owner with payment prompt (inline keyboard) or plain text fallback
        const plans = heartbeat.lastBillingPlans;
        const billingMessage = heartbeat.lastBillingMessage;
        const pricingUrl = buildPricingUrl(config);
        const defaultMessage = t("subscription.expired", locale);
        try {
            if (plans.length > 0 && ownerConfig.telegramChatId) {
                // Send the payment inline keyboard so the owner can select a plan directly
                await channelManager.sendTelegramPaymentPrompt(ownerConfig.telegramChatId, {
                    message: billingMessage ?? defaultMessage,
                    plans,
                });
            }
            else {
                // Fallback: plain text if no plans available or no Telegram
                const baseMessage = billingMessage ?? defaultMessage;
                const fallbackMsg = baseMessage.includes(pricingUrl)
                    ? baseMessage
                    : `${baseMessage}\n\nBrowse plans: ${pricingUrl}`;
                if (ownerConfig.telegramChatId) {
                    await channelManager.sendMessage("telegram", String(ownerConfig.telegramChatId), fallbackMsg);
                }
                else if (ownerConfig.ownerEmail) {
                    await channelManager.sendMessage("gmail", ownerConfig.ownerEmail, fallbackMsg);
                }
            }
        }
        catch {
            logger.warn("Failed to send subscription expiry notification to owner");
        }
        // Pause the runtime heartbeat loop while we own the polling
        // cadence: the gate fires its own heartbeats every 10s via
        // sendHeartbeatForSubscription, and double-firing would only
        // increase load without improving signal.
        await heartbeat.stopRuntime();
        try {
            // Poll heartbeat every 10s until subscription is renewed
            let status = heartbeat.lastSubscriptionStatus;
            while (status === "expired") {
                await new Promise((resolve) => setTimeout(resolve, GATE_POLL_INTERVAL_MS));
                status = await heartbeat.sendHeartbeatForSubscription();
                if (status !== "expired")
                    break;
                logger.debug(`Subscription gate: still expired, polling again in ${GATE_POLL_INTERVAL_MS / 1000}s`);
            }
        }
        finally {
            // Re-arm the runtime loop on every exit path, including errors,
            // so a thrown poll never leaves the agent without periodic
            // heartbeats.
            heartbeat.startRuntime(() => agentState.busy);
        }
        logger.system("Subscription renewed — exiting subscription gate");
        // Notify owner that we're resuming
        const renewedMsg = t("subscription.renewed", locale);
        try {
            if (ownerConfig.telegramChatId) {
                await channelManager.sendMessage("telegram", String(ownerConfig.telegramChatId), renewedMsg);
            }
            else if (ownerConfig.ownerEmail) {
                await channelManager.sendMessage("gmail", ownerConfig.ownerEmail, renewedMsg);
            }
        }
        catch {
            logger.warn("Failed to send subscription renewal notification to owner");
        }
    }
    finally {
        agentState.gated = false;
    }
}
//# sourceMappingURL=subscription-gate.js.map