#!/usr/bin/env node
"use strict";
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 });
require("./utils/fetch-proxy-setup");
const error_manager_1 = require("./utils/error-manager");
const ui_1 = require("./utils/ui");
// Import centralized error handling
const errors_1 = require("./errors");
const logging_1 = require("./services/logging");
const log_redaction_1 = require("./services/logging/log-redaction");
// Import target adapter system
const targets_1 = require("./targets");
// Import extracted dispatcher modules
const cli_argument_parser_1 = require("./dispatcher/cli-argument-parser");
const target_executor_1 = require("./dispatcher/target-executor");
const pre_dispatch_1 = require("./dispatcher/pre-dispatch");
const profile_resolver_1 = require("./dispatcher/profile-resolver");
// ========== Main Execution ==========
async function main() {
    // Register target adapters (singleton wiring — stays in main)
    (0, targets_1.registerTarget)(new targets_1.ClaudeAdapter());
    (0, targets_1.registerTarget)(new targets_1.DroidAdapter());
    (0, targets_1.registerTarget)(new targets_1.CodexAdapter());
    const cliLogger = (0, logging_1.createLogger)('cli');
    // Phase A: bootstrap + early arg pre-parse
    const bootstrap = await (0, cli_argument_parser_1.bootstrapAndParseEarlyCli)(process.argv.slice(2));
    if (bootstrap.exitNow) {
        return;
    }
    const args = bootstrap.args;
    const browserLaunchOverride = bootstrap.browserLaunchOverride;
    cliLogger.info('command.start', 'CLI invocation started', {
        command: args[0] || 'default',
        argCount: args.length,
        flags: args.filter((arg) => arg.startsWith('-')).slice(0, 20),
    });
    // Phase B: pre-dispatch side-effects (update check, migrate, recovery, root commands, routing)
    const preDispatchConsumed = await (0, pre_dispatch_1.runPreDispatchHandlers)({ args, cliLogger });
    if (preDispatchConsumed) {
        return;
    }
    // Phase C: profile + target detection (extracted to dispatcher/profile-resolver.ts)
    const resolvedProfile = await (0, profile_resolver_1.resolveProfileAndTarget)({ args, browserLaunchOverride, cliLogger });
    const { profile, profileInfo, resolvedTarget, nativeClaudeRemainingArgs } = resolvedProfile;
    // Dynamic imports needed by Phase E flows — preserve original load ordering.
    const InstanceManagerModule = await Promise.resolve().then(() => __importStar(require('./management/instance-manager')));
    const InstanceManager = InstanceManagerModule.default;
    const ProfileRegistryModule = await Promise.resolve().then(() => __importStar(require('./auth/profile-registry')));
    const ProfileRegistry = ProfileRegistryModule.default;
    const AccountContextModule = await Promise.resolve().then(() => __importStar(require('./auth/account-context')));
    const { resolveAccountContextPolicy, isAccountContextMetadata } = AccountContextModule;
    const ProfileContinuityModule = await Promise.resolve().then(() => __importStar(require('./auth/profile-continuity-inheritance')));
    const { resolveProfileContinuityInheritance } = ProfileContinuityModule;
    // Build full dispatch context (Phase E)
    const dispatchCtx = {
        ...resolvedProfile,
        InstanceManager,
        ProfileRegistry,
        resolveAccountContextPolicy,
        isAccountContextMetadata,
        resolveProfileContinuityInheritance,
    };
    try {
        // Special case: headless delegation (-p/--prompt)
        // Keep existing behavior for Claude targets only; non-claude targets must continue
        // through normal adapter dispatch logic.
        if (args.some((arg) => arg === '-p' || arg === '--prompt' || arg.startsWith('--prompt='))) {
            const shouldUseDelegation = resolvedTarget === 'claude' && profileInfo.type === 'settings';
            if (shouldUseDelegation) {
                const { DelegationHandler } = await Promise.resolve().then(() => __importStar(require('./delegation/delegation-handler')));
                const handler = new DelegationHandler();
                await handler.route([profile, ...nativeClaudeRemainingArgs]);
                return;
            }
        }
        // Phase E: dispatch to per-profile-type flow (all 6 branches now live in flows/)
        await (0, target_executor_1.dispatchProfile)(dispatchCtx);
    }
    catch (error) {
        const err = error;
        // Check if this is a profile not found error with suggestions
        if (err.profileName && err.availableProfiles !== undefined) {
            const allProfiles = err.availableProfiles.split('\n');
            await error_manager_1.ErrorManager.showProfileNotFound(err.profileName, allProfiles, err.suggestions);
        }
        else {
            console.error((0, ui_1.fail)(err.message));
        }
        process.exit(1);
    }
}
// ========== Global Error Handlers ==========
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
    (0, errors_1.handleError)(error);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason) => {
    (0, errors_1.handleError)(reason);
});
// Handle process termination signals for cleanup
process.on('SIGTERM', () => {
    try {
        (0, errors_1.runCleanup)();
    }
    catch {
        // Cleanup failure should not block termination.
    }
    // If a target exec path registered additional signal listeners, let those
    // listeners forward/coordinate child shutdown and final exit codes.
    if (process.listenerCount('SIGTERM') <= 1) {
        process.exit(143); // 128 + SIGTERM(15)
    }
});
process.on('SIGINT', () => {
    try {
        (0, errors_1.runCleanup)();
    }
    catch {
        // Cleanup failure should not block termination.
    }
    // Same coordination rule as SIGTERM.
    if (process.listenerCount('SIGINT') <= 1) {
        process.exit(130); // 128 + SIGINT(2)
    }
});
// Run main inside a per-invocation request context so all backend logging
// emitted during this CLI run shares a single requestId. CLI text output
// (stdout/stderr) is unaffected — the requestId lives in logs only.
const cliEntryStartedAt = Date.now();
const cliEntryLogger = (0, logging_1.createLogger)('cli:entry');
(0, logging_1.runWithRequestId)(() => {
    cliEntryLogger.stage('intake', 'cli.command.start', 'CLI invocation started', {
        argv: (0, log_redaction_1.redactArgv)(process.argv.slice(2)),
    });
    return main()
        .then(() => {
        cliEntryLogger.stage('respond', 'cli.command.complete', 'CLI invocation completed', { exitCode: process.exitCode ?? 0 }, { latencyMs: Date.now() - cliEntryStartedAt });
    })
        .catch((err) => {
        const error = err instanceof Error
            ? { name: err.name, message: err.message, stack: err.stack }
            : { name: 'Error', message: String(err) };
        cliEntryLogger.stage('cleanup', 'cli.command.failed', 'CLI invocation failed', undefined, {
            level: 'error',
            latencyMs: Date.now() - cliEntryStartedAt,
            error,
        });
        (0, errors_1.handleError)(err);
    });
});
//# sourceMappingURL=ccs.js.map