"use strict";
/**
 * codex-auth create command.
 * Creates a new profile dir + shared config.toml symlink.
 * After creation, auto-spawns `codex login` with CODEX_HOME pinned (D11).
 * --force: re-link config.toml only, preserve auth.json (D9).
 */
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.handleCreateCodex = 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:create');
async function handleCreateCodex(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    (0, types_1.rejectUnsupportedOptions)(parsed, 'ccsx auth create <name> [--force]', { force: true });
    const { profileName, force } = parsed;
    if (!profileName) {
        console.log(`Usage: ccsx auth create <name> [--force]`);
        (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);
    // Idempotent: profile already exists
    if (registry.hasProfile(profileName)) {
        if (force) {
            // --force: only re-link config.toml, preserve auth.json
            console.log((0, ui_1.info)(`Profile already exists: ${profileName} (repairing shared resources)`));
            _ensureProfileResourcesSafe(profileDir, true);
            console.log((0, ui_1.ok)(`Profile shared resources repaired.`));
            console.log(`  Profile dir: ${profileDir}`);
        }
        else {
            _ensureProfileResourcesSafe(profileDir);
            console.log((0, ui_1.info)(`Profile already exists: ${profileName}`));
            console.log((0, ui_1.ok)(`Profile shared resources are ready.`));
            console.log(`  Profile dir: ${profileDir}`);
            console.log(`  Run: ccsx auth login ${profileName}`);
        }
        return;
    }
    // Create profile dir + symlink FIRST (filesystem is more failure-prone than registry write).
    // Avoids registry orphan if mkdir hits EACCES/ENOSPC.
    try {
        fs.mkdirSync(profileDir, { recursive: true, mode: 0o700 });
        _ensureProfileResourcesSafe(profileDir);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        if (err.code === 'EACCES') {
            (0, errors_1.exitWithError)(msg, exit_codes_1.ExitCode.GENERAL_ERROR);
            return;
        }
        throw err;
    }
    // Now register in the profile registry
    try {
        registry.createProfile(profileName, {
            created: new Date().toISOString(),
            last_used: null,
            email: undefined,
            plan_type: undefined,
        });
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        if (msg.includes('corrupt') || msg.includes('Failed to write')) {
            (0, errors_1.exitWithError)(`Profile registry is corrupt. Backup and remove the file to re-init.\n  ${msg}`, exit_codes_1.ExitCode.GENERAL_ERROR);
            return;
        }
        throw err;
    }
    const authJsonPath = path.join(profileDir, 'auth.json');
    const authExists = fs.existsSync(authJsonPath);
    console.log((0, ui_1.info)(`Creating Codex profile: ${profileName}`));
    console.log('');
    console.log(`  Profile dir : ${profileDir}`);
    console.log(`  Auth state  : ${authExists ? 'authenticated' : 'not authenticated'}`);
    console.log('');
    console.log((0, ui_1.ok)('Profile created.'));
    // D11: auto-spawn codex login after creating the profile
    await _spawnLogin(profileName, profileDir, ctx);
}
exports.handleCreateCodex = handleCreateCodex;
function _ensureSymlinkSafe(profileDir, overwriteRegularFile = false) {
    try {
        (0, index_1.ensureSharedConfigSymlink)(profileDir, undefined, { overwriteRegularFile });
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        logger.warn('codex-auth.create.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);
    }
}
function _ensureProfileResourcesSafe(profileDir, overwriteRegularFile = false) {
    _ensureSymlinkSafe(profileDir, overwriteRegularFile);
    try {
        (0, index_1.ensureCodexProfileResources)(profileDir);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        logger.warn('codex-auth.create.resource-repair-failed', 'Resource repair failed', {
            profileDir,
            error: msg,
        });
        (0, errors_1.exitWithError)(`Failed to prepare profile resources: ${msg}`, exit_codes_1.ExitCode.CONFIG_ERROR);
    }
}
async function _spawnLogin(profileName, profileDir, ctx) {
    const codexCli = (0, codex_detector_1.detectCodexCli)();
    if (!codexCli) {
        process.stderr.write(`[!] codex CLI not found — skipping auto-login.\n`);
        process.stderr.write(`    Install: npm i -g @openai/codex\n`);
        process.stderr.write(`    Then run: ccsx auth login ${profileName}\n`);
        return;
    }
    console.log('');
    console.log(`Next step: logging in to Codex...`);
    console.log(`  CODEX_HOME=${profileDir}`);
    console.log('');
    const loginResult = 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`);
            resolve({ code: exit_codes_1.ExitCode.BINARY_ERROR, error: err.message });
        });
        child.on('exit', (code) => {
            resolve({ code: code ?? 1 });
        });
    });
    if (loginResult.error) {
        (0, errors_1.exitWithError)(`codex login failed to start: ${loginResult.error}`, exit_codes_1.ExitCode.BINARY_ERROR);
        return;
    }
    const authJsonPath = path.join(profileDir, 'auth.json');
    if (loginResult.code === 0 && fs.existsSync(authJsonPath)) {
        const identity = (0, codex_account_identity_1.decodeAccountIdentity)(authJsonPath);
        ctx.registry.updateProfile(profileName, {
            last_used: new Date().toISOString(),
            email: identity.email,
            plan_type: identity.plan_type ?? null,
            account_id: identity.account_id,
        });
        const emailStr = identity.email ? ` as ${identity.email}` : '';
        const planStr = identity.plan_type ? ` (plan: ${identity.plan_type})` : '';
        console.log((0, ui_1.ok)(`Logged in${emailStr}${planStr}`));
    }
    else if (loginResult.code === 0) {
        process.stderr.write(`[!] codex login exited cleanly but no auth.json. Skipping registry update.\n`);
        (0, errors_1.exitWithError)('codex login completed without auth.json', exit_codes_1.ExitCode.AUTH_ERROR);
    }
    else {
        process.stderr.write(`[!] Login cancelled or failed. Profile ${profileName} remains unauthenticated.\n`);
        process.stderr.write(`    Retry: ccsx auth login ${profileName}\n`);
        (0, errors_1.exitWithError)('codex login failed', exit_codes_1.ExitCode.AUTH_ERROR);
    }
}
//# sourceMappingURL=create-command.js.map