"use strict";
/**
 * codex-auth show command.
 * List mode: table of all profiles with STATE column.
 * Detail mode: delegated to show-detail-view.ts.
 * --json: machine-readable output.
 * D14: active(missing) row at top when CCS_CODEX_PROFILE points to deleted 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.handleShowCodex = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const codex_profile_paths_1 = require("../codex-profile-paths");
const codex_account_identity_1 = require("../codex-account-identity");
const show_detail_view_1 = require("./show-detail-view");
const types_1 = require("./types");
async function handleShowCodex(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    (0, types_1.rejectUnsupportedOptions)(parsed, 'ccsx auth show [name] [--json]', { json: true });
    const { profileName, json } = parsed;
    if (profileName) {
        return (0, show_detail_view_1.showProfileDetail)(profileName, ctx, !!json);
    }
    return _showList(ctx, !!json);
}
exports.handleShowCodex = handleShowCodex;
// ── List view ─────────────────────────────────────────────────────────────────
function _showList(ctx, json) {
    const { registry } = ctx;
    const names = registry.listProfiles();
    const defaultName = registry.getDefault();
    const activeName = process.env.CCS_CODEX_PROFILE ?? null;
    // D14: check if CCS_CODEX_PROFILE points to a deleted/missing profile
    const activeMissing = activeName !== null && activeName.length > 0 && !registry.hasProfile(activeName);
    const rows = [];
    // D14: active(missing) row at top
    if (activeMissing) {
        rows.push({
            name: activeName ?? '',
            email: '<unknown>',
            plan: '-',
            accountId: null,
            lastUsed: 'never',
            state: 'active(missing)',
            missing: true,
        });
    }
    for (const name of names) {
        const meta = registry.getProfile(name);
        const states = [];
        if (name === defaultName)
            states.push('default');
        if (name === activeName)
            states.push('active');
        const profileDir = (0, codex_profile_paths_1.resolveCodexProfileDir)(name);
        const authJsonPath = path.join(profileDir, 'auth.json');
        const identity = fs.existsSync(authJsonPath)
            ? (0, codex_account_identity_1.decodeAccountIdentity)(authJsonPath)
            : {};
        const email = meta.email ?? identity.email ?? '<unknown>';
        const plan = meta.plan_type ?? identity.plan_type ?? '-';
        const accountId = meta.account_id ?? identity.account_id ?? null;
        const lastUsed = meta.last_used ? (0, types_1.formatRelativeTime)(new Date(meta.last_used)) : 'never';
        rows.push({ name, email, plan, accountId, lastUsed, state: states.join(',') });
    }
    if (json) {
        const profiles = rows.map((r) => {
            const meta = r.missing ? null : registry.getProfile(r.name);
            const profileDir = r.missing ? '' : (0, codex_profile_paths_1.resolveCodexProfileDir)(r.name);
            return {
                name: r.name,
                is_default: r.name === defaultName,
                is_active: r.name === activeName,
                created: meta?.created ?? '',
                last_used: meta?.last_used ?? null,
                email: r.email === '<unknown>' ? null : r.email,
                plan: r.plan === '-' ? null : r.plan,
                account_id: r.accountId,
                profile_dir: profileDir,
                auth_json_exists: r.missing ? false : fs.existsSync(path.join(profileDir, 'auth.json')),
                auth_json_mtime: null,
                config_toml_link_target: null,
            };
        });
        console.log(JSON.stringify({ profiles }, null, 2));
        return;
    }
    if (names.length === 0 && !activeMissing) {
        console.log((0, ui_1.info)('No Codex profiles yet.'));
        console.log('    Create one: ccsx auth create <name>');
        return;
    }
    const count = names.length + (activeMissing ? 1 : 0);
    console.log(`Codex Profiles (${count})`);
    console.log('');
    const header = ['NAME', 'EMAIL', 'PLAN', 'LAST_USED', 'STATE'];
    const tableRows = [header, ...rows.map((r) => [r.name, r.email, r.plan, r.lastUsed, r.state])];
    console.log((0, ui_1.table)(tableRows, { colWidths: [14, 26, 8, 14, 18] }));
    console.log('');
    console.log((0, ui_1.info)('Default persists across shells. Active is current shell only.'));
}
//# sourceMappingURL=show-command.js.map