"use strict";
/**
 * codex-auth login command.
 * Spawns `codex login` with CODEX_HOME pinned to the profile dir.
 * Auto-creates profile if it doesn't exist yet.
 * Updates registry with email/plan from JWT after successful login.
 */
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.handleLoginCodex = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const childProcess = __importStar(require("child_process"));
const logging_1 = require("../../services/logging");
const ui_1 = require("../../utils/ui");
const errors_1 = require("../../errors");
const exit_codes_1 = require("../../errors/exit-codes");
const index_1 = require("../index");
const codex_account_identity_1 = require("../codex-account-identity");
const codex_detector_1 = require("../../targets/codex-detector");
const types_1 = require("./types");
const logger = (0, logging_1.createLogger)('codex-auth:cmd:login');
async function handleLoginCodex(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    (0, types_1.rejectUnsupportedOptions)(parsed, 'ccsx auth login <name>');
    const { profileName } = parsed;
    if (!profileName) {
        console.log('Usage: ccsx auth login <name>');
        (0, errors_1.exitWithError)('Profile name required', exit_codes_1.ExitCode.PROFILE_ERROR);
        return;
    }
    const nameError = (0, types_1.getProfileNameError)(profileName);
    if (nameError) {
        (0, errors_1.exitWithError)(nameError, exit_codes_1.ExitCode.PROFILE_ERROR);
        return;
    }
    const { registry } = ctx;
    const profileDir = (0, index_1.resolveCodexProfileDir)(profileName);
    // Auto-create profile if missing
    if (!registry.hasProfile(profileName)) {
        console.log((0, ui_1.info)(`Auto-creating profile ${profileName}`));
        ensureProfileDirReady(profileDir);
        registry.createProfile(profileName, {
            created: new Date().toISOString(),
            last_used: null,
        });
    }
    const codexCli = (0, codex_detector_1.detectCodexCli)();
    if (!codexCli) {
        console.log('');
        console.log('Install:');
        console.log('  npm i -g @openai/codex');
        console.log('  # or follow https://github.com/openai/codex#install');
        console.log('');
        console.log(`After installing, re-run:`);
        console.log(`  ccsx auth login ${profileName}`);
        (0, errors_1.exitWithError)('codex CLI not found', exit_codes_1.ExitCode.BINARY_ERROR);
        return;
    }
    // Ensure profile dir exists (may have been deleted)
    if (!fs.existsSync(profileDir)) {
        ensureProfileDirReady(profileDir);
    }
    const authJsonPath = path.join(profileDir, 'auth.json');
    const authJsonExisted = fs.existsSync(authJsonPath);
    console.log((0, ui_1.info)(`Launching codex login for profile: ${profileName}`));
    console.log(`  CODEX_HOME=${profileDir}`);
    console.log('');
    const exitCode = await new Promise((resolve) => {
        const child = childProcess.spawn(codexCli, ['login'], {
            stdio: 'inherit',
            env: { ...process.env, CODEX_HOME: profileDir },
            windowsHide: true,
        });
        child.on('error', (err) => {
            process.stderr.write(`[X] Failed to execute codex: ${err.message}\n`);
            logger.warn('codex-auth.login.spawn-error', 'Spawn failed', { error: err.message });
            resolve(exit_codes_1.ExitCode.BINARY_ERROR);
        });
        child.on('exit', (code) => {
            resolve(code ?? 1);
        });
    });
    if (exitCode === 0 && fs.existsSync(authJsonPath)) {
        const identity = (0, codex_account_identity_1.decodeAccountIdentity)(authJsonPath);
        const now = new Date().toISOString();
        const metadataUpdate = { last_used: now };
        if (identity.email !== undefined)
            metadataUpdate.email = identity.email;
        if (identity.plan_type !== undefined)
            metadataUpdate.plan_type = identity.plan_type;
        if (identity.account_id !== undefined)
            metadataUpdate.account_id = identity.account_id;
        registry.updateProfile(profileName, metadataUpdate);
        const emailStr = identity.email ?? '<unknown>';
        const planStr = identity.plan_type ? ` (plan: ${identity.plan_type})` : '';
        console.log((0, ui_1.ok)(`Logged in as ${emailStr}${planStr}`));
        console.log(`  Profile: ${profileName}`);
        console.log(`  Updated: ${now}`);
    }
    else if (exitCode === 0) {
        process.stderr.write('[!] codex login exited cleanly but no auth.json. Skipping registry update.\n');
    }
    else {
        if (!authJsonExisted) {
            process.stderr.write(`[!] Login cancelled or failed. Profile ${profileName} remains unauthenticated.\n`);
        }
        else {
            process.stderr.write('[!] Login failed. Previous credentials may still be valid.\n');
        }
        process.exit(exit_codes_1.ExitCode.AUTH_ERROR);
    }
}
exports.handleLoginCodex = handleLoginCodex;
function ensureProfileDirReady(profileDir) {
    try {
        fs.mkdirSync(profileDir, { recursive: true, mode: 0o700 });
        (0, index_1.ensureSharedConfigSymlink)(profileDir);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        logger.warn('codex-auth.login.config-repair-failed', 'Config repair failed', {
            profileDir,
            error: msg,
        });
        (0, errors_1.exitWithError)(`Failed to prepare profile config.toml: ${msg}`, exit_codes_1.ExitCode.CONFIG_ERROR);
    }
}
//# sourceMappingURL=login-command.js.map