"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleResources = void 0;
const ui_1 = require("../../utils/ui");
const account_context_1 = require("../account-context");
const shared_resource_policy_1 = require("../shared-resource-policy");
const errors_1 = require("../../errors");
const exit_codes_1 = require("../../errors/exit-codes");
const types_1 = require("./types");
function formatMode(mode) {
    return mode === 'profile-local' ? 'profile-local' : 'shared';
}
function modeDescription(mode) {
    return mode === 'profile-local'
        ? 'profile-local resources; plugins/settings/commands/skills/agents are not linked from ~/.claude'
        : 'shared resources from ~/.claude; plugins/settings/commands/skills/agents are linked into the account';
}
async function handleResources(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args, { allowMode: true });
    const { profileName, mode, json } = parsed;
    (0, types_1.rejectUnsupportedAuthOptions)(parsed, {
        usage: 'ccs auth resources <profile> [--mode shared|profile-local] [--json]',
        allowMode: true,
    });
    if (!profileName) {
        console.log((0, ui_1.fail)('Profile name is required'));
        console.log('');
        console.log(`Usage: ${(0, ui_1.color)('ccs auth resources <profile> [--mode shared|profile-local] [--json]', 'command')}`);
        (0, errors_1.exitWithError)('Profile name is required', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    const profiles = ctx.registry.getAllProfilesMerged();
    const currentProfile = profiles[profileName];
    if (!currentProfile || currentProfile.type !== 'account') {
        (0, errors_1.exitWithError)(`Profile not found: ${profileName}`, exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    const currentPolicy = (0, shared_resource_policy_1.resolveSharedResourcePolicy)(currentProfile);
    if (mode === '') {
        (0, errors_1.exitWithError)('Missing value for --mode: expected shared|profile-local', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    if (mode !== undefined && !(0, shared_resource_policy_1.isSharedResourceMode)(mode)) {
        (0, errors_1.exitWithError)('Invalid shared resource mode: expected shared|profile-local', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    if (mode === undefined) {
        if (json) {
            console.log(JSON.stringify({
                name: profileName,
                shared_resource_mode: currentPolicy.mode,
                shared_resource_inferred: currentPolicy.inferred,
                bare: currentPolicy.profileLocal ? true : undefined,
            }, null, 2));
            return;
        }
        console.log((0, ui_1.header)(`Shared Resources: ${profileName}`));
        console.log('');
        console.log((0, ui_1.table)([
            ['Mode', formatMode(currentPolicy.mode)],
            ['Effective', modeDescription(currentPolicy.mode)],
        ], { colWidths: [14, 70] }));
        console.log('');
        return;
    }
    const existsUnified = ctx.registry.hasAccountUnified(profileName);
    const existsLegacy = ctx.registry.hasProfile(profileName);
    const previousUnified = existsUnified
        ? ctx.registry.getAllAccountsUnified()[profileName]
        : undefined;
    const previousLegacy = existsLegacy ? ctx.registry.getProfile(profileName) : undefined;
    const contextPolicy = (0, account_context_1.resolveAccountContextPolicy)(currentProfile);
    const selectedMode = mode;
    const metadata = (0, shared_resource_policy_1.sharedResourceModeToMetadata)(selectedMode);
    try {
        if (existsUnified) {
            ctx.registry.updateAccountUnified(profileName, metadata);
        }
        if (existsLegacy) {
            ctx.registry.updateProfile(profileName, metadata);
        }
        await ctx.instanceMgr.ensureInstance(profileName, contextPolicy, {
            bare: selectedMode === 'profile-local',
        });
    }
    catch (error) {
        if (existsUnified && previousUnified) {
            ctx.registry.updateAccountUnified(profileName, {
                ...previousUnified,
                shared_resource_mode: previousUnified.shared_resource_mode,
                bare: previousUnified.bare,
            });
        }
        if (existsLegacy && previousLegacy) {
            ctx.registry.updateProfile(profileName, {
                ...previousLegacy,
                shared_resource_mode: previousLegacy.shared_resource_mode,
                bare: previousLegacy.bare,
            });
        }
        throw error;
    }
    if (json) {
        console.log(JSON.stringify({
            name: profileName,
            shared_resource_mode: selectedMode,
            shared_resource_inferred: false,
            bare: selectedMode === 'profile-local' ? true : undefined,
        }, null, 2));
        return;
    }
    console.log((0, ui_1.ok)(`Shared resources for "${profileName}" set to ${formatMode(selectedMode)}`));
    console.log('');
    console.log(modeDescription(selectedMode));
    console.log('');
}
exports.handleResources = handleResources;
//# sourceMappingURL=resources-command.js.map