"use strict";
/**
 * Show Command Handler
 *
 * Shows details for a specific profile.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleShow = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const account_context_1 = require("../account-context");
const account_profile_diagnostics_1 = require("../account-profile-diagnostics");
const resume_lane_diagnostics_1 = require("../resume-lane-diagnostics");
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 formatHistorySummary(history) {
    const scope = history.projects_shared ? 'shared projects' : 'profile-local projects';
    const deeper = history.deeper_artifacts_shared ? ', deeper artifacts shared' : '';
    return `${scope}: ${history.project_count} project(s), ${history.session_count} session env file(s)${deeper}`;
}
/**
 * Handle the show command
 */
async function handleShow(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    const { profileName, json } = parsed;
    (0, types_1.rejectUnsupportedAuthOptions)(parsed, {
        usage: 'ccs auth show <profile> [--json]',
    });
    if (!profileName) {
        console.log((0, ui_1.fail)('Profile name is required'));
        console.log('');
        console.log(`Usage: ${(0, ui_1.color)('ccs auth show <profile> [--json]', 'command')}`);
        (0, errors_1.exitWithError)('Profile name is required', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    try {
        // Use merged profiles (checks unified config first, falls back to legacy)
        const allProfiles = ctx.registry.getAllProfilesMerged();
        const profile = allProfiles[profileName];
        if (!profile) {
            (0, errors_1.exitWithError)(`Profile not found: ${profileName}`, exit_codes_1.ExitCode.PROFILE_ERROR);
        }
        const defaultProfile = ctx.registry.getDefaultResolved();
        const isDefault = profileName === defaultProfile;
        const instancePath = ctx.instanceMgr.getInstancePath(profileName);
        const contextPolicy = (0, account_context_1.resolveAccountContextPolicy)(profile);
        const resourcePolicy = (0, shared_resource_policy_1.resolveSharedResourcePolicy)(profile);
        const settingsSync = (0, account_profile_diagnostics_1.describeSettingsSync)(instancePath, { bare: resourcePolicy.profileLocal });
        const historySummary = (0, account_profile_diagnostics_1.summarizeAccountHistory)(instancePath, contextPolicy);
        const plainCcsLane = await (0, resume_lane_diagnostics_1.resolveConfiguredPlainCcsResumeLane)().catch(() => null);
        const plainCcsUsesThisAccount = !!plainCcsLane && path.resolve(plainCcsLane.configDir) === path.resolve(instancePath);
        // Count sessions
        let sessionCount = 0;
        try {
            const sessionsDir = path.join(instancePath, 'session-env');
            if (fs.existsSync(sessionsDir)) {
                const files = fs.readdirSync(sessionsDir);
                sessionCount = files.filter((f) => f.endsWith('.json')).length;
            }
        }
        catch (_e) {
            // Ignore errors counting sessions
        }
        // JSON output mode
        if (json) {
            const output = {
                name: profileName,
                type: profile.type || 'account',
                is_default: isDefault,
                created: profile.created,
                last_used: profile.last_used || null,
                context_mode: contextPolicy.mode,
                context_group: contextPolicy.group || null,
                continuity_mode: contextPolicy.mode === 'shared' ? contextPolicy.continuityMode : null,
                shared_resource_mode: resourcePolicy.mode,
                shared_resource_inferred: resourcePolicy.inferred,
                instance_path: instancePath,
                session_count: sessionCount,
                settings_sync: {
                    state: settingsSync.state,
                    profile_settings_path: settingsSync.profile_settings_path,
                    shared_settings_path: settingsSync.shared_settings_path,
                    root_settings_path: settingsSync.root_settings_path,
                },
                history: historySummary,
                ...(plainCcsLane
                    ? {
                        plain_ccs_lane: {
                            kind: plainCcsLane.kind,
                            label: plainCcsLane.label,
                            config_dir: plainCcsLane.configDir,
                            project_count: plainCcsLane.projectCount,
                            uses_this_account: plainCcsUsesThisAccount,
                        },
                    }
                    : {}),
                ...(resourcePolicy.profileLocal ? { bare: true } : {}),
            };
            console.log(JSON.stringify(output, null, 2));
            return;
        }
        // Human-readable output
        const defaultBadge = isDefault ? (0, ui_1.color)(' (default)', 'success') : '';
        console.log((0, ui_1.header)(`Profile: ${profileName}${defaultBadge}`));
        console.log('');
        // Details table
        const details = [
            ['Type', profile.type || 'account'],
            ['Instance', instancePath],
            ['Created', new Date(profile.created).toLocaleString()],
            ['Last Used', profile.last_used ? new Date(profile.last_used).toLocaleString() : 'Never'],
            ['Context', (0, account_context_1.formatAccountContextPolicy)(contextPolicy)],
            ['Resources', resourcePolicy.mode],
            ['Credentials', 'isolated per account'],
            ['Settings', settingsSync.description],
            ['History', formatHistorySummary(historySummary)],
            ...(plainCcsLane
                ? [
                    [
                        'Plain ccs',
                        plainCcsUsesThisAccount
                            ? `uses this account lane (${plainCcsLane.projectCount} project(s))`
                            : `${plainCcsLane.label} (${plainCcsLane.projectCount} project(s))`,
                    ],
                ]
                : []),
            ...(resourcePolicy.profileLocal ? [['Bare', 'yes (no shared symlinks)']] : []),
            ['Sessions', `${sessionCount}`],
        ];
        console.log((0, ui_1.table)(details, {
            colWidths: [15, 45],
        }));
        console.log('');
    }
    catch (error) {
        (0, errors_1.exitWithError)(error.message, exit_codes_1.ExitCode.PROFILE_ERROR);
    }
}
exports.handleShow = handleShow;
//# sourceMappingURL=show-command.js.map