"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleApiDiscoverCommand = void 0;
const services_1 = require("../../api/services");
const ui_1 = require("../../utils/ui");
const arg_extractor_1 = require("../arg-extractor");
const shared_1 = require("./shared");
async function handleApiDiscoverCommand(args) {
    await (0, ui_1.initUI)();
    const register = (0, arg_extractor_1.hasAnyFlag)(args, ['--register']);
    const jsonOutput = (0, arg_extractor_1.hasAnyFlag)(args, ['--json']);
    const force = (0, arg_extractor_1.hasAnyFlag)(args, ['--force']);
    const targetParsed = (0, shared_1.parseOptionalTargetFlag)(args, [...shared_1.API_KNOWN_FLAGS, '--register', '--json']);
    if (targetParsed.errors.length > 0) {
        targetParsed.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exit(1);
    }
    const syntax = (0, shared_1.collectUnexpectedApiArgs)(targetParsed.remainingArgs, {
        knownFlags: ['--register', '--json', '--force'],
        maxPositionals: 0,
    });
    if (syntax.errors.length > 0) {
        syntax.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exit(1);
    }
    const result = (0, services_1.discoverApiProfileOrphans)();
    if (jsonOutput) {
        console.log(JSON.stringify(result, null, 2));
        return;
    }
    console.log((0, ui_1.header)('Discover Orphan API Profiles'));
    console.log('');
    if (result.orphans.length === 0) {
        console.log((0, ui_1.ok)('No orphan settings files found.'));
        console.log('');
        return;
    }
    console.log((0, ui_1.table)(result.orphans.map((orphan) => {
        const status = orphan.validation.valid ? (0, ui_1.color)('[OK]', 'success') : (0, ui_1.color)('[X]', 'error');
        const issueSummary = orphan.validation.issues.length > 0
            ? orphan.validation.issues[0].message
            : 'Ready to register';
        return [orphan.name, status, issueSummary];
    }), {
        head: ['Profile', 'Status', 'Validation'],
        colWidths: [20, 10, 64],
    }));
    console.log('');
    if (!register) {
        console.log((0, ui_1.info)('To register discovered profiles:'));
        console.log(`  ${(0, ui_1.color)('ccs api discover --register', 'command')}`);
        console.log('');
        return;
    }
    const registration = (0, services_1.registerApiProfileOrphans)({
        target: targetParsed.target || 'claude',
        force,
    });
    console.log((0, ui_1.ok)(`Registered: ${registration.registered.length}`));
    if (registration.skipped.length > 0) {
        console.log((0, ui_1.warn)(`Skipped: ${registration.skipped.length}`));
        registration.skipped.forEach((item) => {
            console.log(`  - ${item.name}: ${item.reason}`);
        });
    }
    console.log('');
}
exports.handleApiDiscoverCommand = handleApiDiscoverCommand;
//# sourceMappingURL=discover-command.js.map