"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 });
exports.handleApiImportCommand = void 0;
const fs = __importStar(require("fs"));
const services_1 = require("../../api/services");
const ui_1 = require("../../utils/ui");
const prompt_1 = require("../../utils/prompt");
const arg_extractor_1 = require("../arg-extractor");
const shared_1 = require("./shared");
function renderValidationIssue(issue) {
    const indicator = issue.level === 'error' ? (0, ui_1.color)('[X]', 'error') : (0, ui_1.color)('[!]', 'warning');
    console.log(`${indicator} ${issue.message}`);
}
async function handleApiImportCommand(args) {
    await (0, ui_1.initUI)();
    const force = (0, arg_extractor_1.hasAnyFlag)(args, ['--force']);
    const yes = (0, arg_extractor_1.hasAnyFlag)(args, ['--yes', '-y']);
    const nameExtracted = (0, arg_extractor_1.extractOption)(args, ['--name'], {
        knownFlags: ['--name', '--target', '--force', '--yes', '-y'],
    });
    if (nameExtracted.found && (nameExtracted.missingValue || !nameExtracted.value)) {
        console.log((0, ui_1.fail)('Missing value for --name'));
        process.exit(1);
    }
    const targetParsed = (0, shared_1.parseOptionalTargetFlag)(nameExtracted.remainingArgs, [
        '--name',
        '--target',
        '--force',
        '--yes',
        '-y',
    ]);
    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: ['--force', '--yes', '-y'],
        maxPositionals: 1,
    });
    if (syntax.errors.length > 0) {
        syntax.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exit(1);
    }
    const importPath = syntax.positionals[0];
    if (!importPath) {
        console.log((0, ui_1.fail)('Import file path is required. Usage: ccs api import <file> [--name <new-name>]'));
        process.exit(1);
    }
    if (!fs.existsSync(importPath)) {
        console.log((0, ui_1.fail)(`File not found: ${importPath}`));
        process.exit(1);
    }
    let bundle;
    try {
        bundle = JSON.parse(fs.readFileSync(importPath, 'utf8'));
    }
    catch (error) {
        console.log((0, ui_1.fail)(`Invalid JSON file: ${error.message}`));
        process.exit(1);
    }
    if (!yes) {
        const confirmed = await prompt_1.InteractivePrompt.confirm(`Import profile bundle from "${importPath}"?`, {
            default: true,
        });
        if (!confirmed) {
            console.log((0, ui_1.info)('Cancelled'));
            process.exit(0);
        }
    }
    const result = (0, services_1.importApiProfileBundle)(bundle, {
        name: nameExtracted.value,
        target: targetParsed.target,
        force,
    });
    if (!result.success) {
        console.log((0, ui_1.fail)(result.error || 'Failed to import profile'));
        if (result.validation?.issues?.length) {
            console.log('');
            result.validation.issues.forEach(renderValidationIssue);
        }
        process.exit(1);
    }
    console.log((0, ui_1.ok)(`Profile imported: ${result.name}`));
    result.warnings?.forEach((warningMessage) => console.log((0, ui_1.warn)(warningMessage)));
    console.log('');
}
exports.handleApiImportCommand = handleApiImportCommand;
//# sourceMappingURL=import-command.js.map