"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const FindStrategy_1 = __importStar(require("./FindStrategy"));
const messaging_1 = require("@mablhq-internal/runtime/core/messaging/messaging");
const execution_1 = require("@mablhq-internal/runtime/execution");
class VisualFindStrategy extends FindStrategy_1.default {
    constructor() {
        super();
    }
    getName() {
        return 'VisualFindStrategy';
    }
    isApplicable(descriptor) {
        return (super.isApplicable(descriptor) &&
            !!this.getPlatformSelector(descriptor)?.find_prompt);
    }
    getFindTimeout() {
        return 10_000;
    }
    async findElement(driver, executionContext, descriptor, isShortCircuited) {
        if (isShortCircuited()) {
            return undefined;
        }
        const startTime = performance.now();
        const platformSelector = this.getPlatformSelector(descriptor);
        if (!platformSelector?.find_prompt) {
            throw new Error('Selector required but not found for visual find.');
        }
        const screenshot = await driver.takeScreenshot();
        const workspaceId = executionContext.testContext.test.workspace_id ??
            executionContext.testContext.test.organization_id;
        if (!workspaceId) {
            throw new Error('Workspace ID required but not found for visual find.');
        }
        const findPrompt = `${executionContext.variables.resolve(platformSelector.find_prompt)}`;
        const boundingBoxPercentages = await executionContext.mablApiClient.findElementImage(screenshot, findPrompt, workspaceId, true, executionContext.generateTestCreationContext());
        let boundingBox;
        if (boundingBoxPercentages?.found) {
            const windowSize = await executionContext.mobileTestEnvironment.getWindowSize();
            boundingBox = (0, execution_1.createBoundingBoxFromViewport)(windowSize, boundingBoxPercentages.bounding_box);
            executionContext.log.debug(`Returning visual find percentages [${JSON.stringify(boundingBoxPercentages)}] with device screen size [${JSON.stringify(windowSize)}] resulting in bounding box [${JSON.stringify(boundingBox)}]`, {
                executionPhase: messaging_1.ExecutionPhase.DURING_ACTION,
            });
            executionContext.log.info(`Found element with bounding box ${JSON.stringify(boundingBox)} using visual find`, {
                executionPhase: messaging_1.ExecutionPhase.DURING_ACTION,
            });
        }
        const elapsed = performance.now() - startTime;
        executionContext.log.debug(`Visual find elapsed time: ${elapsed}ms`, {
            executionPhase: messaging_1.ExecutionPhase.DURING_ACTION,
        });
        return Promise.resolve(!!boundingBox
            ? {
                visualFindBoundingBox: boundingBox,
                context: FindStrategy_1.NATIVE_CONTEXT,
                scoredCandidates: [],
            }
            : undefined);
    }
}
exports.default = VisualFindStrategy;
