"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleRoutingAffinitySet = exports.handleRoutingAffinityHelp = exports.handleRoutingAffinityStatus = exports.handleRoutingSet = exports.handleRoutingExplain = exports.handleRoutingStatus = void 0;
const ui_1 = require("../../utils/ui");
const arg_extractor_1 = require("../arg-extractor");
const routing_strategy_1 = require("../../cliproxy/routing/routing-strategy");
function printStrategyGuide() {
    console.log((0, ui_1.subheader)('Routing Modes:'));
    console.log(`  ${(0, ui_1.color)('round-robin', 'command')} Spread requests across matching accounts.`);
    console.log(`  ${(0, ui_1.dim)('    Best when you want even usage and predictable distribution.')}`);
    console.log('');
    console.log(`  ${(0, ui_1.color)('fill-first', 'command')} Drain one available account before moving on.`);
    console.log(`  ${(0, ui_1.dim)('    Best when you want backup accounts to stay cold until the active one hits a limit.')}`);
    console.log('');
    console.log((0, ui_1.dim)('  Default stays round-robin. CCS will not switch strategy from your account mix automatically.'));
    console.log('');
}
function printSessionAffinityGuide() {
    console.log((0, ui_1.subheader)('Session Affinity:'));
    console.log(`  ${(0, ui_1.color)('session-affinity off', 'command')} Each request follows the base routing strategy.`);
    console.log(`  ${(0, ui_1.dim)('    Best when you want pure proxy-wide balancing behavior.')}`);
    console.log('');
    console.log(`  ${(0, ui_1.color)('session-affinity on', 'command')} Keep one conversation pinned to the same account when possible.`);
    console.log(`  ${(0, ui_1.dim)('    Best when you want stronger prompt-cache locality for a single conversation.')}`);
    console.log('');
}
function printSessionRecognitionGuide() {
    console.log((0, ui_1.subheader)('How CLIProxy Knows A Session Is New:'));
    console.log(`  ${(0, ui_1.dim)('  CLIProxy prefers explicit session or thread identifiers when clients send them.')}`);
    console.log(`  ${(0, ui_1.dim)('  Common examples: Claude session UUIDs, X-Session-ID, or provider-specific thread ids.')}`);
    console.log(`  ${(0, ui_1.dim)('  If no explicit identifier is present, it can fall back to fields such as metadata.user_id or conversation_id.')}`);
    console.log(`  ${(0, ui_1.dim)('  Last resort: it derives a stable key from the opening prompt history.')}`);
    console.log(`  ${(0, ui_1.dim)('  Exact precedence can vary by upstream backend/runtime version, so CCS does not promise one universal order.')}`);
    console.log('');
}
async function handleRoutingStatus() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('CLIProxy Routing Strategy'));
    console.log('');
    const [state, sessionAffinity] = await Promise.all([
        (0, routing_strategy_1.readCliproxyRoutingState)(),
        (0, routing_strategy_1.readCliproxySessionAffinityState)(),
    ]);
    console.log(`  Current: ${(0, ui_1.color)(state.strategy, 'command')}`);
    console.log(`  Target:  ${(0, ui_1.color)(state.target, 'info')}`);
    console.log(`  Source:  ${(0, ui_1.color)(state.source === 'live' ? 'live CLIProxy' : 'saved startup default', 'info')}`);
    if (state.message) {
        console.log('');
        console.log((0, ui_1.infoBox)(state.message, state.reachable ? 'INFO' : 'WARNING'));
    }
    console.log(`  Session Affinity: ${sessionAffinity.manageable
        ? (0, ui_1.color)(sessionAffinity.enabled ? 'on' : 'off', 'command')
        : (0, ui_1.color)('unsupported', 'warning')}`);
    if (sessionAffinity.ttl) {
        console.log(`  Affinity TTL: ${(0, ui_1.color)(sessionAffinity.ttl, 'info')}`);
    }
    if (sessionAffinity.message) {
        console.log('');
        console.log((0, ui_1.infoBox)(sessionAffinity.message, sessionAffinity.manageable && sessionAffinity.reachable ? 'INFO' : 'WARNING'));
    }
    console.log('');
    printStrategyGuide();
    printSessionAffinityGuide();
}
exports.handleRoutingStatus = handleRoutingStatus;
async function handleRoutingExplain() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('CLIProxy Routing Guide'));
    console.log('');
    printStrategyGuide();
    printSessionAffinityGuide();
    printSessionRecognitionGuide();
}
exports.handleRoutingExplain = handleRoutingExplain;
async function handleRoutingSet(args) {
    const requested = (0, routing_strategy_1.normalizeCliproxyRoutingStrategy)(args[0]);
    if (!requested) {
        await (0, ui_1.initUI)();
        console.log('');
        console.log((0, ui_1.fail)('Invalid strategy. Use: round-robin or fill-first'));
        console.log('');
        printStrategyGuide();
        process.exitCode = 1;
        return;
    }
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('Update CLIProxy Routing'));
    console.log('');
    const result = await (0, routing_strategy_1.applyCliproxyRoutingStrategy)(requested);
    console.log((0, ui_1.ok)(`Routing strategy set to ${requested}`));
    console.log(`  Applied: ${(0, ui_1.color)(result.applied, 'info')}`);
    console.log(`  Target:  ${(0, ui_1.color)(result.target, 'info')}`);
    if (result.message) {
        console.log('');
        console.log((0, ui_1.infoBox)(result.message, result.reachable ? 'SUCCESS' : 'INFO'));
    }
    console.log('');
}
exports.handleRoutingSet = handleRoutingSet;
async function handleRoutingAffinityStatus() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('CLIProxy Session Affinity'));
    console.log('');
    const state = await (0, routing_strategy_1.readCliproxySessionAffinityState)();
    if (!state.manageable) {
        console.log(`  Status: ${(0, ui_1.color)('unsupported', 'warning')}`);
    }
    else {
        console.log(`  Status: ${(0, ui_1.color)(state.enabled ? 'on' : 'off', 'command')}`);
    }
    console.log(`  Source: ${state.manageable ? (0, ui_1.color)('saved local setting', 'info') : (0, ui_1.color)('unsupported', 'warning')}`);
    console.log(`  Target: ${(0, ui_1.color)(state.target, 'info')}`);
    if (state.ttl) {
        console.log(`  TTL:    ${(0, ui_1.color)(state.ttl, 'info')}`);
    }
    if (state.message) {
        console.log('');
        console.log((0, ui_1.infoBox)(state.message, state.manageable && state.reachable ? 'INFO' : 'WARNING'));
    }
    console.log('');
    printSessionAffinityGuide();
    printSessionRecognitionGuide();
}
exports.handleRoutingAffinityStatus = handleRoutingAffinityStatus;
async function handleRoutingAffinityHelp() {
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('CLIProxy Session Affinity'));
    console.log('');
    console.log((0, ui_1.subheader)('Usage:'));
    console.log(`  ${(0, ui_1.color)('ccs cliproxy routing affinity', 'command')}`);
    console.log(`  ${(0, ui_1.color)('ccs cliproxy routing affinity on', 'command')}`);
    console.log(`  ${(0, ui_1.color)('ccs cliproxy routing affinity off', 'command')}`);
    console.log(`  ${(0, ui_1.color)('ccs cliproxy routing affinity on --ttl 1h', 'command')}`);
    console.log('');
    printSessionAffinityGuide();
    console.log(`  ${(0, ui_1.dim)('Accepted TTL examples: 30m, 1h, 2h30m')}`);
    console.log('');
    printSessionRecognitionGuide();
}
exports.handleRoutingAffinityHelp = handleRoutingAffinityHelp;
async function handleRoutingAffinitySet(args) {
    const requested = (0, routing_strategy_1.normalizeCliproxySessionAffinityEnabled)(args[0]);
    const extractedTtl = (0, arg_extractor_1.extractOption)(args.slice(1), ['--ttl']);
    const remainingArgs = extractedTtl.remainingArgs.filter((token) => token.trim().length > 0);
    const ttl = extractedTtl.found && !extractedTtl.missingValue
        ? ((0, routing_strategy_1.normalizeCliproxySessionAffinityTtl)(extractedTtl.value) ?? undefined)
        : undefined;
    if (requested === null ||
        extractedTtl.missingValue ||
        (extractedTtl.found && !ttl) ||
        remainingArgs.length > 0) {
        await (0, ui_1.initUI)();
        console.log('');
        console.log((0, ui_1.fail)('Invalid session affinity command. Use: routing affinity <on|off> [--ttl 1h]'));
        console.log('');
        printSessionAffinityGuide();
        console.log(`  ${(0, ui_1.dim)('Accepted TTL examples: 30m, 1h, 2h30m')}`);
        console.log('');
        process.exitCode = 1;
        return;
    }
    await (0, ui_1.initUI)();
    console.log('');
    console.log((0, ui_1.header)('Update CLIProxy Session Affinity'));
    console.log('');
    const result = await (0, routing_strategy_1.applyCliproxySessionAffinitySettings)({
        enabled: requested,
        ttl,
    });
    if (!result.manageable) {
        console.log((0, ui_1.fail)(result.message || 'Session affinity is not supported for this target.'));
        console.log('');
        process.exitCode = 1;
        return;
    }
    console.log((0, ui_1.ok)(`Session affinity ${requested ? 'enabled' : 'disabled'}`));
    if (result.ttl) {
        console.log(`  TTL:     ${(0, ui_1.color)(result.ttl, 'info')}`);
    }
    console.log(`  Applied: ${(0, ui_1.color)(result.applied, 'info')}`);
    if (result.message) {
        console.log('');
        console.log((0, ui_1.infoBox)(result.message, result.reachable ? 'SUCCESS' : 'INFO'));
    }
    console.log('');
}
exports.handleRoutingAffinitySet = handleRoutingAffinitySet;
//# sourceMappingURL=routing-subcommand.js.map