/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { getEnvironmentByName, VERSION, writeRepoConfig } from '@microsoft/power-apps-actions';
import { getCliLogger, getSettings } from '../CliSettings.js';
import { createDefaultStringOption } from '../CliUtils.js';
import { HelpStrings } from '../Constants/HelpStrings.js';
import { UsageError } from '../Errors/CliError.js';
import { printInfo, printSuccess } from '../Utils/ConsoleOutput.js';
import { InitArguments } from './VerbConstants.js';
export async function initAsync(argumentProvider) {
    const settings = getSettings();
    if (settings.appConfig) {
        throw new UsageError('power.config.json already exists in this directory. Use a new directory or delete the existing config.');
    }
    createOptionSchema(argumentProvider);
    await argumentProvider.runVerb();
    const logger = getCliLogger();
    const initScenario = logger.trackScenario('Init');
    try {
        // Validate required options
        const environmentId = argumentProvider.getEnvironmentId() ||
            (await argumentProvider.getOption('environmentId'));
        const region = await argumentProvider.getOption('cloud');
        if (!environmentId) {
            throw new UsageError('Argument environmentId is required. Use --environmentId or -e to specify it.');
        }
        const environmentExists = await validateEnvironmentExists(environmentId);
        if (!environmentExists) {
            throw new Error(`Environment '${environmentId}' not found. Please verify the environment ID and ensure you have access to it.`);
        }
        const displayName = await argumentProvider.getOption('displayName');
        const description = await argumentProvider.getOption('description');
        const buildPath = await argumentProvider.getOption('buildPath');
        const fileEntryPoint = await argumentProvider.getOption('fileEntryPoint');
        const appUrl = await argumentProvider.getOption('appUrl');
        const logoPath = await argumentProvider.getOption('logoPath');
        const appConfig = {
            version: VERSION,
            appId: null, // This will be set later when the app is created
            appDisplayName: displayName,
            region,
            environmentId,
            description,
            buildPath,
            buildEntryPoint: fileEntryPoint,
            localAppUrl: appUrl,
            logoPath,
            connectionReferences: {},
            databaseReferences: {},
        };
        await writeRepoConfig(settings.fileConfig.powerConfigPath, appConfig);
        initScenario.complete();
        printSuccess(`Created power.config.json for ${displayName}.`);
        printInfo("Hint: Run 'npx power-apps add-data-source' to connect data, or 'npx power-apps run' to start locally.");
    }
    catch (error) {
        initScenario.failure({ error: error instanceof Error ? error.message : String(error) });
        throw error;
    }
}
function createOptionSchema(argumentProvider) {
    argumentProvider.setDescription(HelpStrings.Verbs.Init.Description);
    argumentProvider.addExamples(HelpStrings.Verbs.Init.Examples);
    argumentProvider.addOptions([
        createDefaultStringOption({
            flags: {
                key: InitArguments.DisplayName.name,
                alias: InitArguments.DisplayName.alias,
            },
            env: InitArguments.DisplayName.envVar,
            message: InitArguments.DisplayName.promptMessage,
            description: HelpStrings.Verbs.Init.Options.DisplayName,
        }),
        createDefaultStringOption({
            flags: {
                key: InitArguments.Description.name,
                alias: InitArguments.Description.alias,
            },
            env: InitArguments.Description.envVar,
            default: ' ',
            message: InitArguments.Description.promptMessage,
            description: HelpStrings.Verbs.Init.Options.Description,
        }),
        createDefaultStringOption({
            flags: {
                key: InitArguments.BuildPath.name,
                alias: InitArguments.BuildPath.alias,
            },
            env: InitArguments.BuildPath.envVar,
            message: InitArguments.BuildPath.promptMessage,
            initialValue: InitArguments.BuildPath.initialValue,
            default: './dist',
            description: HelpStrings.Verbs.Init.Options.BuildPath,
        }),
        createDefaultStringOption({
            flags: {
                key: InitArguments.FileEntryPoint.name,
                alias: InitArguments.FileEntryPoint.alias,
            },
            env: InitArguments.FileEntryPoint.envVar,
            message: InitArguments.FileEntryPoint.promptMessage,
            initialValue: InitArguments.FileEntryPoint.initialValue,
            default: 'index.html',
            description: HelpStrings.Verbs.Init.Options.FileEntryPoint,
        }),
        createDefaultStringOption({
            flags: {
                key: InitArguments.AppUrl.name,
                alias: InitArguments.AppUrl.alias,
            },
            env: InitArguments.AppUrl.envVar,
            message: InitArguments.AppUrl.promptMessage,
            initialValue: InitArguments.AppUrl.initialValue,
            default: 'http://localhost:3000',
            description: HelpStrings.Verbs.Init.Options.AppUrl,
        }),
        createDefaultStringOption({
            flags: {
                key: InitArguments.LogoPath.name,
                alias: InitArguments.LogoPath.alias,
            },
            env: InitArguments.LogoPath.envVar,
            message: InitArguments.LogoPath.promptMessage,
            initialValue: InitArguments.LogoPath.initialValue,
            default: 'Default',
            description: HelpStrings.Verbs.Init.Options.LogoPath,
        }),
    ]);
}
/**
 * Validates that an environment exists by pinging the Power Platform API.
 * @param environmentId - The environment ID to validate
 * @returns True if the environment exists, false otherwise
 */
async function validateEnvironmentExists(environmentId) {
    try {
        const environment = await getEnvironmentByName(environmentId);
        return !!environment?.properties;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=Init.js.map