"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractLaunchActivityFromAndroidManifest = extractLaunchActivityFromAndroidManifest;
const adbkit_apkreader_1 = __importDefault(require("@devicefarmer/adbkit-apkreader"));
const loggingProvider_1 = require("@mablhq-internal/runtime/providers/logging/loggingProvider");
async function extractLaunchActivityFromAndroidManifest(appPath) {
    try {
        const reader = await adbkit_apkreader_1.default.open(appPath);
        const manifest = await reader.readManifest();
        const { firstLaunchActivity } = parseManifest(manifest);
        return firstLaunchActivity;
    }
    catch (error) {
        loggingProvider_1.logger.warn('Failed to identify launch activity', error);
    }
    return undefined;
}
const MAIN_ACTION = 'android.intent.action.MAIN';
const LAUNCHER_CATEGORY = 'android.intent.category.LAUNCHER';
function parseManifest(manifest) {
    const result = {
        firstLaunchActivity: undefined,
    };
    if (!manifest.application) {
        return result;
    }
    for (const activity of [
        ...(manifest.application.activities ?? []),
        ...(manifest.application.activityAliases ?? []),
    ]) {
        if (activity.enabled === false || !activity.intentFilters?.length) {
            continue;
        }
        for (const { actions, categories } of activity.intentFilters) {
            if (!actions?.length || !categories?.length) {
                continue;
            }
            const isMainAction = actions.some(({ name }) => name === MAIN_ACTION);
            const isLauncherCategory = categories.some(({ name }) => name === LAUNCHER_CATEGORY);
            if (isMainAction && isLauncherCategory) {
                result.firstLaunchActivity = activity.name;
                return result;
            }
        }
    }
    return result;
}
