"use strict";
/**
 * Detail view renderer for `ccsx auth show <name>`.
 * Extracted from show-command.ts to keep files under 200 lines.
 */
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.showProfileDetail = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const errors_1 = require("../../errors");
const exit_codes_1 = require("../../errors/exit-codes");
const codex_profile_paths_1 = require("../codex-profile-paths");
const codex_account_identity_1 = require("../codex-account-identity");
function showProfileDetail(profileName, ctx, json) {
    const { registry } = ctx;
    if (!registry.hasProfile(profileName)) {
        (0, errors_1.exitWithError)(`Profile not found: ${profileName}`, exit_codes_1.ExitCode.PROFILE_ERROR);
        return;
    }
    const meta = registry.getProfile(profileName);
    const profileDir = (0, codex_profile_paths_1.resolveCodexProfileDir)(profileName);
    const authJsonPath = path.join(profileDir, 'auth.json');
    const configTomlPath = path.join(profileDir, 'config.toml');
    const authExists = fs.existsSync(authJsonPath);
    let authMtime = null;
    let identity = {
        email: undefined,
        plan_type: undefined,
        account_id: undefined,
    };
    let authState = 'missing';
    if (authExists) {
        try {
            const stat = fs.statSync(authJsonPath);
            authMtime = stat.mtime.toISOString();
            identity = (0, codex_account_identity_1.decodeAccountIdentity)(authJsonPath);
            authState = `present (mtime: ${new Date(authMtime).toLocaleString()})`;
        }
        catch {
            authState = 'present (unreadable)';
        }
    }
    // Inspect config.toml symlink
    let configTarget = null;
    try {
        const lstat = fs.lstatSync(configTomlPath);
        if (lstat.isSymbolicLink()) {
            configTarget = fs.readlinkSync(configTomlPath);
        }
        else {
            configTarget = `${configTomlPath} (regular file, not symlink)`;
        }
    }
    catch {
        configTarget = null;
    }
    const isDefault = registry.getDefault() === profileName;
    const isActive = process.env.CCS_CODEX_PROFILE === profileName;
    const states = [];
    if (isDefault)
        states.push('default');
    if (isActive)
        states.push('active');
    const stateStr = states.join(',');
    const accountId = meta.account_id ?? identity.account_id ?? null;
    const email = meta.email ?? identity.email ?? null;
    const plan = meta.plan_type ?? identity.plan_type ?? null;
    if (json) {
        const out = {
            name: profileName,
            is_default: isDefault,
            is_active: isActive,
            created: meta.created,
            last_used: meta.last_used ?? null,
            email,
            plan,
            account_id: accountId,
            profile_dir: profileDir,
            auth_json_exists: authExists,
            auth_json_mtime: authMtime,
            config_toml_link_target: configTarget,
        };
        console.log(JSON.stringify(out, null, 2));
        return;
    }
    const badge = stateStr ? ` (${stateStr})` : '';
    console.log(`Codex Profile: ${profileName}${badge}`);
    console.log('');
    const rows = [
        ['Name', profileName],
        ['Profile dir', profileDir],
        ['config.toml', configTarget ? `-> ${configTarget}  (symlink)` : '(not linked)'],
        ['auth.json', authState],
        ['Email', email ?? (authExists ? '<invalid>' : '<unknown>')],
        ['Plan', plan ?? (authExists ? '<invalid>' : '<unknown>')],
        ['Account ID', accountId ?? '-'],
        ['Created', new Date(meta.created).toLocaleString()],
        ['Last used', meta.last_used ? new Date(meta.last_used).toLocaleString() : 'never'],
        ['CODEX_HOME (env)', process.env.CODEX_HOME ?? 'unset'],
        ['CCS_CODEX_PROFILE', process.env.CCS_CODEX_PROFILE ?? 'unset'],
    ];
    console.log((0, ui_1.table)(rows, { colWidths: [20, 55] }));
    // H4: warn if config.toml is a regular file (not symlink)
    if (configTarget && configTarget.includes('regular file')) {
        process.stderr.write(`[!] config.toml is a regular file, not a symlink. Config changes won't propagate.\n`);
        process.stderr.write(`    Run: ccsx auth create ${profileName} --force\n`);
    }
}
exports.showProfileDetail = showProfileDetail;
//# sourceMappingURL=show-detail-view.js.map