"use strict";
/**
 * Account Resolution — Executor-level account management
 *
 * Extracted from executor/index.ts (Phase 05).
 * Handles:
 * - --accounts listing (early exit)
 * - --use <account> switching
 * - --nickname rename
 * - Default account touch (lastUsedAt update)
 * - Account safety guards (cross-provider isolation, ban risk, stale pauses)
 * - Runtime quota monitor provider resolution
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.touchDefaultAccount = exports.resolveAccounts = exports.applyAccountSafetyGuards = exports.resolveRuntimeQuotaMonitorProviders = void 0;
const ui_1 = require("../../utils/ui");
const account_manager_1 = require("../accounts/account-manager");
const email_account_identity_1 = require("../accounts/email-account-identity");
const config_generator_1 = require("../config/config-generator");
const quota_manager_1 = require("../quota/quota-manager");
const account_safety_1 = require("../accounts/account-safety");
// ── Quota provider resolution ─────────────────────────────────────────────────
/**
 * Determine which managed quota providers need runtime monitoring.
 * For composite variants, checks all tier providers; otherwise checks the
 * single active provider.
 */
function resolveRuntimeQuotaMonitorProviders(provider, compositeProviders) {
    const candidates = compositeProviders.length > 0 ? compositeProviders : [provider];
    const resolved = [];
    for (const candidate of candidates) {
        if (quota_manager_1.MANAGED_QUOTA_PROVIDERS.includes(candidate) &&
            !resolved.includes(candidate)) {
            resolved.push(candidate);
        }
    }
    return resolved;
}
exports.resolveRuntimeQuotaMonitorProviders = resolveRuntimeQuotaMonitorProviders;
// ── Account safety guards ─────────────────────────────────────────────────────
/**
 * Apply account safety guards: stale auto-pause cleanup, provider isolation,
 * cross-provider duplicate warnings, and OAuth ban risk warnings.
 *
 * Registers process.on('exit') restore handler when isolation is enforced.
 */
function applyAccountSafetyGuards(provider, _compositeProviders) {
    (0, account_safety_1.cleanupStaleAutoPauses)();
    const isolated = (0, account_safety_1.enforceProviderIsolation)(provider);
    if (isolated === 0) {
        // No enforcement — still warn about duplicates for awareness
        (0, account_safety_1.warnCrossProviderDuplicates)(provider);
    }
    else {
        // 'exit' handlers must be synchronous — restoreAutoPausedAccounts uses sync fs APIs
        process.on('exit', () => {
            (0, account_safety_1.restoreAutoPausedAccounts)(provider);
        });
    }
}
exports.applyAccountSafetyGuards = applyAccountSafetyGuards;
// ── Main account resolution ───────────────────────────────────────────────────
/**
 * Handle account management CLI flags:
 * --accounts (list + early exit), --use (switch), --nickname (rename).
 *
 * Also calls warnOAuthBanRisk for the active provider.
 */
async function resolveAccounts(ctx) {
    const { provider, showAccounts, useAccount, setNickname, addAccount } = ctx;
    const providerConfig = (0, config_generator_1.getProviderConfig)(provider);
    // Warn about OAuth ban risk for this provider (always)
    (0, account_safety_1.warnOAuthBanRisk)(provider);
    // Handle --accounts
    if (showAccounts) {
        const accounts = (0, account_manager_1.getProviderAccounts)(provider);
        if (accounts.length === 0) {
            console.log((0, ui_1.info)(`No accounts registered for ${providerConfig.displayName}`));
            console.log(`    Run "ccs ${provider} --auth" to add an account`);
        }
        else {
            console.log(`\n${providerConfig.displayName} Accounts:\n`);
            for (const acct of accounts) {
                const defaultMark = acct.isDefault ? ' (default)' : '';
                const nickname = acct.nickname ? `[${acct.nickname}]` : '';
                console.log(`  ${nickname.padEnd(12)} ${(0, email_account_identity_1.formatAccountDisplayName)(acct)}${defaultMark}`);
            }
            console.log(`\n  Use "ccs ${provider} --use <nickname-or-id>" to switch accounts`);
        }
        process.exit(0);
        return { earlyExit: true };
    }
    // Handle --use
    if (useAccount) {
        const account = (0, account_manager_1.findAccountByQuery)(provider, useAccount);
        if (!account) {
            console.error((0, ui_1.fail)(`Account not found: "${useAccount}"`));
            const accounts = (0, account_manager_1.getProviderAccounts)(provider);
            if (accounts.length > 0) {
                console.error(`    Available accounts:`);
                for (const acct of accounts) {
                    const displayName = (0, email_account_identity_1.formatAccountDisplayName)(acct);
                    const label = acct.nickname ? `${acct.nickname} (${displayName})` : displayName;
                    console.error(`      - ${label}`);
                }
            }
            process.exit(1);
        }
        (0, account_manager_1.setDefaultAccount)(provider, account.id);
        (0, account_manager_1.touchAccount)(provider, account.id);
        const switchedLabel = account.nickname
            ? `${account.nickname} (${(0, email_account_identity_1.formatAccountDisplayName)(account)})`
            : (0, email_account_identity_1.formatAccountDisplayName)(account);
        console.log((0, ui_1.ok)(`Switched to account: ${switchedLabel}`));
    }
    // Handle --nickname (rename account) — only when not in --auth flow
    if (setNickname && !addAccount) {
        const defaultAccount = (0, account_manager_1.getDefaultAccount)(provider);
        if (!defaultAccount) {
            console.error((0, ui_1.fail)(`No account found for ${providerConfig.displayName}`));
            console.error(`    Run "ccs ${provider} --auth" to add an account first`);
            process.exit(1);
        }
        try {
            const success = (0, account_manager_1.renameAccount)(provider, defaultAccount.id, setNickname);
            if (success) {
                console.log((0, ui_1.ok)(`Renamed account to: ${setNickname}`));
            }
            else {
                console.error((0, ui_1.fail)('Failed to rename account'));
                process.exit(1);
            }
        }
        catch (err) {
            console.error((0, ui_1.fail)(err instanceof Error ? err.message : 'Failed to rename account'));
            process.exit(1);
        }
        process.exit(0);
    }
    return { earlyExit: false };
}
exports.resolveAccounts = resolveAccounts;
/**
 * Touch the default account's lastUsedAt timestamp.
 * Called after authentication succeeds and before proxy spawn.
 */
function touchDefaultAccount(provider) {
    const usedAccount = (0, account_manager_1.getDefaultAccount)(provider);
    if (usedAccount) {
        (0, account_manager_1.touchAccount)(provider, usedAccount.id);
    }
}
exports.touchDefaultAccount = touchDefaultAccount;
//# sourceMappingURL=account-resolution.js.map