import { test, expect, Page, BrowserContext, Locator } from "@playwright/test";
import { RegistrationPage } from "../../pages/RegistrationPage";
import { waitForActivationCode } from "../../utils/ActivationCodeUtils";
import { ChatPage } from "../../pages/ChatPage";
import { WidgetCreationProcess } from "../../pages/widgetCreationProcess";
import { DatasetCreationProcess } from "../../pages/datasetCreationProcess";
import { MediaCreationProcess } from "../../pages/mediaCreationProcess";
import { ModelCreationProcess } from "../../pages/modelCreationProcess";
// @ts-ignore
import path from "path";

let page: Page;
let context: BrowserContext;
let onboardingFullName: string;
let onboardingEmail: string;
let onboardingPassword: string;
let onboardingSubdomain: string;
let onboardingWalletAddress: string;
let chatPage: ChatPage;
const SEARCH_LIMIT_MESSAGE = /Your search query limit of 10 has reached\./i;
const MARKETPLACE_SEARCH_PROMPT = 'I need to detect telecommunications fraud by CDR analyser';
const PUBLISHED_AGENT_TITLE_REGEX = /PUBLISHED CDR analyzer for/i;
const CDR_PURCHASED_ASSET_TITLE = /CDR analyzer for fraud prevention/i;
const MCP_TYPE_ID = '8562c8e6-776d-4989-8398-589a5d5d1f38';
const MCP_CREDENTIAL_NAME = 'CDR_data';
const CDR_AGENT_DESCRIPTION = 'This playbook is designed to guide junior analysts in utilizing Call Detail Records (CDRs) to detect, analyze, and report telecommunications fraud.';
const CDR_AGENT_SOURCES = 'File system containing CDR file, list of international dialing prefixes, repository of tracked telephone numbers';
const CDR_ANALYSIS_INSTRUCTIONS = `● Identifying Pattern:
○ Zero/Low Duration: CALL_DURATION is often 0 or <3 seconds.
○ Massive B-Party Variance: Single A-Party calling thousands of unique B-Parties rapidly.
○ High Error/Busy Rates: Many calls may fail as victims are active on other calls.
○ Timing: often occurs during unsociable hours (late night) to ensure missed calls.
C. SIM Boxing (Interconnect Bypass)
Fraudsters use a device (SIM Box) holding hundreds of consumer SIM cards to terminate international VoIP calls over local mobile networks, bypassing official international gateways and interconnect fees.
● Identifying Pattern:
○ Stationary Location: High volume of calls from a single CELL_GLOBAL_ID (or very few adjacent cells) despite mobile behavior.
○ Imbalanced Traffic: Almost exclusively Mobile Originating Calls (MOC). A real human receives calls (MTC).
○ IMEI Rotation: High number of different IMSIs (SIMs) appearing on a single IMEI (device slot) sequentially.
○ No SMS/Data: Often voice-only traffic, lacking normal human usage mix.
D. Account Takeover (ATO) / SIM Swap
A fraudster gains control of a victim's phone number by convincing the carrier to port it to a new SIM card.
● Identifying Pattern:
○ IMSI Change: The A_PARTY_NO (MSISDN) remains the same, but the IMSI changes mid-activity stream.
○ Subsequent Anomaly: Immediately following the IMSI change, the line is used for OTP reception (incoming SMS) or high-value IRSF calls.
Phase 1: Data Validation & Baselining
1. Sanity Check: Ensure timestamps are sequential and cover the expected period.
2. Volume Check: Calculate total calls per hour. Look for unexplained spikes deviating more than 3 standard deviations from the average.
Phase 2: Aggregation & Filtering (The Hunting Phase)
● Action A: Find Top Talkers (Potential IRSF/SIM Box)
○ Query: Group by A_PARTY_NO, sum CALL_DURATION, count distinct B_PARTY_NO.
● Action B: Location Analysis (SIM Box Detection)
○ Query: Group by A_PARTY_NO, count distinct CELL_GLOBAL_ID.
● Action C: Destination Monitoring (IRSF)
○ Query: Filter for international calls to watchlist countries.
Phase 3: Deep Dive Investigation
1. Ratio Analysis: Calculate MOC/MTC ratio (Normal: 0.8-1.2, >10 suspicious).
2. Velocity Check: Calculate time difference between consecutive calls for physical feasibility.`;

const AGRICULTURE_AGENT_DESCRIPTION =
    "The Agriculture Agent is an intelligent assistant designed to help farmers, agricultural planners, and agribusiness professionals make informed decisions using agricultural data and insights.";
const AGRICULTURE_AGENT_INSTRUCTIONS =
    "Assist users with crop recommendations, planting and harvesting schedules, pest and disease risk analysis, irrigation planning, and yield forecasting using the provided agricultural context and data.";
const AGRICULTURE_AGENT_SOURCES =
    "Historical weather data, real-time weather forecasts, rainfall data, temperature and humidity data, and climate trend data.";
const SPAM_EMAIL_MODEL_NAME = "Spam Email Detection";
const SPAM_EMAIL_MODEL_DESCRIPTION = "A model for predicting spam emails";
const SPAM_EMAIL_MODEL_THUMBNAIL = path.join(process.cwd(), "asset-creation-files", "model-asset.jpg");
const SPAM_EMAIL_MODEL_FILE = path.join(process.cwd(), "asset-creation-files", "rf.pkl");
const MEDICAL_DIAGNOSIS_MODEL_NAME = "Medical diagnosis systems";
const MEDICAL_DIAGNOSIS_MODEL_DESCRIPTION = "A model to detect diseases from medical data";
const MEDICAL_DIAGNOSIS_MODEL_THUMBNAIL = path.join(process.cwd(), "asset-creation-files", "model-asset.jpg");
const MEDICAL_DIAGNOSIS_MODEL_FILE = path.join(process.cwd(), "asset-creation-files", "rf.pkl");
const MEDICAL_DIAGNOSIS_CREATOR_EMAIL = "anuka@datafab.ai";
const MEDICAL_DIAGNOSIS_CREATOR_PASSWORD = "anuka@123";
const MEDICAL_DIAGNOSIS_VIEWER_EMAIL = "nipuna@datafab.ai";
const MEDICAL_DIAGNOSIS_VIEWER_PASSWORD = "nipuna@123";
const CANCER_PREDICTION_MODEL_NAME = "Cancer Prediction";
const CANCER_PREDICTION_MODEL_DESCRIPTION = "A model for predicting cancers";
const CANCER_PREDICTION_MODEL_THUMBNAIL = "asset-creation-files/model-asset.jpg";
const CANCER_PREDICTION_MODEL_FILE = "asset-creation-files/rf.pkl";
const VEHICLE_TYPE_PREDICTOR_MODEL_NAME = "Vehicle type Predictor";
const VEHICLE_TYPE_PREDICTOR_MODEL_DESCRIPTION = "A model to predict the vehicle type";
const VEHICLE_TYPE_PREDICTOR_MODEL_THUMBNAIL = "asset-creation-files/model-asset.jpg";
const VEHICLE_TYPE_PREDICTOR_MODEL_FILE = "asset-creation-files/rf.pkl";
const VEHICLE_TYPE_PREDICTOR_MODEL_UPDATED_NAME = "Vehicle type Predictor - B";
const VEHICLE_TYPE_PREDICTOR_MODEL_UPDATED_DESCRIPTION = "A model to predict the vehicle type.";

async function isVisible(locator: Locator, timeout = 1500): Promise<boolean> {
    return locator.isVisible({ timeout }).catch(() => false);
}

function escapeRegExp(value: string) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

async function expectTerminalMessage(page: Page) {
    const terminalMessage = page
        .locator('div')
        .filter({
            hasText: /No active wallet found\. Please activate a DAAC wallet to continue\.|Your search query limit of 10 has reached\./i
        })
        .last();

    await expect(terminalMessage).toBeVisible({ timeout: 180000 });
}

async function clearChat() {
    await chatPage.clearChatAndCanvas();
    await page.waitForTimeout(500);
}

async function purchaseDdaFromMarketplace() {
    const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill('open marketplace\n');

    await expect(
        page.getByLabel('Widget content').getByRole('paragraph').filter({ hasText: /^Marketplace$/ })
    ).toBeVisible({ timeout: 180000 });

    await page.getByRole('button', { name: 'Maximize widget' }).click();
    await page.locator('#btn_expand_domain_driven_agent_0').click();
    await page.getByRole('button', { name: 'Purchase' }).click();
    await page.getByRole('button', { name: 'Unlimited 0.01 DAAC' }).click();
    await page.getByRole('button', { name: 'Purchase' }).click();
    await expect(page.getByText('Purchase from pricing plan')).toBeVisible({ timeout: 60000 });
}

async function purchaseAgricultureCuratedDataFromMarketplace() {
    const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill('I need a agriculture dataset');
    await chatInput.press('Enter');

    const marketplaceLabel = page.getByLabel('Widget content').getByText('Marketplace').first();
    await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });
    await marketplaceLabel.click();

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
    await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
    await curatedDataButton.click();

    const expandFirstDatasetButton = page.locator('#btn_expand_datasets_0').first();
    await expect(expandFirstDatasetButton).toBeVisible({ timeout: 60000 });
    await expandFirstDatasetButton.click();

    const purchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
    await expect(purchaseButton).toBeVisible({ timeout: 30000 });
    await purchaseButton.click();

    const pricingButton = page.getByRole('button', { name: /unlimited\s*0\.01 DAAC/i }).first();
    await expect(pricingButton).toBeVisible({ timeout: 30000 });
    await pricingButton.click();

    const confirmPurchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
    await expect(confirmPurchaseButton).toBeVisible({ timeout: 30000 });
    await confirmPurchaseButton.click();

    await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });
    await page.getByRole('button', { name: 'close' }).first().click();

    const refreshChatButton = page.locator('#btn-refresh-chat').first();
    if (await refreshChatButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await refreshChatButton.click();
    }
}

async function purchaseAgricultureUtilityFromMarketplace() {
    const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
    const sendButton = page.locator('#chat-input').getByRole('button').first();
    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill('I need a agriculture utility');
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    const marketplaceLabel = page.getByLabel('Widget content').getByText('Marketplace').first();
    await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });
    await marketplaceLabel.click();

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const utilitiesButton = page.getByRole('button', { name: 'Utilities' }).first();
    await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
    await utilitiesButton.click();

    const utilityActionButton = page.locator('.absolute.right-3').first();
    if (await utilityActionButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await utilityActionButton.click();
        await utilityActionButton.click();
    }

    const expandFirstUtilityButton = page.locator('#btn_expand_utilities_0').first();
    await expect(expandFirstUtilityButton).toBeVisible({ timeout: 60000 });
    await expandFirstUtilityButton.click();

    const purchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
    await expect(purchaseButton).toBeVisible({ timeout: 30000 });
    await purchaseButton.click();

    const pricingButton = page.getByRole('button', { name: /Unlimited Use\s*1\.00 DAAC/i }).first();
    await expect(pricingButton).toBeVisible({ timeout: 30000 });
    await pricingButton.click();

    const confirmPurchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
    await expect(confirmPurchaseButton).toBeVisible({ timeout: 30000 });
    await confirmPurchaseButton.click();

    await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });
}

async function openFirstUtilityFromInventory() {
    await page.getByRole('button', { name: 'Open inventory' }).click();
    await page.getByRole('button', { name: 'Utilities' }).click();
    await page.locator('.absolute.right-3').first().click();
}

async function openUtilityCreationStudioFromChat(prompt = "I need to create a utility without a domain") {
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();
    const registrationPage = new RegistrationPage(page);

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill(prompt);
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await registrationPage.logoutFromChatUi();
    await registrationPage.loginFromSignIn(onboardingEmail, onboardingPassword);
    await page.waitForURL(/robocorp-fe-dev\.promptyf\.cloud/i, { timeout: 60000 }).catch(() => null);
    await chatPage.waitForChatReady();

    const skipBusinessProfileButton = page.getByRole("button", { name: /Skip for now/i }).first();
    if (await skipBusinessProfileButton.isVisible({ timeout: 5000 }).catch(() => false)) {
        await skipBusinessProfileButton.click();
    }

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill(prompt);
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    const dataStudioButton = page.getByText("Data Studio", { exact: true }).first();
    await expect(dataStudioButton).toBeVisible({ timeout: 180000 });
    await page.waitForTimeout(5000);
    await dataStudioButton.click();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();
}

async function completeUtilitySetupUntilAssetsStep() {
    const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
    const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
    const domainSelector = page.locator(".flex.flex-1 > div:nth-child(3) > .relative.flex").first();
    const defaultDomainButton = page.getByRole("button", { name: "default" }).first();
    const tagsCombobox = page.getByRole("combobox", { name: "Tags/categories" }).first();
    const thumbnailInput = page.getByRole("button", { name: "Thumbnail*" }).first();
    const nextButton = page.getByRole("button", { name: "Next" }).first();

    await expect(purposeInput).toBeVisible({ timeout: 30000 });
    await purposeInput.fill("Travel Planner Utility");

    await expect(descriptionInput).toBeVisible({ timeout: 30000 });
    await descriptionInput.fill(
        "The Travel Planner Utility helps users organize destinations, itineraries, budgets, and bookings in one place."
    );

    await expect(domainSelector).toBeVisible({ timeout: 30000 });
    await domainSelector.click();
    await expect(defaultDomainButton).toBeVisible({ timeout: 30000 });
    await defaultDomainButton.click();

    await expect(nextButton).toBeVisible({ timeout: 30000 });
    await expect(nextButton).toBeEnabled({ timeout: 30000 });
    await nextButton.click();

    await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
    await tagsCombobox.click();
    await tagsCombobox.fill("travel");
    await page.getByRole("option", { name: "Travel", exact: true }).first().click();

    await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
    await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "asset-image.jpg"));

    await page.getByRole("button", { name: "Next" }).first().click();

    const workflowSearch = page.getByRole("textbox", { name: "Select" }).first();
    await expect(workflowSearch).toBeVisible({ timeout: 30000 });
    await workflowSearch.click();
    await page.getByRole("button", { name: "Manual Intake Workflow" }).first().click();
    await page.getByRole("button", { name: "Next" }).first().click();
}

async function addFirstThreePublishedUtilityAssets() {
    const addAssetsButton = page.getByRole("button", { name: "Add +" }).first();
    await expect(addAssetsButton).toBeVisible({ timeout: 30000 });
    await addAssetsButton.click();

    const publishedAssets = page.getByRole("button", { name: /^PUBLISHED /i });
    await expect(publishedAssets.first()).toBeVisible({ timeout: 30000 });
    const publishedCount = await publishedAssets.count();
    if (publishedCount < 3) {
        throw new Error("Need at least three published assets to validate utility update flow.");
    }

    await publishedAssets.nth(0).click();
    await publishedAssets.nth(1).click();
    await publishedAssets.nth(2).click();
    await page.getByRole("button", { name: "Add" }).first().click();
}

async function replaceOneUtilityAssetAndVerifyConnectionChangeWarning(): Promise<boolean> {
    const addAssetsButton = page.getByRole("button", { name: "Add +" }).first();
    await expect(addAssetsButton).toBeVisible({ timeout: 30000 });
    await addAssetsButton.click();

    const publishedAssets = page.getByRole("button", { name: /^PUBLISHED /i });
    await expect(publishedAssets.first()).toBeVisible({ timeout: 30000 });
    const publishedCount = await publishedAssets.count();
    if (publishedCount < 2) {
        return false;
    }

    await publishedAssets.nth(0).click();
    await page.getByRole("button", { name: "Add" }).first().click();

    const warningMessage = page
        .getByText(/warning|changed.*api|api.*changed|connection.*changed|asset.*changed/i)
        .first();
    await expect(warningMessage).toBeVisible({ timeout: 30000 });

    const setApiButton = page.getByRole("button", { name: "Set API" }).first();
    await expect(setApiButton).toBeVisible({ timeout: 30000 });
    return true;
}

async function dragConnectUtilityNodes() {
    const sourceHandles = page.locator(".react-flow__handle-right");
    const targetHandles = page.locator(".react-flow__handle-left");
    await expect(sourceHandles.first()).toBeVisible({ timeout: 30000 });
    await expect(targetHandles.first()).toBeVisible({ timeout: 30000 });

    await sourceHandles.first().dragTo(targetHandles.first());

    const sourceCount = await sourceHandles.count();
    const targetCount = await targetHandles.count();
    if (sourceCount > 1 && targetCount > 1) {
        await sourceHandles.nth(1).dragTo(targetHandles.nth(1)).catch(() => {});
    }
}

async function openPublishedUtilityAndRunPrompt(prompt: string) {
    const openInventoryButton = page.getByRole("button", { name: "Open inventory" }).first();
    await expect(openInventoryButton).toBeVisible({ timeout: 30000 });
    await openInventoryButton.click();

    const manageAssetsText = page.getByText("Manage your assets").first();
    await expect(manageAssetsText).toBeVisible({ timeout: 30000 });
    await manageAssetsText.click();

    const utilitiesButton = page.getByRole("button", { name: "Utilities" }).first();
    await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
    await utilitiesButton.click();

    const publishedFilterButton = page.getByRole("button", { name: "PUBLISHED", exact: true }).first();
    await expect(publishedFilterButton).toBeVisible({ timeout: 30000 });
    await publishedFilterButton.click();

    const previousCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(prompt);
    await chatPage.waitForNewReceivedMessage(previousCount, 180000);
    await expect(chatPage.receivedMessageBubbles.last()).toBeVisible({ timeout: 60000 });
}

async function openFirstDraftUtilityInInventoryAndSwitchToEditor() {
    const openInventoryButton = page.getByRole("button", { name: "Open inventory" }).first();
    await expect(openInventoryButton).toBeVisible({ timeout: 60000 });
    await openInventoryButton.click();

    const manageAssetsText = page.getByText("Manage your assets").first();
    await expect(manageAssetsText).toBeVisible({ timeout: 60000 });
    await manageAssetsText.click();

    const utilitiesButton = page.getByRole("button", { name: "Utilities" }).first();
    await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
    await utilitiesButton.click();

    const draftFilterButton = page.getByRole("button", { name: "DRAFT", exact: true }).first();
    if (await draftFilterButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await draftFilterButton.click();
    }

    const draftUtilityButton = page.getByRole("button", { name: /^DRAFT /i }).first();
    await expect(draftUtilityButton).toBeVisible({ timeout: 60000 });
    await draftUtilityButton.locator("#btn_see_details").click();

    const editButton = page.locator("#edit").first();
    if (await editButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await expect(editButton).toBeEnabled({ timeout: 30000 });
        await editButton.click();
    } else {
        const actionButton = page.getByRole("button").first();
        await expect(actionButton).toBeVisible({ timeout: 30000 });
        await actionButton.click();
    }

    const closeWidgetButton = page.getByRole("button", { name: "Close widget" }).first();
    if (await closeWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeWidgetButton.click();
    }

    const dataStudioButton = page.getByText("Data Studio", { exact: true }).first();
    await expect(dataStudioButton).toBeVisible({ timeout: 60000 });
    await dataStudioButton.click();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();
}

async function waitForWidgetStartOutcome(page: Page): Promise<'terminal' | 'continue'> {
    const terminalMessage = page
        .locator('div')
        .filter({
            hasText: /No active wallet found\. Please activate a DAAC wallet to continue\.|Your search query limit of 10 has reached\./i
        })
        .last();
    const namePrompt = page
        .locator('body')
        .getByText(/provide the name of your new widget|name of your new widget/i)
        .first();

    const deadline = Date.now() + 180000;
    while (Date.now() < deadline) {
        if (await terminalMessage.isVisible({ timeout: 500 }).catch(() => false)) {
            return 'terminal';
        }

        if (await namePrompt.isVisible({ timeout: 500 }).catch(() => false)) {
            return 'continue';
        }

        await page.waitForTimeout(500);
    }

    throw new Error('Timed out waiting for model start outcome.');
}

async function createDraftWidget() {
    const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
    const sendButton = page.locator('#chat-input').getByRole('button').first();
    const namePrompt = page
        .locator('body')
        .getByText(/provide the name of your new widget|name of your new widget/i)
        .first();

    const widget = new WidgetCreationProcess(page);
    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await expect(chatInput).toBeEnabled({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill('I need to create a widget without a domain');
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    const outcome = await waitForWidgetStartOutcome(page);
    if (outcome === 'terminal') {
        await expectTerminalMessage(page);
        throw new Error('Widget creation was blocked before reaching the draft limit.');
    }

    await expect(namePrompt).toBeVisible({ timeout: 60000 });
    await widget.provideWidgetName();
    await widget.provideDescription();
    await widget.provideInstructions();
    await widget.provideSourceType();
    await widget.selectFirstWidgetOption();
    await widget.createWidget();
    await expect(page.getByText('Widget created successfully!')).toBeVisible({ timeout: 120000 });
}

async function deleteFirstAgenticWidgetDraft() {
    await page.getByRole('button', { name: 'Open inventory' }).click();
    await page.getByRole('button', { name: 'Agentic Widget' }).click();
    await page.locator('.absolute.right-3').first().click();
    await page.locator('#bulk-delete').click();
    await page.getByRole('button', { name: 'Confirm' }).click();
    await expect(page.getByRole('heading', { name: 'Successfully Deleted!' })).toBeVisible({ timeout: 30000 });
}

async function sendSearchAndWaitForResponse(query: string) {
    const previousCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(query);
    await chatPage.waitForNewReceivedMessage(previousCount, 180000);
    return chatPage.getLastReceivedMessage();
}

async function sendChatPromptAndWaitForInput(text: string) {
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();
    const previousReceivedCount = await chatPage.getReceivedMessageCount();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill(text);
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await chatPage.waitForNewReceivedMessage(previousReceivedCount, 300000);
    await page.waitForTimeout(5000);
}

async function createAndPublishAgentWithoutUnlimitedPricingForUtility() {
    const uniqueAgentName = `Agriculture Agent ${Date.now()}`;

    await sendChatPromptAndWaitForInput("I need to create an agent without domain");
    await sendChatPromptAndWaitForInput(uniqueAgentName);
    await sendChatPromptAndWaitForInput(AGRICULTURE_AGENT_DESCRIPTION);

    const agenticFlowButton = page.getByRole("button", { name: /Agentic Flow/i }).first();
    await expect(agenticFlowButton).toBeVisible({ timeout: 180000 });
    await agenticFlowButton.click();

    await sendChatPromptAndWaitForInput(AGRICULTURE_AGENT_INSTRUCTIONS);
    await sendChatPromptAndWaitForInput(AGRICULTURE_AGENT_SOURCES);

    const createAgentButton = page.getByRole("button", { name: /Create DDA/i }).first();
    await expect(createAgentButton).toBeVisible({ timeout: 180000 });
    await createAgentButton.click();
    await expect(page.getByRole("heading", { name: /Successfully Created!/i }).first()).toBeVisible({ timeout: 180000 });

    const testButton = page.getByRole("button", { name: /^Test$/i }).first();
    await expect(testButton).toBeVisible({ timeout: 60000 });
    await testButton.click();

    const understandButton = page.getByRole("button", { name: /I understand/i }).first();
    if (await understandButton.isVisible({ timeout: 5000 }).catch(() => false)) {
        await understandButton.click();
    }

    const fileUploadButton = page.getByRole("button", { name: /File Upload Upload Data file/i }).first();
    await expect(fileUploadButton).toBeVisible({ timeout: 30000 });
    await fileUploadButton.click();

    const thumbnailInput = page.getByRole("button", { name: "Thumbnail" }).first();
    await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
    await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "Tourism_Domain_Guide_2.pdf"));

    const nextButton = page.getByRole("button", { name: "Next" }).first();
    await expect(nextButton).toBeVisible({ timeout: 30000 });
    await page.waitForTimeout(1500);
    const uploadPlaceholder = page.getByText("Drag and drop file here or click to select").first();
    const placeholderVisible = await uploadPlaceholder.isVisible({ timeout: 2000 }).catch(() => false);
    const nextDisabled = await nextButton.isDisabled().catch(() => false);
    if (placeholderVisible && nextDisabled) {
        await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "Tourism_Domain_Guide_3.pdf"));
        await page.waitForTimeout(1500);
    }
    await nextButton.click();

    const testInput = page.getByRole("textbox", { name: "Enter your input query here..." }).first();
    await expect(testInput).toBeVisible({ timeout: 30000 });
    await testInput.fill("Recommend the best crops for dry weather conditions");
    await page.getByRole("button", { name: /^Test$/i }).first().click();

    const closeButton = page.getByRole("button", { name: /^Close$/i }).first();
    await expect(closeButton).toBeVisible({ timeout: 60000 });
    await closeButton.click();

    const publishButton = page.getByRole("button", { name: /^Publish$/i }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const publishDialog = page.getByRole("dialog").first();
    const prerequisitesInput = publishDialog.getByRole("textbox", { name: "Prerequisites" }).first();
    await expect(prerequisitesInput).toBeVisible({ timeout: 30000 });
    await prerequisitesInput.fill("No prerequisites");

    const singleUseInput = page.locator('#int_agent_builder_single_use input[type="text"]').first();
    const fiveUsesInput = page.locator('#int_agent_builder_five_uses input[type="text"]').first();
    await expect(singleUseInput).toBeVisible({ timeout: 30000 });
    await singleUseInput.fill("1");
    await fiveUsesInput.fill("1");

    const confirmButton = page.getByRole("button", { name: /^Confirm$/i }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();
    await expect(page.getByText(/Successfully Published!/i).first()).toBeVisible({ timeout: 120000 });

    return uniqueAgentName;
}

async function completeUtilitySetupUntilAssetsStepForNonUnlimited() {
    const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
    const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
    const domainSelector = page.locator(".flex.flex-1 > div:nth-child(3) > .relative.flex").first();
    const defaultDomainButton = page.getByRole("button", { name: "default" }).first();
    const tagsCombobox = page.getByRole("combobox", { name: "Tags/categories" }).first();
    const thumbnailInput = page.getByRole("button", { name: "Thumbnail*" }).first();
    const nextButton = page.getByRole("button", { name: "Next" }).first();

    await expect(purposeInput).toBeVisible({ timeout: 30000 });
    await purposeInput.fill("Utility Without Unlimited Assets");

    await expect(descriptionInput).toBeVisible({ timeout: 30000 });
    await descriptionInput.fill("Utility test flow that validates assets without unlimited pricing are not available for selection.");

    await expect(domainSelector).toBeVisible({ timeout: 30000 });
    await domainSelector.click();
    await expect(defaultDomainButton).toBeVisible({ timeout: 30000 });
    await defaultDomainButton.click();

    await expect(nextButton).toBeVisible({ timeout: 30000 });
    await expect(nextButton).toBeEnabled({ timeout: 30000 });
    await nextButton.click();

    await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
    await tagsCombobox.click();
    await tagsCombobox.fill("agriculture");
    await tagsCombobox.press("Enter");

    await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
    await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "asset-image.jpg"));

    await page.getByRole("button", { name: "Next" }).first().click();

    const workflowSearch = page.getByRole("textbox", { name: "Select" }).first();
    await expect(workflowSearch).toBeVisible({ timeout: 30000 });
    await workflowSearch.click();
    await page.getByRole("button", { name: "Manual Intake Workflow" }).first().click();
    await page.getByRole("button", { name: "Next" }).first().click();
}

async function fillUtilityDetailsAndVerifyDefaultDomain(purpose: string, description: string) {
    const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
    const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
    const domainLabel = page.getByText(/^Domain$/i).first();
    const nextButton = page.getByRole("button", { name: "Next" }).first();

    await expect(purposeInput).toBeVisible({ timeout: 30000 });
    await purposeInput.fill(purpose);

    await expect(descriptionInput).toBeVisible({ timeout: 30000 });
    await descriptionInput.fill(description);

    await expect(domainLabel).toBeVisible({ timeout: 30000 });
    const defaultDomainText = domainLabel
        .locator("xpath=ancestor::div[1]")
        .locator("xpath=.//*[contains(translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'default')]")
        .first();
    await expect(defaultDomainText).toBeVisible({ timeout: 30000 });

    await expect(nextButton).toBeEnabled({ timeout: 30000 });
}

async function completeUtilitySetupUntilBuilderForDraftSave(purpose: string, description: string) {
    const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
    const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
    const domainInput = page.getByRole("textbox", { name: "Domain of the Utility" }).first();
    const defaultDomainButton = page.getByRole("button", { name: "default" }).first();
    const nextButton = page.getByRole("button", { name: "Next" }).first();

    await expect(purposeInput).toBeVisible({ timeout: 30000 });
    await purposeInput.fill(purpose);

    await expect(descriptionInput).toBeVisible({ timeout: 30000 });
    await descriptionInput.fill(description);

    await expect(domainInput).toBeVisible({ timeout: 30000 });
    await domainInput.click();
    await expect(defaultDomainButton).toBeVisible({ timeout: 30000 });
    await expect(nextButton).toBeEnabled({ timeout: 30000 });
    await nextButton.click();

    const tagsCombobox = page.getByRole("combobox", { name: "Tags/categories" }).first();
    const thumbnailInput = page.getByRole("button", { name: "Thumbnail*" }).first();
    await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
    await tagsCombobox.click();
    await tagsCombobox.fill("travel");
    await page.getByRole("option", { name: "Travel", exact: true }).first().click();

    await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
    await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "asset-image.jpg"));

    await page.getByRole("button", { name: "Next" }).first().click();

    const workflowSearch = page.getByRole("textbox", { name: "Select" }).first();
    await expect(workflowSearch).toBeVisible({ timeout: 30000 });
    await workflowSearch.click();
    await page.getByRole("button", { name: "Manual Intake Workflow" }).first().click();
    await page.getByRole("button", { name: "Next" }).first().click();
}

async function addFirstPublishedUtilityAssetForDraft(): Promise<boolean> {
    const addAssetsButton = page.getByRole("button", { name: "Add +" }).first();
    await expect(addAssetsButton).toBeVisible({ timeout: 30000 });
    await addAssetsButton.click();

    const addButton = page.getByRole("button", { name: "Add" }).first();
    await expect(addButton).toBeVisible({ timeout: 30000 });

    const deadline = Date.now() + 60000;
    while (Date.now() < deadline) {
        const publishedAssetButtons = page.getByRole("button", { name: /PUBLISHED/i });
        const publishedCount = await publishedAssetButtons.count();

        if (publishedCount > 0) {
            const attempts = Math.min(publishedCount, 5);
            for (let i = 0; i < attempts; i++) {
                const candidate = publishedAssetButtons.nth(i);
                if (!(await candidate.isVisible({ timeout: 1000 }).catch(() => false))) {
                    continue;
                }

                await candidate.click();
                if (await addButton.isEnabled({ timeout: 1500 }).catch(() => false)) {
                    await addButton.click();
                    return true;
                }
            }
        }

        await page.waitForTimeout(1000);
    }

    return false;
}

async function waitForMediaStartOutcome(page: Page, media: MediaCreationProcess): Promise<'terminal' | 'continue'> {
    const terminalMessage = page
        .locator('div')
        .filter({
            hasText: /No active wallet found\. Please activate a DAAC wallet to continue\.|Your search query limit of 10 has reached\./i
        })
        .last();

    const deadline = Date.now() + 180000;
    while (Date.now() < deadline) {
        if (await terminalMessage.isVisible({ timeout: 500 }).catch(() => false)) {
            return 'terminal';
        }

        if (
            await media.domainFirstQuestion.isVisible({ timeout: 500 }).catch(() => false) ||
            await media.mediaNamePrompt.isVisible({ timeout: 500 }).catch(() => false)
        ) {
            return 'continue';
        }

        await page.waitForTimeout(500);
    }

    throw new Error('Timed out waiting for media start outcome.');
}

async function waitForModelStartOutcome(page: Page, model: ModelCreationProcess): Promise<'terminal' | 'continue'> {
    const terminalMessage = page
        .locator('div')
        .filter({
            hasText: /No active wallet found\. Please activate a DAAC wallet to continue\.|Your search query limit of 10 has reached\./i
        })
        .last();

    const deadline = Date.now() + 180000;
    while (Date.now() < deadline) {
        if (await terminalMessage.isVisible({ timeout: 500 }).catch(() => false)) {
            return 'terminal';
        }

        if (await model.modelNamePrompt.isVisible({ timeout: 500 }).catch(() => false)) {
            return 'continue';
        }

        await page.waitForTimeout(500);
    }

    throw new Error('Timed out waiting for model start outcome.');
}

async function createAndPublishSpamEmailDetectionModel() {
    const model = new ModelCreationProcess(page);
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await expect(chatInput).toBeEditable({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill("I need to create a new model");
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await expect(page.getByText(/Please provide the name of your new model/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(SPAM_EMAIL_MODEL_NAME);
    await sendButton.click();
    await expect(page.getByText(/please describe/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(SPAM_EMAIL_MODEL_DESCRIPTION);
    await sendButton.click();
    await expect(page.getByText(/Thumbnail Image Uploader/i).first()).toBeVisible({
        timeout: 300000
    });

    await model.uploadThumbnail(SPAM_EMAIL_MODEL_THUMBNAIL);
    await model.uploadModelFile(SPAM_EMAIL_MODEL_FILE);
    await model.createModel();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const publishButton = page.getByRole("button", { name: "Publish" }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const priceInput = page.getByRole("dialog").getByRole("textbox").first();
    await expect(priceInput).toBeVisible({ timeout: 15000 });
    await priceInput.fill("10");
    await page.getByTitle("Confirm").click();

    await expect(page.getByText("Model published successfully!").first()).toBeVisible({
        timeout: 120000
    });
}

async function createAndPublishMedicalDiagnosisModel() {
    const model = new ModelCreationProcess(page);
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await expect(chatInput).toBeEditable({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill("I need to create a new model");
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await expect(page.getByText(/Please provide the name of your new model/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(MEDICAL_DIAGNOSIS_MODEL_NAME);
    await sendButton.click();
    await expect(page.getByText(/please describe/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(MEDICAL_DIAGNOSIS_MODEL_DESCRIPTION);
    await sendButton.click();
    await expect(page.getByText(/Thumbnail Image Uploader/i).first()).toBeVisible({
        timeout: 300000
    });

    await model.uploadThumbnail(MEDICAL_DIAGNOSIS_MODEL_THUMBNAIL);
    await model.uploadModelFile(MEDICAL_DIAGNOSIS_MODEL_FILE);
    await model.createModel();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const publishButton = page.getByRole("button", { name: "Publish" }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const priceInput = page.getByRole("dialog").getByRole("textbox").first();
    await expect(priceInput).toBeVisible({ timeout: 15000 });
    await priceInput.fill("18");
    await page.getByTitle("Confirm").click();
    await page.waitForTimeout(5000);

    await page.locator("html").click();
    await page.waitForTimeout(2000);
    const closeWidgetButton = page.getByRole("button", { name: "Close widget" }).first();
    if (await closeWidgetButton.isVisible({ timeout: 3000 }).catch(() => false)) {
        await closeWidgetButton.click();
    }
}

async function createCancerPredictionModelAsDraft() {
    const model = new ModelCreationProcess(page);
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await expect(chatInput).toBeEditable({ timeout: 30000 });
    await chatInput.fill("I need to create a new model");
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await expect(page.getByText(/Please provide the name of your new model/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(CANCER_PREDICTION_MODEL_NAME);
    await sendButton.click();
    await expect(page.getByText(/please describe/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(CANCER_PREDICTION_MODEL_DESCRIPTION);
    await sendButton.click();
    await expect(page.getByText(/Thumbnail Image Uploader/i).first()).toBeVisible({
        timeout: 300000
    });

    await model.uploadThumbnail(CANCER_PREDICTION_MODEL_THUMBNAIL);
    await model.uploadModelFile(CANCER_PREDICTION_MODEL_FILE);
    await model.createModel();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const closeButton = page.getByRole("button", { name: "Close", exact: true }).first();
    await expect(closeButton).toBeVisible({ timeout: 30000 });
    await closeButton.click();
}

async function createVehicleTypePredictorModelAsDraft() {
    const model = new ModelCreationProcess(page);
    const chatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
    const sendButton = page.locator("#chat-input").getByRole("button").first();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await expect(chatInput).toBeEditable({ timeout: 30000 });
    await chatInput.fill("I need to create a new model");
    await expect(sendButton).toBeVisible({ timeout: 30000 });
    await expect(sendButton).toBeEnabled({ timeout: 30000 });
    await sendButton.click();

    await expect(page.getByText(/Please provide the name of your new model/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(VEHICLE_TYPE_PREDICTOR_MODEL_NAME);
    await sendButton.click();
    await expect(page.getByText(/please describe/i).first()).toBeVisible({
        timeout: 300000
    });

    await chatInput.fill(VEHICLE_TYPE_PREDICTOR_MODEL_DESCRIPTION);
    await sendButton.click();
    await expect(page.getByText(/Thumbnail Image Uploader/i).first()).toBeVisible({
        timeout: 300000
    });

    await model.uploadThumbnail(VEHICLE_TYPE_PREDICTOR_MODEL_THUMBNAIL);
    await model.uploadModelFile(VEHICLE_TYPE_PREDICTOR_MODEL_FILE);
    await model.createModel();

    const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const closeButton = page.getByRole("button", { name: "Close", exact: true }).first();
    await expect(closeButton).toBeVisible({ timeout: 30000 });
    await closeButton.click();
}

function generateRandomEthWalletAddress() {
    const hex = "0123456789abcdef";
    let wallet = "0x";
    for (let i = 0; i < 40; i++) {
        wallet += hex[Math.floor(Math.random() * hex.length)];
    }
    return wallet;
}

async function dismissWelcomeChooser(page: Page) {
    const welcomeHeading = page.getByText("Welcome to RoboCorp!").first();
    const verifyBanner = page.getByText(/Verify your business profile and unlock advanced features/i).first();
    const legacyWelcomeBanner = page.locator("#welcome-cards-banner");

    if (await legacyWelcomeBanner.isVisible({ timeout: 3000 }).catch(() => false)) {
        const legacyCheckbox = legacyWelcomeBanner.getByRole("checkbox").first();
        if (await legacyCheckbox.isVisible({ timeout: 2000 }).catch(() => false)) {
            await legacyCheckbox.click({ force: true }).catch(() => { });
        }
        await Promise.race([
            verifyBanner.waitFor({ state: "visible", timeout: 10000 }).catch(() => null),
            legacyWelcomeBanner.waitFor({ state: "hidden", timeout: 10000 }).catch(() => null)
        ]);
        return;
    }

    if (!(await welcomeHeading.isVisible({ timeout: 5000 }).catch(() => false))) {
        return;
    }

    const welcomeModal = page.locator("main").locator("div").filter({ has: welcomeHeading }).first();

    for (let attempt = 1; attempt <= 3; attempt++) {
        const closeButton = welcomeModal.locator("button").last();
        if (await closeButton.isVisible({ timeout: 1000 }).catch(() => false)) {
            await closeButton.click({ force: true }).catch(() => { });
        }

        const progressed = await Promise.race([
            verifyBanner.waitFor({ state: "visible", timeout: 5000 }).then(() => true).catch(() => false),
            welcomeHeading.waitFor({ state: "hidden", timeout: 5000 }).then(() => true).catch(() => false)
        ]);

        if (progressed) {
            return;
        }
    }

    throw new Error("Welcome chooser did not dismiss to the business verification banner.");
}

async function initiateAgentCreationWithoutDomain(page: Page, chatPage: ChatPage) {
    const attempts = 5;
    for (let attempt = 1; attempt <= attempts; attempt++) {
        await chatPage.sendMessage("I need to create new agent without a domain.");

        const domainQuestion = page.locator("body").getByText(/Would you like to create a new domain first\?/i).first();
        const namePrompt = page.locator("body").getByText(/name of your new agent|agent name/i).first();

        const [domainVisible, nameVisible] = await Promise.all([
            domainQuestion.isVisible({ timeout: 120000 }).catch(() => false),
            namePrompt.isVisible({ timeout: 120000 }).catch(() => false)
        ]);

        if (domainVisible || nameVisible) {
            if (domainVisible) {
                await domainQuestion.waitFor({ state: "visible", timeout: 60000 });
            }
            return;
        }

        if (attempt === attempts) {
            throw new Error("Agent creation prompt did not reach domain decision state.");
        }

        await page.waitForTimeout(1500);
    }
}

async function runAgentCreationWithoutDomainFlow(page: Page, chatPage: ChatPage) {
    await initiateAgentCreationWithoutDomain(page, chatPage);

    const domainQuestion = page.locator("body").getByText(/Would you like to create a new domain first\?/i).first();
    const domainVisible = await domainQuestion.isVisible({ timeout: 60000 }).catch(() => false);
    if (domainVisible) {
        const noDomainBtn = page.getByRole("button", { name: /skip|no|without domain|general knowledge/i }).first();
        if (await noDomainBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
            await noDomainBtn.click();
        } else {
            await chatPage.sendMessage("No, proceed without creating a domain");
        }
    }

    const walletGate = page.locator("body").getByText(/No active wallet found/i).first();
    await expect(walletGate).toHaveCount(0, { timeout: 15000 });

    await expect(page.locator("body")).toContainText(/name of your new agent|agent name/i, { timeout: 180000 });
    await chatPage.sendMessage(`AutoAgentNoDomain_${Date.now()}`);

    await expect(page.locator("body")).toContainText(/describe|description/i, { timeout: 90000 });
    await chatPage.sendMessage("Automated no-domain agent test description.");

    await expect(page.locator("body")).toContainText(/how would you like this agent to work|Agentic Flow|Deterministic Flow/i, {
        timeout: 90000
    });
    const flowTypeButton = page.getByRole("button", { name: /Agentic Flow/i }).first();
    await expect(flowTypeButton).toBeVisible({ timeout: 30000 });
    await flowTypeButton.click();

    await expect(page.locator("body")).toContainText(/provide the instructions of your agent|instructions/i, { timeout: 90000 });
    await chatPage.sendMessage("You are a reliable assistant for automation validation.");

    await expect(page.locator("body")).toContainText(/list of sources|sources related to your agent/i, { timeout: 90000 });
    await chatPage.sendMessage("Google, Wikipedia");

    await expect(page.getByRole("button", { name: /Create DDA/i })).toBeVisible({ timeout: 90000 });
    await expect(page.getByRole("button", { name: /Open Studio/i })).toBeVisible({ timeout: 90000 });
}

async function createAgentWithoutDomain() {
    await chatPage.waitForChatReady();
    await runAgentCreationWithoutDomainFlow(page, chatPage);
    await page.getByRole("button", { name: /Create DDA/i }).click();
    await expect(page.getByText('Agent created successfully!')).toBeVisible({ timeout: 120000 });
}

async function createCdrAgentWithoutDomain() {
    await clearChat();
    await chatPage.refreshChat();
    await chatPage.waitForChatReady();

    let messageCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage('I need to create new agent without domain');
    await chatPage.waitForNewReceivedMessage(messageCount, 300000);

    messageCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(`CDR analyzer for fraud prevention ${Date.now()}`);
    await chatPage.waitForNewReceivedMessage(messageCount, 300000);

    messageCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(CDR_AGENT_DESCRIPTION);
    await chatPage.waitForNewReceivedMessage(messageCount, 300000);

    await page.getByRole('button', { name: /Agentic Flow Where the agent/i }).click();

    messageCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(CDR_ANALYSIS_INSTRUCTIONS);
    await chatPage.waitForNewReceivedMessage(messageCount, 300000);

    messageCount = await chatPage.getReceivedMessageCount();
    await chatPage.sendMessage(CDR_AGENT_SOURCES);
    await chatPage.waitForNewReceivedMessage(messageCount, 300000);

    await page.getByRole('button', { name: /Create DDA lean back and/i }).click();
    await expect(page.getByText(/Agent created successfully/i)).toBeVisible({ timeout: 120000 });
}

async function openCdrAgentFileUploadStep() {
    await createCdrAgentWithoutDomain();

    await page.getByRole('button', { name: /^Test$/i }).click();
    const understandBtn = page.getByRole('button', { name: /I understand/i }).first();
    if (await understandBtn.isVisible({ timeout: 5000 }).catch(() => false)) {
        await understandBtn.click();
    }

    const fileUploadBtn = page.getByRole('button', { name: /File Upload Upload Data file/i }).first();
    await expect(fileUploadBtn).toBeVisible({ timeout: 10000 });
    await fileUploadBtn.click();
}

async function uploadAllCdrPlaceholderFiles() {
    const cdrFilePath = path.resolve(__dirname, '../../asset-creation-files/cdr_sample.csv');
    const uploadAssetButton = page.getByRole('button', { name: /^Thumbnail$/i }).first();
    const nextBtn = page.getByRole('button', { name: /^Next$/i }).first();

    for (let i = 0; i < 3; i++) {
        await expect(uploadAssetButton).toBeVisible({ timeout: 10000 });
        await uploadAssetButton.click();

        const fileInput = page.locator('input[type="file"]').last();
        await expect(fileInput).toBeAttached({ timeout: 10000 });
        await fileInput.setInputFiles(cdrFilePath);

        if (i < 2) {
            await expect(nextBtn).toBeVisible({ timeout: 10000 });
            await expect(nextBtn).toBeEnabled({ timeout: 10000 });
            await nextBtn.click();
        }
    }
}

type PricingOption = {
    buttonName: string;
    amountText: string;
    planText: RegExp;
};

const ANNUAL_PLAN: PricingOption = {
    buttonName: 'Annual Use 10.00 DAAC',
    amountText: 'Amount Paid : 10.00000000 DAAC',
    planText: /Annual Use/i
};

async function openMarketplaceAssetForPurchase() {
    const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
    const sendButton = page.locator('#chat-input').getByRole('button').first();

    await expect(chatInput).toBeVisible({ timeout: 30000 });
    await chatInput.click();
    await chatInput.fill(MARKETPLACE_SEARCH_PROMPT);
    await sendButton.click();

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 120000 });
    await maximizeWidgetButton.click();

    await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
    const publishedAgentButton = page.getByRole('button', { name: PUBLISHED_AGENT_TITLE_REGEX }).first();
    await expect(publishedAgentButton).toBeVisible({ timeout: 120000 });
    await page.locator('#btn_expand_domain_driven_agent_0').click();
    await expect(page.getByRole('heading', { name: /DOMAIN DRIVEN AGENT: CDR/i })).toBeVisible({ timeout: 120000 });
}

async function purchaseMarketplaceAsset(pricing: PricingOption) {
    await page.getByRole('button', { name: 'Purchase' }).click();
    await page.getByRole('button', { name: pricing.buttonName }).click();
    await page.getByRole('button', { name: 'Purchase' }).click();

    await expect(page.getByText('Purchase from pricing plan')).toBeVisible({ timeout: 120000 });
    await expect(page.getByText('Successfully Purchased!')).toBeVisible({ timeout: 120000 });

    const closeWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
    if (await closeWidgetButton.isVisible({ timeout: 5000 }).catch(() => false)) {
        await closeWidgetButton.click({ force: true }).catch(() => {});
    }

    const refreshChatButton = page.locator('#btn-refresh-chat').first();
    if (await refreshChatButton.isVisible({ timeout: 5000 }).catch(() => false)) {
        await refreshChatButton.click({ force: true }).catch(() => {});
    }
}

async function openInventoryWidgetForPurchasedAsset() {
    const successBannerCloseButton = page.locator('main > div').first().getByRole('button').first();
    if (await successBannerCloseButton.isVisible({ timeout: 2000 }).catch(() => false)) {
        await successBannerCloseButton.click().catch(() => {});
    }

    const amountPaidText = page.getByText(ANNUAL_PLAN.amountText).first();
    const inventoryHeading = page.getByRole('heading', { name: /Inventory/i }).first();
    const purchasedEntry = page.getByRole('listitem').filter({ hasText: /purchased/i }).first();

    if (await inventoryHeading.isVisible({ timeout: 2000 }).catch(() => false)) {
        if (await purchasedEntry.isVisible({ timeout: 2000 }).catch(() => false)) {
            await purchasedEntry.click().catch(() => {});
        }
    } else {
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 3000 }).catch(() => false)) {
            await inventoryButton.click();

            const inventoryWidget = page.getByRole('region').filter({ has: page.getByText('Inventory') }).last();
            await expect(inventoryWidget).toBeVisible({ timeout: 30000 });
            await inventoryWidget.getByRole('button', { name: 'Domain Driven Agent' }).click();
            await inventoryWidget.getByRole('textbox', { name: 'Search' }).fill('CDR');
            await inventoryWidget.getByRole('button', { name: 'See details...', exact: true }).first().click();
        } else {
            const marketplaceWidget = page.getByRole('region').filter({ has: page.getByText('Marketplace').first() }).last();
            if (await marketplaceWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                const domainDrivenAgentTab = marketplaceWidget.getByRole('button', { name: 'Domain Driven Agent' }).first();
                if (await domainDrivenAgentTab.isVisible({ timeout: 2000 }).catch(() => false)) {
                    await domainDrivenAgentTab.click();
                }

                const assetCard = marketplaceWidget
                    .getByRole('button')
                    .filter({ hasText: CDR_PURCHASED_ASSET_TITLE })
                    .first();
                await expect(assetCard).toBeVisible({ timeout: 30000 });
                await assetCard.locator('#btn_see_details').click();
            }
        }
    }

    await expect(amountPaidText).toBeVisible({ timeout: 120000 });
}

async function openPurchasedAssetDetailsFromInventory() {
    await page.locator('#btn-refresh-chat').click().catch(() => {});

    const inventoryHeading = page.getByRole('heading', { name: /Inventory/i }).first();
    if (!(await inventoryHeading.isVisible({ timeout: 2000 }).catch(() => false))) {
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        await expect(inventoryButton).toBeVisible({ timeout: 30000 });
        await inventoryButton.click();
    }

    const inventoryWidget = page.getByRole('region').filter({ has: page.getByText('Inventory') }).last();
    await expect(inventoryWidget).toBeVisible({ timeout: 30000 });
    await inventoryWidget.getByRole('button', { name: 'Domain Driven Agent' }).click();

    const assetCard = inventoryWidget.getByRole('button').filter({ hasText: CDR_PURCHASED_ASSET_TITLE }).first();
    await expect(assetCard).toBeVisible({ timeout: 30000 });
    await assetCard.locator('#btn_see_details').click();
}

async function assertWalletTransaction(pricing: PricingOption) {
    const walletButton = page
        .getByRole('button')
        .filter({ has: page.getByText(/\d+(?:\.\d+)?\s*DAAC/i).first() })
        .first();
    await expect(walletButton).toBeVisible({ timeout: 30000 });
    await walletButton.click();

    const walletMenu = page.getByRole('menu').first();
    await expect(walletMenu).toContainText(CDR_PURCHASED_ASSET_TITLE, { timeout: 120000 });
    await expect(walletMenu).toContainText(/PURCHASE/i, { timeout: 120000 });
    await expect(walletMenu).toContainText(pricing.planText, { timeout: 120000 });
    await expect(walletMenu).toContainText(/\d{1,2}:\d{2}/, { timeout: 120000 });
}

async function openPlaceholderConnectionFlow() {
    await openInventoryWidgetForPurchasedAsset();
    const connectAllPlaceholders = page.getByText('Connect all placeholders').first();
    await expect(connectAllPlaceholders).toBeVisible({ timeout: 30000 });
    await connectAllPlaceholders.click();
}

async function openPlaceholder(name: string) {
    const placeholderButton = page.getByRole('button', { name }).first();
    await expect(placeholderButton).toBeVisible({ timeout: 30000 });
    await placeholderButton.click();
}

async function createMcpCredential() {
    await page.getByRole('button', { name: 'MCP Credentials Enter' }).click();
    await page.getByLabel('MCP Type').selectOption(MCP_TYPE_ID);
    await page.getByRole('textbox', { name: 'Enter Name' }).fill('CDR data');
    await page.getByRole('textbox', { name: 'Enter Description' }).fill('cdr data');
    await page.getByRole('textbox', { name: 'Enter User' }).fill('root');
    await page.getByRole('textbox', { name: 'Enter Password' }).fill('1234');
    await page.getByRole('textbox', { name: 'Enter Host' }).fill('100.1.2.3');
    await page.getByPlaceholder('Enter Port').fill('5506');
    await page.getByRole('textbox', { name: 'Enter Database' }).fill('cdr_data');
    await page.getByRole('button', { name: 'Connect' }).click();
    await expect(page.getByText(/MCP credential created/i)).toBeVisible({ timeout: 120000 });
    await expect(page.getByRole('heading', { name: /MCP connected successfully/i })).toBeVisible({ timeout: 120000 });
}

async function connectExistingMcp(placeholderName: string) {
    await openPlaceholder(placeholderName);
    await page.getByRole('button', { name: 'Existing MCPs Connect' }).click();
    await page.getByRole('checkbox', { name: new RegExp(MCP_CREDENTIAL_NAME, 'i') }).check();
    await page.getByRole('button', { name: 'Test Connection' }).click();
    await expect(page.getByRole('heading', { name: /MCP connected successfully/i })).toBeVisible({ timeout: 120000 });
}

async function publishWidgetFromStudio(detailsIndex = 0, unpublish = false) {
    const inventoryHeader = page.getByText(/Manage your assets/i).first();
    if (await inventoryHeader.isVisible({ timeout: 2000 }).catch(() => false)) {
        const openInventoryTitle = page.getByText(/^Inventory$/i).first();
        if (await openInventoryTitle.isVisible({ timeout: 1000 }).catch(() => false)) {
            const closeInventoryWidget = page
                .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
                .first();
            if (await closeInventoryWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                await closeInventoryWidget.click({ force: true }).catch(() => {});
                await page.waitForTimeout(2000);
            }
        }
    }

    await clearChat();
    await page.getByRole('button', { name: 'Open inventory' }).click();
    const inventoryHeaderAfterOpen = page.getByText(/Manage your assets/i).first();
    if (!(await inventoryHeaderAfterOpen.isVisible({ timeout: 20000 }).catch(() => false))) {
        const maximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeButton.click();
            await expect(inventoryHeaderAfterOpen).toBeVisible({ timeout: 15000 });
        }
    }

    await page.getByRole('button', { name: 'Agentic Widget' }).click();
    await page.getByRole('button', { name: 'See details...', exact: true }).nth(detailsIndex).click();

    const inventoryActionButton = page.getByRole('button').nth(1);
    await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
    await inventoryActionButton.click();
    await page.waitForTimeout(5000);

    const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
    if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeInventoryWidget.click({ force: true }).catch(() => {});
    }

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const previewButton = page.locator('.lucide.lucide-eye').first();
    if (await previewButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await previewButton.click();
    }

    const testButton = page.getByRole('button', { name: 'Test', exact: true }).first();
    await expect(testButton).toBeVisible({ timeout: 60000 });
    await testButton.click();

    const understandButton = page.getByRole('button', { name: 'I understand' }).first();
    if (await understandButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await understandButton.click();
    }

    const testInput = page.getByRole('textbox', { name: 'Enter your input query here...' }).first();
    await expect(testInput).toBeVisible({ timeout: 60000 });
    await testInput.fill('Test widget');
    await testButton.click();

    const closeExecutionButton = page.getByRole('button', { name: /^Close$/i }).first();
    if (await closeExecutionButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeExecutionButton.click();
    }

    const publishButton = page.getByRole('button', { name: 'Publish' }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const publishDialog = page.getByRole('dialog').first();
    await expect(publishDialog).toBeVisible({ timeout: 30000 });

    const prerequisitesInput = publishDialog.getByRole('textbox', { name: 'Prerequisites' }).first();
    await expect(prerequisitesInput).toBeVisible({ timeout: 30000 });
    await prerequisitesInput.fill('No prerequisites');

    await page.locator('#int_agent_builder_single_use input[type="text"]').first().fill('1');
    await page.locator('#int_agent_builder_five_uses input[type="text"]').first().fill('5');
    await page.locator('#int_agent_builder_annual input[type="text"]').first().fill('49');
    await page
        .locator('[id="int_agent_builder_unlimited_(including_for_reselling)"] input[type="text"]')
        .first()
        .fill('99');

    const confirmButton = page.getByRole('button', { name: 'Confirm' }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();

    await expect(page.getByText('Widget published successfully!').first()).toBeVisible({ timeout: 120000 });

    if (unpublish) {
        await page.waitForTimeout(6000);
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryButton.click();
            await page.waitForTimeout(1000);
        }
        const unpublishButton = page.getByRole('button', { name: 'Unpublish' }).first();
        await expect(unpublishButton).toBeVisible({ timeout: 60000 });
        await unpublishButton.click();
        await expect(page.getByRole('heading', { name: /unpublished/i }).first()).toBeVisible({ timeout: 120000 });
    }
}

async function publishDatasetFromStudio(detailsIndex = 0, unpublish = false) {
    const inventoryHeader = page.getByText(/Manage your assets/i).first();
    if (await inventoryHeader.isVisible({ timeout: 2000 }).catch(() => false)) {
        const openInventoryTitle = page.getByText(/^Inventory$/i).first();
        if (await openInventoryTitle.isVisible({ timeout: 1000 }).catch(() => false)) {
            const closeInventoryWidget = page
                .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
                .first();
            if (await closeInventoryWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                await closeInventoryWidget.click({ force: true }).catch(() => {});
                await page.waitForTimeout(2000);
            }
        }
    }

    await clearChat();
    await page.getByRole('button', { name: 'Open inventory' }).click();
    const inventoryHeaderAfterOpen = page.getByText(/Manage your assets/i).first();
    if (!(await inventoryHeaderAfterOpen.isVisible({ timeout: 20000 }).catch(() => false))) {
        const maximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeButton.click();
            await expect(inventoryHeaderAfterOpen).toBeVisible({ timeout: 15000 });
        }
    }

    await page.getByRole('button', { name: 'Curated Data' }).click();
    await page.getByRole('button', { name: 'See details...', exact: true }).nth(detailsIndex).click();

    const inventoryActionButton = page.getByRole('button').first();
    await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
    await inventoryActionButton.click();
    await page.waitForTimeout(5000);

    const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
    if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeInventoryWidget.click({ force: true }).catch(() => {});
    }

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const publishEntry = page.locator('div:nth-child(5) > .flex > .lucide').first();
    if (await publishEntry.isVisible({ timeout: 10000 }).catch(() => false)) {
        await publishEntry.click();
    }

    const publishButton = page.getByRole('button', { name: 'Publish' }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    await page.locator('#sabw_form-field-single-use').getByRole('textbox').first().fill('1');
    await page.locator('#sabw_form-field-five-uses').getByRole('textbox').first().fill('5');
    await page.locator('#sabw_form-field-annual').getByRole('textbox').first().fill('49');
    await page
        .locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]')
        .first()
        .fill('99');

    const confirmButton = page.getByRole('button', { name: 'Confirm' }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();

    await expect(page.getByText('Asset published successfully!').first()).toBeVisible({ timeout: 120000 });

    if (unpublish) {
        await page.waitForTimeout(6000);
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryButton.click();
            await page.waitForTimeout(1000);
        }
        const unpublishButton = page.getByRole('button', { name: 'Unpublish' }).first();
        await expect(unpublishButton).toBeVisible({ timeout: 60000 });
        await unpublishButton.click();
        await expect(page.getByRole('heading', { name: /unpublished/i }).first()).toBeVisible({ timeout: 120000 });
    }
}

async function publishMediaFromStudio(detailsIndex = 0, unpublish = false) {
    const inventoryHeader = page.getByText(/Manage your assets/i).first();
    if (await inventoryHeader.isVisible({ timeout: 2000 }).catch(() => false)) {
        const openInventoryTitle = page.getByText(/^Inventory$/i).first();
        if (await openInventoryTitle.isVisible({ timeout: 1000 }).catch(() => false)) {
            const closeInventoryWidget = page
                .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
                .first();
            if (await closeInventoryWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                await closeInventoryWidget.click({ force: true }).catch(() => {});
                await page.waitForTimeout(2000);
            }
        }
    }

    await clearChat();
    await page.getByRole('button', { name: 'Open inventory' }).click();
    const inventoryHeaderAfterOpen = page.getByText(/Manage your assets/i).first();
    if (!(await inventoryHeaderAfterOpen.isVisible({ timeout: 20000 }).catch(() => false))) {
        const maximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeButton.click();
            await expect(inventoryHeaderAfterOpen).toBeVisible({ timeout: 15000 });
        }
    }

    await page.getByRole('button', { name: 'Media', exact: true }).click();
    await page.getByRole('button', { name: 'See details...', exact: true }).nth(detailsIndex).click();

    const inventoryActionButton = page.getByRole('button').first();
    await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
    await inventoryActionButton.click();
    await page.waitForTimeout(5000);

    const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
    if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeInventoryWidget.click({ force: true }).catch(() => {});
    }

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const previewButton = page.locator('.lucide.lucide-eye').first();
    if (await previewButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await previewButton.click();
    }

    const publishButton = page.getByRole('button', { name: 'Publish' }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    await page.locator('#media_creation_price_per_single_percent').getByRole('textbox').first().fill('5');
    const confirmButton = page.getByRole('button', { name: 'Confirm' }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();

    if (await page.getByText('Media published successfully!').first().isVisible({ timeout: 5000 }).catch(() => false)) {
        await expect(page.getByText('Media published successfully!').first()).toBeVisible({ timeout: 120000 });
    }

    if (unpublish) {
        await page.waitForTimeout(6000);
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryButton.click();
            await page.waitForTimeout(1000);
        }
        const unpublishButton = page.getByRole('button', { name: 'Unpublish' }).first();
        await expect(unpublishButton).toBeVisible({ timeout: 60000 });
        await unpublishButton.click();
        await expect(page.getByRole('heading', { name: /unpublished/i }).first()).toBeVisible({ timeout: 120000 });
    }
}

async function publishModelFromStudio(detailsIndex = 0, unpublish = false) {
    const inventoryHeader = page.getByText(/Manage your assets/i).first();
    if (await inventoryHeader.isVisible({ timeout: 2000 }).catch(() => false)) {
        const openInventoryTitle = page.getByText(/^Inventory$/i).first();
        if (await openInventoryTitle.isVisible({ timeout: 1000 }).catch(() => false)) {
            const closeInventoryWidget = page
                .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
                .first();
            if (await closeInventoryWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                await closeInventoryWidget.click({ force: true }).catch(() => {});
                await page.waitForTimeout(2000);
            }
        }
    }

    await clearChat();
    await page.getByRole('button', { name: 'Open inventory' }).click();
    const inventoryHeaderAfterOpen = page.getByText(/Manage your assets/i).first();
    if (!(await inventoryHeaderAfterOpen.isVisible({ timeout: 20000 }).catch(() => false))) {
        const maximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeButton.click();
            await expect(inventoryHeaderAfterOpen).toBeVisible({ timeout: 15000 });
        }
    }

    await page.getByRole('button', { name: 'Models' }).click();
    await page.getByRole('button', { name: 'See details...', exact: true }).nth(detailsIndex).click();

    const inventoryActionButton = page.getByRole('button').nth(1);
    await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
    await inventoryActionButton.click();
    await page.waitForTimeout(5000);

    const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
    if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeInventoryWidget.click({ force: true }).catch(() => {});
    }

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const previewButton = page.locator('.lucide.lucide-eye').first();
    if (await previewButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await previewButton.click();
    }

    const publishButton = page.getByRole('button', { name: 'Publish' }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const priceInput = page.getByRole('dialog').getByRole('textbox').first();
    await expect(priceInput).toBeVisible({ timeout: 30000 });
    await priceInput.fill('9');

    const confirmButton = page.getByRole('button', { name: 'Confirm' }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();

    await expect(page.getByText('Model published successfully!').first()).toBeVisible({ timeout: 120000 });

    if (unpublish) {
        await page.waitForTimeout(6000);
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryButton.click();
            await page.waitForTimeout(1000);
        }
        const unpublishButton = page.getByRole('button', { name: 'Unpublish' }).first();
        await expect(unpublishButton).toBeVisible({ timeout: 60000 });
        await unpublishButton.click();
        await expect(page.getByRole('heading', { name: /unpublished/i }).first()).toBeVisible({ timeout: 120000 });
    }
}

async function publishAgentFromStudio(detailsIndex = 0, unpublish = false) {
    const inventoryHeader = page.getByText(/Manage your assets/i).first();
    if (await inventoryHeader.isVisible({ timeout: 2000 }).catch(() => false)) {
        const openInventoryTitle = page.getByText(/^Inventory$/i).first();
        if (await openInventoryTitle.isVisible({ timeout: 1000 }).catch(() => false)) {
            const closeInventoryWidget = page
                .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
                .first();
            if (await closeInventoryWidget.isVisible({ timeout: 3000 }).catch(() => false)) {
                await closeInventoryWidget.click({ force: true }).catch(() => {});
                await page.waitForTimeout(2000);
            }
        }
    }
    await clearChat();
    await page.getByRole('button', { name: 'Open inventory' }).click();
    const inventoryHeaderAfterOpen = page.getByText(/Manage your assets/i).first();
    if (!(await inventoryHeaderAfterOpen.isVisible({ timeout: 20000 }).catch(() => false))) {
        const maximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeButton.click();
            await expect(inventoryHeaderAfterOpen).toBeVisible({ timeout: 15000 });
        }
    }
    await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
    await page.getByRole('button', { name: 'See details...', exact: true }).nth(detailsIndex).click();

    const inventoryActionButton = page.getByRole('button').nth(1);
    await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
    await inventoryActionButton.click();
    await page.waitForTimeout(5000);

    const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
    if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
        await closeInventoryWidget.click({ force: true }).catch(() => {});
    }

    const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();

    const previewButton = page.locator('.lucide.lucide-eye').first();
    if (await previewButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await previewButton.click();
    }

    const testButton = page.getByRole('button', { name: 'Test', exact: true }).first();
    await expect(testButton).toBeVisible({ timeout: 60000 });
    await testButton.click();

    const understandButton = page.getByRole('button', { name: 'I understand' }).first();
    if (await understandButton.isVisible({ timeout: 10000 }).catch(() => false)) {
        await understandButton.click();
    }

    const testInput = page.getByRole('textbox', { name: 'Enter your input query here...' }).first();
    await expect(testInput).toBeVisible({ timeout: 60000 });
    await testInput.fill('Test agent query');
    await testButton.click();

    const executionDialog = page.getByRole('dialog').first();
    const executionCloseButton = executionDialog.getByRole('button', { name: /^Close$/i }).first();
    await expect(executionCloseButton).toBeVisible({ timeout: 60000 });
    await executionCloseButton.click();
    await expect(executionDialog).toBeHidden({ timeout: 30000 });

    const publishButton = page.getByRole('button', { name: 'Publish' }).first();
    await expect(publishButton).toBeVisible({ timeout: 60000 });
    await publishButton.click();

    const publishDialog = page.getByRole('dialog').first();
    await expect(publishDialog).toBeVisible({ timeout: 30000 });

    const prerequisitesInput = publishDialog.getByRole('textbox', { name: 'Prerequisites' }).first();
    await expect(prerequisitesInput).toBeVisible({ timeout: 30000 });
    await prerequisitesInput.fill('Test prerequisites');

    await page.locator('#int_agent_builder_single_use input[type="text"]').first().fill('2');
    await page.locator('#int_agent_builder_five_uses input[type="text"]').first().fill('10');
    await page.locator('#int_agent_builder_annual input[type="text"]').first().fill('20');
    await page
        .locator('[id="int_agent_builder_unlimited_(including_for_reselling)"] input[type="text"]')
        .first()
        .fill('50');

    const confirmButton = page.getByRole('button', { name: 'Confirm' }).first();
    await expect(confirmButton).toBeVisible({ timeout: 30000 });
    await confirmButton.click();

    await expect(page.getByText('Agent published successfully!').first()).toBeVisible({ timeout: 120000 });

    if (unpublish) {
        await page.waitForTimeout(6000);
        const inventoryButton = page.getByRole('button', { name: 'Open inventory' }).first();
        if (await inventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryButton.click();
            await page.waitForTimeout(1000);
        }
        const unpublishButton = page.getByRole('button', { name: 'Unpublish' }).first();
        await expect(unpublishButton).toBeVisible({ timeout: 60000 });
        await unpublishButton.click();
        await expect(page.getByRole('heading', { name: 'Agent unpublished' }).first()).toBeVisible({ timeout: 120000 });
    }
}

async function depositWallet(amount: string, description: string) {
    const cookies = await page.context().cookies();
    const token = cookies.find((cookie) => cookie.name === 'access_token')?.value;
    if (!token) {
        throw new Error('access_token not found in cookies.');
    }

    const depositUrl = new URL(
        `https://promptify-exchange-be-dev.promptyf.cloud/api/v1/wallet/${onboardingWalletAddress}/deposit`
    );
    depositUrl.searchParams.set('amount', amount);
    depositUrl.searchParams.set('description', description);
    depositUrl.searchParams.set('perform_blockchain_transfer', 'false');

    const response = await page.request.post(depositUrl.toString(), {
        headers: {
            accept: 'application/json',
            Authorization: `Bearer ${token}`
        }
    });
    expect(response.ok()).toBeTruthy();
}

async function expectWalletBalance(amount: string) {
    await chatPage.refreshChat();
    await page.getByRole("button", { name: "Toggle Wallet" }).click();
    const daacHeading = page.getByRole("heading", { name: "DAAC" });
    await daacHeading.click();
    const amountRegex = new RegExp(`${amount.replace('.', '\\.')}\\s*DAAC`, 'i');
    await expect(daacHeading).toHaveText(amountRegex, { timeout: 20000 });
}

async function getWalletBalanceDaac(): Promise<number> {
    const daacHeading = page.getByRole("heading", { name: "DAAC" }).first();
    const walletToggle = page.getByRole("button", { name: "Toggle Wallet" }).first();

    if (!(await daacHeading.isVisible({ timeout: 1500 }).catch(() => false))) {
        await expect(walletToggle).toBeVisible({ timeout: 10000 });
        await walletToggle.click();
    }

    await expect(daacHeading).toBeVisible({ timeout: 10000 });
    await daacHeading.click();

    const balanceText = (await daacHeading.innerText()).replace(/,/g, "");
    const balanceMatch = balanceText.match(/(\d+(?:\.\d+)?)/);
    if (!balanceMatch) {
        throw new Error(`Unable to parse DAAC balance from text: ${balanceText}`);
    }

    return Number.parseFloat(balanceMatch[1]);
}

async function logoutCurrentUser() {
    const userDropdownToggle = page
        .locator('#btn-user-dropdown')
        .getByRole('button', { name: /Toggle User Dropdown/i })
        .first();
    if (await userDropdownToggle.isVisible({ timeout: 10000 }).catch(() => false)) {
        await userDropdownToggle.click();
    } else {
        await page.getByRole('button', { name: /Toggle User Dropdown/i }).first().click();
    }

    const logoutButton = page.getByRole('button', { name: 'Logout this device' }).first();
    await expect(logoutButton).toBeVisible({ timeout: 15000 });
    await logoutButton.click();
    await expect(page.getByRole('button', { name: /Log In\/ Sign Up/i }).first()).toBeVisible({ timeout: 30000 });
}

async function loginWithCredentials(email: string, password: string, skipVerification = false) {
    const loginButton = page.getByRole('button', { name: /Log In\/ Sign Up/i }).first();
    await expect(loginButton).toBeVisible({ timeout: 30000 });
    await loginButton.click();

    const emailInput = page.getByRole('textbox', { name: 'Email' }).first();
    const passwordInput = page.getByRole('textbox', { name: 'Enter your password' }).first();
    await expect(emailInput).toBeVisible({ timeout: 30000 });
    await emailInput.fill(email);
    await expect(passwordInput).toBeVisible({ timeout: 30000 });
    await passwordInput.fill(password);
    await page.getByRole('button', { name: 'Confirm' }).first().click();

    await expect(page.getByRole('textbox', { name: 'Ask anything...' }).first()).toBeVisible({ timeout: 60000 });
    await chatPage.dismissChatOverlays();

    const legacyWelcomeBanner = page.locator('#welcome-cards-banner');
    if (await legacyWelcomeBanner.isVisible({ timeout: 5000 }).catch(() => false)) {
        const closeBannerButton = legacyWelcomeBanner.getByRole('button').filter({ hasText: /^$/ }).first();
        if (await closeBannerButton.isVisible({ timeout: 2000 }).catch(() => false)) {
            await closeBannerButton.click({ force: true }).catch(() => {});
        }
    }

    if (skipVerification) {
        await dismissWelcomeChooser(page).catch(() => {});
        const skipVerifyButton = page.getByRole('button', { name: /Skip for now/i }).first();
        if (await skipVerifyButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await skipVerifyButton.click();
        }
    }
}

async function initiateWidgetCreation(page: Page, chatPage: ChatPage) {
    for (let attempt = 1; attempt <= 5; attempt += 1) {
        await page.getByRole('textbox', { name: 'Ask anything...' }).click();
        await chatPage.sendMessage('I need to create widget without domain');

        const namePrompt = page.locator('body').getByText(
            /provide the name of your new widget|name of your new widget/i
        ).first();
        const nextState = await namePrompt.waitFor({ state: 'visible', timeout: 180000 }).then(() => 'name').catch(() => null);

        if (nextState === 'name') {
            return;
        }

        if (attempt === 5) {
            throw new Error('Widget creation prompt did not reach the naming state.');
        }

        await page.waitForTimeout(1200);
    }
}

async function completeWidgetCreationWithoutDomain(page: Page, chatPage: ChatPage) {
    await chatPage.waitForChatReady();
    await page.getByRole('textbox', { name: 'Ask anything...' }).click();

    await initiateWidgetCreation(page, chatPage);

    const namePrompt = page.locator('body').getByText(
        /provide the name of your new widget|name of your new widget/i
    ).first();
    await expect(namePrompt).toBeVisible({ timeout: 60000 });

    await page.getByRole('textbox', { name: 'Ask anything...' }).click();
    await chatPage.sendMessage(`AutoWidgetNoDomain_${Date.now()}`);

    const descriptionPrompt = page.locator('body').getByText(
        /describe you widget|describe your widget|potential users can easily understand its purpose/i
    ).first();
    await expect(descriptionPrompt).toBeVisible({ timeout: 60000 });

    await page.getByRole('textbox', { name: 'Ask anything...' }).click();
    await chatPage.sendMessage('Automated no-domain widget test description.');

    const instructionsPrompt = page.locator('body').getByText(
        /provide the instructions of your widget|instructions of your widget/i
    ).first();
    await expect(instructionsPrompt).toBeVisible({ timeout: 60000 });

    await page.getByRole('textbox', { name: 'Ask anything...' }).click();
    await chatPage.sendMessage('You are a reliable widget for automation validation.');

    const sourcePrompt = page.locator('body').getByText(
        /specify the type of sources|sources that your widget should interact with/i
    ).first();
    await expect(sourcePrompt).toBeVisible({ timeout: 60000 });

    await page.getByRole('textbox', { name: 'Ask anything...' }).click();
    await chatPage.sendMessage('Test widget sources');

    const firstWidgetCheckbox = page.locator('#widget_selection_item_1').getByRole('checkbox').first();
    await expect(firstWidgetCheckbox).toBeVisible({ timeout: 60000 });
    await firstWidgetCheckbox.click({ force: true });

    const confirmButton = page.getByRole('button', { name: /^Confirm$/i }).first();
    await expect(confirmButton).toBeVisible({ timeout: 10000 });
    await confirmButton.click();

    const createWidgetButton = page.getByRole('button', { name: /Create Widget/i }).first();
    await expect(createWidgetButton).toBeVisible({ timeout: 60000 });
    await createWidgetButton.click();

    const gridLayout = page.locator('.react-grid-layout').first();
    await expect(gridLayout).toBeVisible({ timeout: 120000 });
    await gridLayout.click({ force: true }).catch(() => {});

    const resizeHandle = page.locator('.react-resizable-handle').first();
    if (await resizeHandle.isVisible({ timeout: 10000 }).catch(() => false)) {
        await resizeHandle.click({ force: true }).catch(() => {});
    }

    await gridLayout.click({ force: true }).catch(() => {});

    const maximizeWidgetButton = page.getByRole('button', { name: /Maximize widget/i }).first();
    await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
    await maximizeWidgetButton.click();
}

test.describe.serial("Business Users / B7 User", () => {
    test.describe.configure({ timeout: 480000 });

    test.beforeAll(async ({ browser }, testInfo) => {
        testInfo.setTimeout(480000);
        context = await browser.newContext();
        page = await context.newPage();
        const registrationPage = new RegistrationPage(page);
        chatPage = new ChatPage(page);

        onboardingEmail = `automation.b7+${Date.now()}@datafab.ai`;
        onboardingPassword = process.env.USER_PASSWORD?.trim() || "User@123";
        onboardingFullName = "Automation B Seven User";
        onboardingSubdomain =
            process.env.USER_USERNAME?.trim() ||
            onboardingEmail
                .split("@")[0]
                .replace(/[^a-zA-Z0-9-]/g, "-")
                .slice(0, 32);
        onboardingWalletAddress = generateRandomEthWalletAddress();

        await registrationPage.gotoSignIn();
        await registrationPage.openSignUpFromSignIn();
        await registrationPage.submitSignUpCredentials(onboardingEmail, onboardingPassword);
        await registrationPage.submitFullName(onboardingFullName);

        await registrationPage.waitForVerificationScreen();
        const code = await waitForActivationCode(onboardingEmail, { timeoutMs: 90000, intervalMs: 3000 });
        await registrationPage.enterVerificationCode(code);
        await registrationPage.clickVerify();

        await expect(page).toHaveURL(/\/sign-in\/account/i, { timeout: 30000 });
        await registrationPage.completeBusinessUserConsumerFlow();
        await registrationPage.waitForTipsOrOnboarding();

        for (let i = 0; i < 4; i++) {
            const tipsVisible = await page
                .locator("body")
                .getByText(/Here is tips how to use our platform/i)
                .first()
                .isVisible({ timeout: 2000 })
                .catch(() => false);
            if (!tipsVisible) {
                break;
            }

            const continueBtn = page.getByRole("button", { name: /^Continue$/i }).first();
            if (await continueBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
                await continueBtn.click();
                await page.waitForTimeout(400);
                continue;
            }

            const skipBtn = page.getByRole("button", { name: /Skip for now/i }).first();
            if (await skipBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
                await skipBtn.click();
                await page.waitForTimeout(400);
            }
        }

        // The welcome popup appears asynchronously after the last tips action.
        await page.waitForTimeout(2500);

        await chatPage.dismissChatOverlays();

        await dismissWelcomeChooser(page);
        await page.waitForTimeout(2500);

        const legacyBusinessBanner = page.locator("#business-verification-banner");
        await Promise.race([
            legacyBusinessBanner.waitFor({ state: "visible", timeout: 10000 }).catch(() => null),
            page.getByText(/Verify your business profile and unlock advanced features/i).first().waitFor({ state: "visible", timeout: 10000 }).catch(() => null)
        ]);

        const verifyButton = page.getByRole("button", { name: "Verify" }).first();
        if (await verifyButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await verifyButton.click();
        }

        await Promise.race([
            page.waitForURL(/robocorp-galaxy-fe-gen2\.promptyf\.cloud/i, { timeout: 30000 }).catch(() => null),
            page.getByText("Can you please provide the address of your organization?").waitFor({ state: "visible", timeout: 30000 }).catch(() => null)
        ]);

        await expect(page.getByText("Can you please provide the address of your organization?")).toBeVisible({ timeout: 30000 });
    })

    test("should be able to answer first question", async ({ }) => {
        await expect(page.getByText("Can you please provide the address of your organization?")).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole("textbox")).toBeVisible()
        await page.getByRole("textbox").fill("123 Main Street, New York, USA");
        await page.getByRole("textbox").press("Enter");
        await expect(page.getByText("What is the registration number of your organization?")).toBeVisible({ timeout: 20000 });
    })

    test("should be able to answer second question", async ({ }) => {
        await page.getByRole("textbox").fill("REG-456789");
        await page.getByRole("textbox").press("Enter");
        await expect(page.getByText("I need to know the type of organization you represent.")).toBeVisible({ timeout: 20000 });
        await expect(page.getByText("Please choose one from the following options:")).toBeVisible();

        await expect(page.getByText("Law Firm")).toBeVisible();
        await expect(page.getByText("Litigation Funder")).toBeVisible();
        await expect(page.getByText("Corporate")).toBeVisible();
        await expect(page.getByText("Investigation Agency")).toBeVisible();
        await expect(page.getByText("Insurance Carrier")).toBeVisible();
        await page.getByText("Law Firm").click();
    })

    test("should be able to answer third question", async ({ }) => {
        await expect(page.getByRole("radio", { name: "1 to 10", exact: true })).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole("radio", { name: "11 to 50", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "51 to 100", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "100+", exact: true })).toBeVisible();
        await page.getByRole("radio", { name: "1 to 10", exact: true }).click();
        await page.getByRole("button", { name: "Confirm" }).click();
    })

    test("should be able to choose a subscription plan", async ({ }) => {
        await expect(page.locator("#workflow_id_2")).toBeVisible({ timeout: 20000 });
        await expect(page.getByText("Based on the information you provided, I recommend the following package.")).toBeVisible();
        await expect(page.getByText("Pilot Plan", { exact: true })).toBeVisible();
        await expect(page.locator("p", { hasText: "Plan A" })).toBeVisible();
        await expect(page.locator("p", { hasText: "Plan B" })).toBeVisible();
        await expect(page.locator("p", { hasText: "Plan C" }).first()).toBeVisible();
        await page.locator("p", { hasText: "Plan A" }).click();
        await page.mouse.move(0, 0);
    })

    test("should be able to confirm additional features", async ({ }) => {
        await expect(page.locator("#workflow_id_3")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("h2", { hasText: "Additional Features" })).toBeVisible();
        await expect(page.getByText("To extend functionality", { exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Skip", exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to select cloud preferences", async ({ }) => {
        await expect(page.locator("#workflow_id_4")).toBeVisible({ timeout: 20000 });
        await expect(page.getByText("Let’s start with Cloud Preferences.")).toBeVisible();
        await expect(page.getByRole("radio", { name: "DataFab Managed Deployment" })).toBeVisible();
        await page.getByRole("radio", { name: "DataFab Managed Deployment" }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to configure network access", async ({ }) => {
        await expect(page.getByText("Public Network")).toBeVisible({ timeout: 20000 });
        await expect(page.getByPlaceholder("Enter Subdomain")).toBeVisible();
        await page.getByPlaceholder("Enter Subdomain").fill(`${onboardingSubdomain}.datafab.ai`);
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to confirm encryption preference", async ({ }) => {
        await expect(page.getByRole('paragraph').filter({ hasText: 'Cloud-managed keys' })).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        // await expect(page.getByRole("button", { name: "Skip", exact: true })).toBeVisible();
        await expect(page.getByText("GCM", { exact: true })).toBeVisible();
        await expect(page.getByText("CBC", { exact: true })).toBeVisible();
        await expect(page.getByText("CTR", { exact: true })).toBeVisible();
        await expect(page.getByText("XTS", { exact: true })).toBeVisible();
        await expect(page.getByText("CCM", { exact: true })).toBeVisible();
        await page.getByText("GCM", { exact: true }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to skip anonymization configuration", async ({ }) => {
        await expect(page.getByText("Anonymization", { exact: true })).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole('main').getByText('Replacement', { exact: true })).toBeVisible();
        await expect(page.getByRole('main').getByText('Hashing', { exact: true })).toBeVisible();
        await expect(page.getByRole('main').getByText('Redaction', { exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Add", exact: true })).toBeVisible();
        // await expect(page.getByRole("button", { name: "Skip", exact: true })).toBeVisible();
        // await page.getByRole("button", { name: "Skip", exact: true }).click();
        await page.getByRole("button", { name: "Add", exact: true }).click();
    })

    test("should be able to confirm deployment summary", async ({ }) => {
        await expect(page.locator("h5", { hasText: "Cloud Preferences" })).toBeVisible({ timeout: 20000 });
        await expect(page.locator("h5", { hasText: "Encryption" })).toBeVisible();
        await expect(page.locator("h5", { hasText: "Anonymization" })).toBeVisible();
        await expect(page.locator("h5", { hasText: "Large Language Models" })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to select agentic queries volume", async ({ }) => {
        await expect(page.locator("#workflow_id_5")).toBeVisible({ timeout: 20000 });
        await expect(page.locator('#workflow_id_5').getByText("Volumes", { exact: true })).toBeVisible();
        await expect(page.getByText("Now, let’s talk about agentic queries.")).toBeVisible();
        await expect(page.getByRole("radio", { name: "1000/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "2000/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "5000/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("radio", { name: "2000/mo", exact: true }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to select cases volume", async ({ }) => {
        await expect(page.getByText("How many cases would you like to maintain?")).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole("radio", { name: "100/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "200/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "500/mo", exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("radio", { name: "200/mo", exact: true }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to select storage size", async ({ }) => {
        await expect(page.locator("#workflow_id_6")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("#workflow_id_6").getByText("Sizing", { exact: true })).toBeVisible();
        await expect(page.getByText(/Now, let’s discuss storage./i)).toBeVisible();
        await expect(page.getByRole("radio", { name: "6TB", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "12TB", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "24TB", exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("radio", { name: "12TB", exact: true }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to confirm commitment period", async ({ }) => {
        await expect(page.locator("#workflow_id_7")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("#workflow_id_7").getByText("Commitment", { exact: true })).toBeVisible();
        await expect(page.getByText(/Your base package includes/i)).toBeVisible();
        await expect(page.getByRole("radio", { name: "12 months", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "24 months", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "36 months", exact: true })).toBeVisible();
        await expect(page.getByRole("radio", { name: "48 months", exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("radio", { name: "12 months", exact: true }).click();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to confirm SLA selection", async ({ }) => {
        await expect(page.locator("#workflow_id_8")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("#workflow_id_8").getByText("SLA", { exact: true })).toBeVisible();
        await expect(page.getByText(/Your base package currently includes/i)).toBeVisible();
        await expect(page.getByText("Bronze SLA", { exact: true })).toBeVisible();
        await expect(page.getByRole("main").getByText("Silver SLA")).toBeVisible();
        await expect(page.getByText("Gold SLA", { exact: true })).toBeVisible();
        await expect(page.getByText("Platinum SLA", { exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to confirm review", async ({ }) => {
        await expect(page.locator("#workflow_id_9")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("#workflow_id_9").getByText("Review", { exact: true })).toBeVisible();
        await expect(page.getByText("Please review all the selections.")).toBeVisible();
        await expect(page.locator("p", { hasText: "Finalize and checkout" })).toBeVisible();

        await expect(page.getByRole("tab", { name: "Basic Details", exact: true })).toBeVisible();
        await expect(page.getByRole("tab", { name: "Localization", exact: true })).toBeVisible();
        await expect(page.getByRole("tab", { name: "Subscription", exact: true })).toBeVisible();
        await expect(page.getByRole("tab", { name: "Additional Features", exact: true })).toBeVisible();

        await expect(page.locator("p", { hasText: "Organization Name" })).toBeVisible();
        await expect(page.locator("p", { hasText: onboardingFullName })).toBeVisible();

        await expect(page.locator("p").filter({ hasText: /^Organization Type$/ })).toBeVisible();
        await expect(page.locator("p", { hasText: "Law Firm" })).toBeVisible();

        await expect(page.locator("p", { hasText: "Organization Size" })).toBeVisible();
        await expect(page.getByLabel("Basic Details").getByText("1 to 10", { exact: true })).toBeVisible();

        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should be able to connect wallet", async ({ }) => {
        await expect(page.locator("#workflow_id_10")).toBeVisible({ timeout: 20000 });
        await expect(page.locator("#workflow_id_10").getByText("Initiate Deployment", { exact: true })).toBeVisible();
        await expect(page.getByText("Connect your wallet", { exact: true }).first()).toBeVisible();
        await expect(page.getByRole("textbox", { name: "Wallet Address" })).toBeVisible();
        await expect(page.getByLabel("Currency", { exact: true })).toBeVisible();
        await expect(page.getByRole("button", { name: "Confirm", exact: true })).toBeVisible();
        await page.getByRole("textbox", { name: "Wallet Address", exact: true }).fill(onboardingWalletAddress);
        await page.getByRole("button", { name: "Confirm", exact: true }).click();
    })

    test("should show checkout options", async ({ }) => {
        await expect(page.getByRole("heading", { name: "Checkout", exact: true })).toBeVisible({ timeout: 20000 });
        await expect(page.getByRole("button", { name: "Credit/Debit Card payment method" })).toBeVisible();
        await expect(page.getByRole("button", { name: "Bank Transfer payment method" })).toBeVisible();
        await expect(page.getByRole("button", { name: "Initiate deployment", exact: true })).toBeVisible();
    })

    test("should be able to enter payment details", async ({ }) => {
        await expect(page.getByText("Card information", { exact: true })).toBeVisible({ timeout: 20000 });
        await page.getByPlaceholder("1234 1234 1234 1234").fill("4242424242424242");
        await page.getByPlaceholder("MM / YY").fill("12/34");
        await page.getByPlaceholder("CVC").fill("123");
        await page.getByPlaceholder("Postal Code").fill("12345");
        await page.getByPlaceholder("Full name on card").fill(onboardingFullName);
        await expect(page.getByRole("button", { name: "Initiate deployment" })).toBeEnabled({ timeout: 10000 });
    })

    test("should complete checkout and show confirmation", async ({ }) => {
        await page.getByRole("button", { name: "Initiate deployment", exact: true }).click();
        await expect(page.getByText("Robocorp onboarding has successfully captured your details.")).toBeVisible({ timeout: 20000 });
        await expect(page.getByText("You have been rewarded with 10 DAAC tokens.")).toBeVisible();
        await expect(page.getByText("You are now being redirected to the Robocorp platform to continue.")).toBeVisible();
        await page.waitForURL(/robocorp-fe-dev\.promptyf\.cloud/i, { timeout: 60000 });
        await expect(page.getByPlaceholder("Ask anything...").first()).toBeVisible({ timeout: 30000 });
    })

    test("should see 10 DAAC in wallet after chat loads", async () => {
        await page.getByRole("button", { name: "Toggle Wallet" }).click();
        const daacHeading = page.getByRole("heading", { name: "DAAC" });
        await daacHeading.click();
        await expect(daacHeading).toHaveText(/10\.00 DAAC/, { timeout: 10000 });
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
            return;
        }
    })

    test("should be able to create agent without domain", async () => {
        await chatPage.waitForChatReady();
        await runAgentCreationWithoutDomainFlow(page, chatPage);
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
    })

    test("should be able to create widget without domain", async () => {
        await chatPage.waitForChatReady();
        await completeWidgetCreationWithoutDomain(page, chatPage);
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
    })

    test("should be able to create dataset without domain", async () => {
        await chatPage.waitForChatReady();
        const dataset = new DatasetCreationProcess(page);

        await dataset.startDatasetCreation();
        await dataset.provideDatasetName();
        await dataset.provideDescription();
        await dataset.uploadDataset();
        await dataset.chooseSchema();
        await dataset.completeStudioSetup();
        await dataset.createDataset();
        await dataset.publishDataset();
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
    })

    test("should be able to create media without domain", async () => {
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
        const media = new MediaCreationProcess(page);
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        const sendButton = page.locator('#chat-input').getByRole('button').first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await expect(chatInput).toBeEnabled({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create media without a domain');
        await expect(sendButton).toBeVisible({ timeout: 30000 });
        await expect(sendButton).toBeEnabled({ timeout: 30000 });
        await sendButton.click();

        const outcome = await waitForMediaStartOutcome(page, media);
        if (outcome === 'terminal') {
            await expectTerminalMessage(page);
            await page.waitForTimeout(5000);
            return;
        }

        await media.continueAfterStart();
        await media.provideMediaName();
        await media.provideDescription();
        await media.uploadMedia('asset-creation-files/asset-image.jpg');
        await media.provideContentUrl('https://www.youtube.com/watch?v=5wSztvWhx14');
        await media.provideSource('https://www.youtube.com/watch?v=5wSztvWhx14');
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
    })

    test("should be able to create model without domain", async () => {
        const refreshChat = page.locator('#btn-refresh-chat').first();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
        const model = new ModelCreationProcess(page);
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        const sendButton = page.locator('#chat-input').getByRole('button').first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await expect(chatInput).toBeEnabled({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create a model without a domain');
        await expect(sendButton).toBeVisible({ timeout: 30000 });
        await expect(sendButton).toBeEnabled({ timeout: 30000 });
        await sendButton.click();

        const outcome = await waitForModelStartOutcome(page, model);
        if (outcome === 'terminal') {
            await expectTerminalMessage(page);
            await page.waitForTimeout(5000);
            return;
        }

        await model.waitForModelNamePrompt();
        await model.provideModelName();
        await model.provideDescription();
        await model.uploadThumbnail('asset-creation-files/asset-image.jpg');
        await model.uploadModelFile('asset-creation-files/rf.pkl');
        await model.createModel();
        if (await refreshChat.isVisible({ timeout: 2000 }).catch(() => false)) {
            await refreshChat.click({ force: true, timeout: 5000 }).catch(() => {});
        }
    })

    // 309. Can create asset
    test("should be able to create asset", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await createAndPublishSpamEmailDetectionModel();
    })

    // 310. Cannot update an asset in my inventory that i didnt create
    test("should not be able to update a model in the inventory that current user didn't create", async () => {
        test.setTimeout(900000);
        await clearChat();
        await chatPage.waitForChatReady();

        await logoutCurrentUser();
        await loginWithCredentials(MEDICAL_DIAGNOSIS_CREATOR_EMAIL, MEDICAL_DIAGNOSIS_CREATOR_PASSWORD);

        const model = new ModelCreationProcess(page);
        await model.closeWelcomePopupIfVisible();
        await createAndPublishMedicalDiagnosisModel();

        await clearChat();
        await logoutCurrentUser();
        await loginWithCredentials(MEDICAL_DIAGNOSIS_VIEWER_EMAIL, MEDICAL_DIAGNOSIS_VIEWER_PASSWORD);
        await clearChat();

        const viewerChatInput = page.getByRole("textbox", { name: "Ask anything..." }).first();
        await expect(viewerChatInput).toBeVisible({ timeout: 30000 });
        await viewerChatInput.click();
        await viewerChatInput.fill(`I need ${MEDICAL_DIAGNOSIS_MODEL_NAME}`);
        await page.locator("#chat-input").getByRole("button").click();

        await expect(page.getByRole("button", { name: "Maximize widget" })).toBeVisible({
            timeout: 300000
        });
        await page.getByRole("button", { name: "Maximize widget" }).click();
        await expect(page.getByRole("button", { name: "Model", exact: true })).toBeVisible({
            timeout: 15000
        });
        await page.getByRole("button", { name: "Model", exact: true }).click();

        const searchInput = page.getByRole("textbox", { name: "Search" });
        await expect(searchInput).toBeVisible({ timeout: 15000 });
        await searchInput.fill(MEDICAL_DIAGNOSIS_MODEL_NAME);
        await page.waitForTimeout(1000);

        const publishedButton = page
            .getByRole("button", {
                name: new RegExp(`PUBLISHED\\s+${MEDICAL_DIAGNOSIS_MODEL_NAME}`, "i")
            })
            .first();
        await expect(publishedButton).toBeVisible({ timeout: 15000 });
        await publishedButton.click();

        await page.locator("#btn_expand_model_0").click();
        await page.getByRole("button", { name: "Purchase" }).click();
        await page.getByRole("button", { name: "Unlimited Use 18.00 DAAC" }).click();
        await page.getByRole("button", { name: "Purchase" }).click();

        await expect(page.getByText("Successfully Purchased!")).toBeVisible({
            timeout: 300000
        });

        await page.locator("html").click();
        await page.waitForTimeout(1000);

        await page.locator(".lucide.lucide-maximize2").click();
        await page.waitForTimeout(2000);

        const closeWidgetButton = page.getByLabel("Close widget").first();
        if (await closeWidgetButton.isVisible({ timeout: 3000 }).catch(() => false)) {
            await closeWidgetButton.click();
        }

        await page.getByRole("button", { name: "Models" }).click();
        await page.waitForTimeout(1000);

        const modelSearch = page.getByRole("textbox", { name: "Search" });
        await expect(modelSearch).toBeVisible({ timeout: 15000 });
        await modelSearch.fill(MEDICAL_DIAGNOSIS_MODEL_NAME);
        await page.waitForTimeout(1000);

        const publishedModelButton = page
            .getByRole("button", {
                name: new RegExp(`PUBLISHED\\s+${MEDICAL_DIAGNOSIS_MODEL_NAME}`, "i")
            })
            .first();
        await expect(publishedModelButton).toBeVisible({ timeout: 15000 });
        await publishedModelButton.locator("#btn_see_details").click();

        await expect(page.getByRole("button", { name: /^Edit$/i })).not.toBeVisible({
            timeout: 10000
        });
    })

    // 311. Can save an asset before publishing and the asset will appear in Draft status in the inventory
    test("should be able to save a model before publishing and the model will appear in draft status in the inventory", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await createCancerPredictionModelAsDraft();

        await page.getByRole("button", { name: "Open inventory" }).click();
        await expect(page.getByRole("button", { name: "Models" })).toBeVisible({ timeout: 15000 });
        await page.getByRole("button", { name: "Models" }).click();

        await expect(
            page.getByRole("button", { name: new RegExp(`DRAFT\\s+${CANCER_PREDICTION_MODEL_NAME}`, "i") }).first()
        ).toBeVisible({ timeout: 15000 });
    })

    // 312. Can update all asset fields when it Draft
    test("should be able to update all asset fields when it is Draft", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await createVehicleTypePredictorModelAsDraft();

        await page.getByRole("button", { name: "Open inventory" }).click();
        await expect(page.getByRole("button", { name: "Models" })).toBeVisible({ timeout: 15000 });
        await page.getByRole("button", { name: "Models" }).click();

        const draftModelButton = page
            .getByRole("button", {
                name: new RegExp(`DRAFT\\s+${VEHICLE_TYPE_PREDICTOR_MODEL_NAME}`, "i")
            })
            .first();
        await expect(draftModelButton).toBeVisible({ timeout: 60000 });
        await draftModelButton.locator("#btn_see_details").click();

        const inventoryActionButton = page.getByRole("button").nth(1);
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => { });
        }

        const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const nameInput = page.getByRole("textbox", { name: "Name Your Model" }).first();
        const descriptionInput = page.getByRole("textbox", { name: "Describe the model in a" }).first();

        await expect(nameInput).toBeEditable({ timeout: 30000 });
        await nameInput.fill(VEHICLE_TYPE_PREDICTOR_MODEL_UPDATED_NAME);

        await expect(descriptionInput).toBeEditable({ timeout: 30000 });
        await descriptionInput.fill(VEHICLE_TYPE_PREDICTOR_MODEL_UPDATED_DESCRIPTION);

        const saveButton = page.getByRole("button", { name: "Save" }).first();
        await expect(saveButton).toBeVisible({ timeout: 30000 });
        await saveButton.click();

        const removeThumbnailButton = page.getByRole("button", { name: "Remove thumbnail" }).first();
        if (await removeThumbnailButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await removeThumbnailButton.click();
        }

        const thumbnailButton = page.getByRole("button", { name: "Thumbnail" }).first();
        await expect(thumbnailButton).toBeVisible({ timeout: 30000 });
        await thumbnailButton.setInputFiles(VEHICLE_TYPE_PREDICTOR_MODEL_THUMBNAIL);

        await saveButton.click();
        await expect(page.getByRole("heading", { name: "Changes saved successfully!" })).toBeVisible({
            timeout: 120000
        });

        await page.getByRole("tab", { name: "Files" }).click();
        await page.getByRole("tab", { name: "Review" }).click();

        await expect(page.getByRole("textbox", { name: /Name your model/i })).toBeVisible({
            timeout: 10000
        });
    })

    // 209. Cannot create utility with assets not having unlimited pricing plan
    test("should not be able to create an utility with assets not having unlimited pricing plan", async () => {
        test.setTimeout(900000);
        await clearChat();
        await chatPage.waitForChatReady();

        const createdAgentName = await createAndPublishAgentWithoutUnlimitedPricingForUtility();

        await clearChat();
        await page.reload({ waitUntil: "domcontentloaded" });
        await page.waitForTimeout(4000);
        const skipBusinessProfileButton = page.getByRole("button", { name: /Skip for now/i }).first();
        if (await skipBusinessProfileButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await skipBusinessProfileButton.click();
        }
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();
        await completeUtilitySetupUntilAssetsStepForNonUnlimited();

        const addAssetsButton = page.getByRole("button", { name: "Add +" }).first();
        await expect(addAssetsButton).toBeVisible({ timeout: 30000 });
        await addAssetsButton.click();

        await expect(page.getByRole("button", { name: new RegExp(`^PUBLISHED\\s+${createdAgentName}$`, "i") })).toHaveCount(0, {
            timeout: 30000
        });
    })

    // 210. Can create a utility without picking a domain and then any assets used by the utility are from the Default domain
    test("should be able to create an utility without picking a domain and then any assets used by the utility are from the default domain", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();
        await fillUtilityDetailsAndVerifyDefaultDomain(
            `Default Domain Utility ${Date.now()}`,
            "Utility creation flow where domain is not manually selected and default domain is used."
        );
    });

    // 216. Cannot update utility domain, assets, API connection or pricing after it is created
    test("should not be able to update utility domain, assets, API connections or pricing after it is created", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        const openInventoryButton = page.getByRole("button", { name: "Open inventory" }).first();
        await expect(openInventoryButton).toBeVisible({ timeout: 60000 });
        await openInventoryButton.click();

        const manageAssetsText = page.getByText("Manage your assets").first();
        await expect(manageAssetsText).toBeVisible({ timeout: 60000 });
        await manageAssetsText.click();

        const utilitiesButton = page.getByRole("button", { name: "Utilities" }).first();
        await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
        await utilitiesButton.click();

        const createdUtilityRow = page.getByRole("button", { name: /^(PUBLISHED|DRAFT) /i }).first();
        await expect(createdUtilityRow).toBeVisible({ timeout: 60000 });

        const utilityActionButton = page.locator(".absolute.right-3").first();
        await expect(utilityActionButton).toBeVisible({ timeout: 30000 });
        await utilityActionButton.click();

        const editButton = page.locator("#edit").first();
        await expect(editButton).toBeVisible({ timeout: 30000 });
        await expect(editButton).toBeDisabled({ timeout: 30000 });
    });

    // 218. Cannot update utility domain, assets, API connection or pricing after it is published
    test("should not be able to update utility domain, assets, API connection or pricing after it is published", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        const openInventoryButton = page.getByRole("button", { name: "Open inventory" }).first();
        await expect(openInventoryButton).toBeVisible({ timeout: 60000 });
        await openInventoryButton.click();

        const manageAssetsText = page.getByText("Manage your assets").first();
        await expect(manageAssetsText).toBeVisible({ timeout: 60000 });
        await manageAssetsText.click();

        const utilitiesButton = page.getByRole("button", { name: "Utilities" }).first();
        await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
        await utilitiesButton.click();

        const publishedFilterButton = page.getByRole("button", { name: "PUBLISHED", exact: true }).first();
        if (await publishedFilterButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await publishedFilterButton.click();
        }

        const publishedUtilityButton = page.getByRole("button", { name: /PUBLISHED Travel Planner/i }).first();
        await expect(publishedUtilityButton).toBeVisible({ timeout: 60000 });
        await publishedUtilityButton.locator("#btn_see_details").click();

        const utilityActionButton = page.getByRole("button").first();
        await expect(utilityActionButton).toBeVisible({ timeout: 30000 });
        await utilityActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const dataStudioButton = page.getByText("Data Studio", { exact: true }).first();
        await expect(dataStudioButton).toBeVisible({ timeout: 60000 });
        await dataStudioButton.click();

        const maximizeWidgetButton = page.getByRole("button", { name: "Maximize widget" }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
        const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
        const domainInput = page.getByRole("textbox", { name: "Domain of the Utility" }).first();

        await expect(purposeInput).toBeVisible({ timeout: 30000 });
        await expect(purposeInput).not.toBeEditable();

        await expect(descriptionInput).toBeVisible({ timeout: 30000 });
        await expect(descriptionInput).not.toBeEditable();

        await expect(domainInput).toBeVisible({ timeout: 30000 });
        await expect(domainInput).not.toBeEditable();

        const marketingInformationTab = page.getByRole("tab", { name: "Marketing Information" }).first();
        if (await marketingInformationTab.isVisible({ timeout: 5000 }).catch(() => false)) {
            await marketingInformationTab.click();
        }

        await expect(page.locator(".lucide.lucide-database").first()).toBeVisible({ timeout: 30000 });
        await expect(page.locator(".lucide.lucide-cable").first()).toBeVisible({ timeout: 30000 });
    });

    // 221. Can create asset with multple agents/widgets which share data
    test("should be able to create utility asset with multiple agents/widgets which share data", async () => {
        test.setTimeout(900000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();
        await completeUtilitySetupUntilAssetsStep();
        await addFirstThreePublishedUtilityAssets();

        const setApiButton = page.getByRole("button", { name: "Set API" }).first();
        if (await setApiButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await setApiButton.click();
        }

        const firstNodeAddButton = page.locator('[data-testid^="rf__node-"]').getByRole("button", { name: "Add" }).first();
        if (await firstNodeAddButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await firstNodeAddButton.click();
            const instructionInput = page.getByRole("textbox", { name: "Instruction" }).first();
            await expect(instructionInput).toBeVisible({ timeout: 30000 });
            await instructionInput.fill("Initial utility API instruction.");
            await page.getByRole("button", { name: "Save" }).first().click();
        }

        await dragConnectUtilityNodes();

        const createButton = page.getByRole("button", { name: "Create" }).first();
        await expect(createButton).toBeVisible({ timeout: 30000 });
        await expect(createButton).toBeEnabled({ timeout: 30000 });
        await createButton.click();

        await expect(page.getByRole("heading", { name: /Successfully Created!/i }).first()).toBeVisible({
            timeout: 180000
        });
    });

    // 224. Can test successfully adding values using one asset and viewing them using another asset
    test("should be able to test successfully adding values using one asset and viewing them using another asset", async () => {
        test.setTimeout(480000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openPublishedUtilityAndRunPrompt("Plan a travel journey from Sri Lanka to Germany");
    });

    // 217. can update a utility name, description, thumbnail, tags and prerequists of a created asset before it is published
    test("should be able to update a utility name, description, thumbnail, tags and prerequisites of a created asset before it is published", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openFirstDraftUtilityInInventoryAndSwitchToEditor();

        const updatedPurpose = `Agriculture Utility ${Date.now()}`;
        const updatedDescription =
            "The Agriculture Utility is a smart tool designed to support farmers and agribusiness users with crop, weather, irrigation, pest, and yield insights.";
        const updatedPrerequisites = "Farm location, crop type, and season details";

        const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
        await expect(purposeInput).toBeEditable({ timeout: 30000 });
        await purposeInput.fill(updatedPurpose);

        const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
        await expect(descriptionInput).toBeEditable({ timeout: 30000 });
        await descriptionInput.fill(updatedDescription);

        await page.getByRole("button", { name: "Next" }).first().click();

        const tagsCombobox = page.getByRole("combobox", { name: "Tags/categories" }).first();
        await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
        await tagsCombobox.click();
        await tagsCombobox.fill("cultivation");
        await tagsCombobox.press("Enter");

        const prerequisitesInput = page.getByRole("textbox", { name: "Prerequisites" }).first();
        await expect(prerequisitesInput).toBeEditable({ timeout: 30000 });
        await prerequisitesInput.fill(updatedPrerequisites);

        const thumbnailInput = page.getByRole("button", { name: "Thumbnail*" }).first();
        await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
        await thumbnailInput.setInputFiles(path.join(process.cwd(), "asset-creation-files", "asset-image.jpg"));

        await page.getByRole("button", { name: "Next" }).first().click();
        await expect(page.getByRole("heading", { name: "Utility updated successfully!" }).first()).toBeVisible({
            timeout: 120000
        });
    });

    // 212. Can save an asset before clicking create and the asset will appear in Draft status in the inventory
    test("should be able to save an utility asset before clicking create and the asset will appear in draft status in the inventory", async () => {
        test.setTimeout(900000);
        await clearChat();
        await chatPage.waitForChatReady();

        const utilityPurpose = `Draft Utility ${Date.now()}`;
        await openUtilityCreationStudioFromChat();
        await completeUtilitySetupUntilBuilderForDraftSave(
            utilityPurpose,
            "Utility draft-save flow that validates the asset can be finalized as draft and appears in inventory."
        );

        const publishedAssetAdded = await addFirstPublishedUtilityAssetForDraft();
        if (!publishedAssetAdded) {
            return;
        }

        const closeWidgetButton = page.getByRole("button", { name: "Close widget" }).first();
        await expect(closeWidgetButton).toBeVisible({ timeout: 60000 });
        await closeWidgetButton.click();

        const openInventoryButton = page.getByRole("button", { name: "Open inventory" }).first();
        await expect(openInventoryButton).toBeVisible({ timeout: 60000 });
        await openInventoryButton.click();

        const manageAssetsText = page.getByText("Manage your assets").first();
        await expect(manageAssetsText).toBeVisible({ timeout: 60000 });
        await manageAssetsText.click();

        const utilitiesButton = page.getByRole("button", { name: "Utilities" }).first();
        await expect(utilitiesButton).toBeVisible({ timeout: 30000 });
        await utilitiesButton.click();

        const draftUtilityByPurpose = page.getByRole("button", {
            name: new RegExp(`DRAFT.*${escapeRegExp(utilityPurpose)}`, "i")
        }).first();

        if (await draftUtilityByPurpose.isVisible({ timeout: 10000 }).catch(() => false)) {
            await expect(draftUtilityByPurpose).toBeVisible({ timeout: 30000 });
            return;
        }

        const draftUtilityButton = page.getByRole("button", { name: /^DRAFT /i }).first();
        await expect(draftUtilityButton).toBeVisible({ timeout: 30000 });
    });

    // 213. Can update all asset fields before clicking create
    test("should be able to update all utility asset fields before clicking create", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();

        const purposeInput = page.getByRole("textbox", { name: "Purpose of the Utility" }).first();
        const descriptionInput = page.getByRole("textbox", { name: "Describe the utility in a" }).first();
        const domainSelector = page.locator(".flex.flex-1 > div:nth-child(3) > .relative.flex").first();
        const defaultDomainButton = page.getByRole("button", { name: "default" }).first();
        const nextButton = page.getByRole("button", { name: "Next" }).first();

        await expect(purposeInput).toBeVisible({ timeout: 30000 });
        await purposeInput.fill("Travel Planner Utility");
        await purposeInput.fill("Travel Planner Utility Updated");

        await expect(descriptionInput).toBeVisible({ timeout: 30000 });
        await descriptionInput.fill("Initial travel utility description.");
        await descriptionInput.fill(
            "Updated utility description with itinerary planning, budget tracking, and booking support."
        );

        await expect(domainSelector).toBeVisible({ timeout: 30000 });
        await domainSelector.click();
        await expect(defaultDomainButton).toBeVisible({ timeout: 30000 });
        await defaultDomainButton.click();

        await expect(nextButton).toBeEnabled({ timeout: 30000 });
        await nextButton.click();

        const tagsCombobox = page.getByRole("combobox", { name: "Tags/categories" }).first();
        const thumbnailInput = page.getByRole("button", { name: "Thumbnail*" }).first();
        await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
        await tagsCombobox.click();
        await tagsCombobox.fill("travel");
        await page.getByRole("option", { name: "Travel", exact: true }).first().click();

        await expect(thumbnailInput).toBeVisible({ timeout: 30000 });
        const thumbnailPath = path.join(process.cwd(), "asset-creation-files", "asset-image.jpg");
        await thumbnailInput.setInputFiles(thumbnailPath);
        await thumbnailInput.setInputFiles(thumbnailPath);

        await page.getByRole("button", { name: "Next" }).first().click();
        const workflowSearch = page.getByRole("textbox", { name: "Select" }).first();
        await expect(workflowSearch).toBeVisible({ timeout: 30000 });
        await workflowSearch.click();
        await page.getByRole("button", { name: "Manual Intake Workflow" }).first().click();
        await page.getByRole("button", { name: "Next" }).first().click();

        await addFirstThreePublishedUtilityAssets();

        const setApiButton = page.getByRole("button", { name: "Set API" }).first();
        if (await setApiButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await setApiButton.click();
        }

        const firstNodeAddButton = page.locator('[data-testid^="rf__node-"]').getByRole("button", { name: "Add" }).first();
        if (await firstNodeAddButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await firstNodeAddButton.click();
            const instructionInput = page.getByRole("textbox", { name: "Instruction" }).first();
            await expect(instructionInput).toBeVisible({ timeout: 30000 });
            await instructionInput.fill("Create Travel Plan");
            await instructionInput.fill("Create Travel Plan Updated");
            await page.getByRole("button", { name: "Save" }).first().click();
        }

        await dragConnectUtilityNodes();

        await expect(purposeInput).toHaveValue("Travel Planner Utility Updated");
        await expect(descriptionInput).toHaveValue(
            "Updated utility description with itinerary planning, budget tracking, and booking support."
        );

        const createButton = page.getByRole("button", { name: "Create" }).first();
        await expect(createButton).toBeVisible({ timeout: 30000 });
    })

    // 214. Cannot save a utility without assets
    test("should not be able to save a utility without assets", async () => {
        test.setTimeout(480000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();
        await completeUtilitySetupUntilAssetsStep();

        const addAssetsButton = page.getByRole("button", { name: "Add +" }).first();
        await expect(addAssetsButton).toBeVisible({ timeout: 30000 });

        const createButtonWithoutAssets = page.getByRole("button", { name: "Create" }).first();
        await expect(createButtonWithoutAssets).toBeDisabled({ timeout: 30000 });
    })

    // 215. Can succesfully add and remove assets to a utility before it is created. When changing assets list, the API connections are changed accordingly and warning appears of change
    test("should be able to successfully add and remove assets to a utility before it is created", async () => {
        test.setTimeout(900000);
        await clearChat();
        await chatPage.waitForChatReady();

        await openUtilityCreationStudioFromChat();
        await completeUtilitySetupUntilAssetsStep();
        await addFirstThreePublishedUtilityAssets();

        const setApiButton = page.getByRole("button", { name: "Set API" }).first();
        if (await setApiButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await setApiButton.click();
        }

        const firstNodeAddButton = page.locator('[data-testid^="rf__node-"]').getByRole("button", { name: "Add" }).first();
        if (await firstNodeAddButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await firstNodeAddButton.click();
            const instructionInput = page.getByRole("textbox", { name: "Instruction" }).first();
            await expect(instructionInput).toBeVisible({ timeout: 30000 });
            await instructionInput.fill("Initial utility API instruction.");
            await page.getByRole("button", { name: "Save" }).first().click();
        }

        await dragConnectUtilityNodes();

        const assetListUpdated = await replaceOneUtilityAssetAndVerifyConnectionChangeWarning();
        if (!assetListUpdated) {
            return;
        }

        const createButton = page.getByRole("button", { name: "Create" }).first();
        await expect(createButton).toBeVisible({ timeout: 30000 });
    })

    test("should be able to create a domain from a long document", async () => {
        test.setTimeout(600000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create an agent\n');
        await chatInput.click();
        await chatInput.fill('Yes\n');

        const filePath = path.join(
            process.cwd(),
            'asset-creation-files',
            'Agriculture_Domain_Guide_25_Pages.pdf'
        );
        await page.getByRole('button', { name: 'Select file to upload' }).click();
        await page.getByRole('button', { name: 'Select file to upload' }).setInputFiles(filePath);
        await page.getByRole('button', { name: 'Create' }).click();

        await expect(page.getByText('Domain Creation Widget')).toBeVisible({ timeout: 180000 });
        await page.getByRole('button', { name: 'Continue' }).click();
        await expect(page.getByText('Please follow the systems').nth(1)).toBeVisible({ timeout: 120000 });
    })

    test("should be able to create a domain from multiple documents", async () => {
        test.setTimeout(600000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create an agent\n');
        await chatInput.click();
        await chatInput.fill('Yes\n');

        const filePaths = [
            path.join(process.cwd(), 'asset-creation-files', 'Tourism_Domain_Guide_1.pdf'),
            path.join(process.cwd(), 'asset-creation-files', 'Tourism_Domain_Guide_2.pdf'),
            path.join(process.cwd(), 'asset-creation-files', 'Tourism_Domain_Guide_3.pdf')
        ];
        await page.getByRole('button', { name: 'Select file to upload' }).click();
        await page.getByRole('button', { name: 'Select file to upload' }).setInputFiles(filePaths);
        await page.getByRole('button', { name: 'Create' }).click();

        await expect(page.getByText('Domain Creation Widget')).toBeVisible({ timeout: 180000 });
        await page.getByRole('button', { name: 'Continue' }).click();
        await expect(page.getByText('Please follow the systems').nth(1)).toBeVisible({ timeout: 120000 });
    })

    test("should be able to see all schemas in the domain appearing in the inventory", async () => {
        test.setTimeout(300000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Schemas' }).click();
        await page.getByRole('button', { name: 'See details...' }).nth(1).click();
        await expect(page.getByRole('heading', { name: 'SCHEMA: AutomationValidation' })).toBeVisible({ timeout: 120000 });
    })

    test("should be able to update the schema", async () => {
        test.setTimeout(300000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Schemas' }).click();
        await page.locator('.absolute.right-3').first().click();
        await page.locator('#edit').click();
        await page.locator('#inventory_widget_canvas_1_close_btn').click();
        await page.getByRole('button', { name: 'Maximize widget' }).click();
        await page.getByRole('textbox', { name: 'Schema Name' }).click();
        await page.getByRole('textbox', { name: 'Schema Name' }).fill('AutomationValidationTest');
        await page.getByRole('button', { name: 'Save Schema' }).click();
        await expect(page.getByRole('heading', { name: 'Schema saved successfully.' })).toBeVisible({ timeout: 120000 });
    })

    test("should be able to see updated changes of schema in the inventory", async () => {
        test.setTimeout(300000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Schemas' }).click();
        await page.getByRole('button', { name: 'See details...' }).nth(1).click();
        await expect(page.getByRole('heading', { name: 'SCHEMA: AutomationValidationTest' })).toBeVisible({ timeout: 120000 });
    })

    test("should be able to see changed domain schemas when selecting the domain during asset creation", async () => {
        test.setTimeout(600000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await chatInput.click();
        await chatInput.fill('I need to create an agent\n');
        await chatInput.click();
        await chatInput.fill('Yes\n');
        await page.getByRole('button', { name: 'Existing Domain' }).click();
        await page.getByRole('checkbox', { name: 'Automation Validation' }).click();
        await expect(page.getByText('Domain Creation Widget')).toBeVisible({ timeout: 180000 });
        await page.getByRole('button', { name: 'Continue' }).click();

        await chatInput.click();
        await chatInput.fill('Tourism Agent\n');
        await chatInput.click();
        await chatInput.fill('Tourism Agent in UK\n');
        await page.getByRole('button', { name: 'Agentic Flow Where the agent' }).click();
        await chatInput.click();
        await chatInput.fill('booking.com, airbnb.com\n');
        await page.getByRole('button', { name: 'Create DDA lean back and' }).click();

        await expect(page.getByRole('heading', { name: 'Successfully Created!' })).toBeVisible({ timeout: 180000 });
        await page.getByLabel('Close widget').first().click();
    })

    // 211. Cannot update an asset in my inventorty that i didnt create
    test("should not be able to update an utility asset in the inventory that current user didn't create", async () => {
        test.setTimeout(600000);
        await clearChat();
        await chatPage.waitForChatReady();

        await purchaseAgricultureUtilityFromMarketplace();
        await clearChat();
        await page.reload({ waitUntil: 'domcontentloaded' });
        await page.waitForTimeout(4000);
        const skipBusinessProfileButton = page.getByRole('button', { name: /Skip for now/i }).first();
        if (await skipBusinessProfileButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await skipBusinessProfileButton.click();
        }
        await chatPage.waitForChatReady();
        await openFirstUtilityFromInventory();

        await expect(page.locator('#edit').first()).toBeDisabled({ timeout: 30000 });
    })

    test("should not be able to update an curated data asset in inventory that current user didn't create", async () => {
        test.setTimeout(360000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('Open Marketplace\n');

        await expect(
            page
                .getByLabel('Widget content')
                .getByRole('paragraph')
                .filter({ hasText: /^Marketplace$/ })
        ).toBeVisible({ timeout: 180000 });

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        await page.getByRole('button', { name: 'Curated Data' }).click();
        await page.locator('#btn_expand_datasets_0').click();
        await page.getByRole('button', { name: 'Purchase' }).click();
        await page.getByRole('button', { name: 'single_use 1.00 DAAC' }).click();
        await page.getByRole('button', { name: 'Purchase' }).click();

        await expect(page.getByText('Successfully Purchased!')).toBeVisible({ timeout: 60000 });

        const closeWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await closeWidgetButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeWidgetButton.click();
        }

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        await page.getByRole('button', { name: 'Curated Data' }).click();
        await page.locator('.absolute.right-3').first().click();

        await expect(page.locator('#edit')).toBeDisabled();
    })

    test("should be able to update all curated data asset fields when it is in draft", async () => {
        test.setTimeout(480000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const inventoryMaximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await inventoryMaximizeButton.isVisible({ timeout: 20000 }).catch(() => false)) {
            await inventoryMaximizeButton.click();
        }

        await page.getByRole('button', { name: 'Curated Data' }).click();
        const draftCuratedDataButton = page.getByRole('button', { name: /DRAFT.*Tourism Guide/i }).first();
        await expect(draftCuratedDataButton).toBeVisible({ timeout: 60000 });
        await draftCuratedDataButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').first();
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => { });
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const nameInput = page.getByRole('textbox', { name: 'Name Your Asset' }).first();
        const descriptionInput = page.getByRole('textbox', { name: 'Describe the asset in a' }).first();
        const tagsCombobox = page.getByRole('combobox', { name: 'Tags/categories' }).first();

        await expect(nameInput).toBeEditable({ timeout: 30000 });
        await nameInput.fill(`Tourism Guide Dataset Test ${Date.now()}`);

        await expect(descriptionInput).toBeEditable({ timeout: 30000 });
        await descriptionInput.fill('Test 2');

        const firstSaveButton = page.getByRole('button', { name: 'Save' }).first();
        await expect(firstSaveButton).toBeVisible({ timeout: 30000 });
        await firstSaveButton.click();

        await page.locator('.relative.flex.w-full.items-center').first().click();
        await expect(tagsCombobox).toBeEditable({ timeout: 30000 });
        await tagsCombobox.fill('Tourism');
        await page.getByRole('option', { name: /tourism/i }).first().click();

        const removeThumbnailButton = page.getByRole('button', { name: 'Remove thumbnail' }).first();
        if (await removeThumbnailButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await removeThumbnailButton.click();
        }

        const testImagePath = path.join(process.cwd(), 'asset-creation-files', 'test-image.png');
        const thumbnailButton = page.getByRole('button', { name: 'Thumbnail' }).first();
        await expect(thumbnailButton).toBeVisible({ timeout: 30000 });
        await thumbnailButton.setInputFiles(testImagePath);

        await firstSaveButton.click();
        await expect(page.getByRole('heading', { name: 'Changes saved successfully!' })).toBeVisible({ timeout: 120000 });
    })

    test("should be able to update all curated data asset fields before it is sold at least once", async () => {
        test.setTimeout(600000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const inventoryMaximizeButton = page.locator('.lucide.lucide-maximize2').first();
        if (await inventoryMaximizeButton.isVisible({ timeout: 20000 }).catch(() => false)) {
            await inventoryMaximizeButton.click();
        }

        await page.getByRole('button', { name: 'Curated Data' }).click();
        const draftCuratedDataButton = page.getByRole('button', { name: /DRAFT.*Tourism Guide/i }).first();
        await expect(draftCuratedDataButton).toBeVisible({ timeout: 60000 });
        await draftCuratedDataButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').first();
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => { });
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const publishEntryButton = page.locator('div:nth-child(5) > .flex > .lucide').first();
        if (await publishEntryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await publishEntryButton.click();
        }

        const publishButton = page.getByRole('button', { name: 'Publish' }).first();
        await expect(publishButton).toBeVisible({ timeout: 60000 });
        await publishButton.click();

        const singleUsePrice = page.locator('#sabw_form-field-single-use').getByRole('textbox').first();
        const fiveUsesPrice = page.locator('#sabw_form-field-five-uses').getByRole('textbox').first();
        const annualPrice = page.locator('#sabw_form-field-annual').getByRole('textbox').first();
        const unlimitedPrice = page
            .locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]')
            .first();

        await expect(singleUsePrice).toBeVisible({ timeout: 30000 });
        await singleUsePrice.fill('1');
        await fiveUsesPrice.fill('1');
        await annualPrice.fill('1');
        await unlimitedPrice.fill('1');

        await page.getByRole('button', { name: 'Confirm' }).first().click();
        await expect(page.getByText('Asset published successfully!').first()).toBeVisible({ timeout: 120000 });

        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const inventoryMaximizeButtonAfterPublish = page.locator('.lucide.lucide-maximize2').first();
        if (await inventoryMaximizeButtonAfterPublish.isVisible({ timeout: 20000 }).catch(() => false)) {
            await inventoryMaximizeButtonAfterPublish.click();
        }

        await page.getByRole('button', { name: 'Curated Data' }).click();
        const publishedCuratedDataButton = page.getByRole('button', { name: /PUBLISHED.*Tourism/i }).first();
        await expect(publishedCuratedDataButton).toBeVisible({ timeout: 60000 });
        await publishedCuratedDataButton.locator('#btn_see_details').click();

        const publishedAssetActionButton = page.getByRole('button').first();
        await expect(publishedAssetActionButton).toBeVisible({ timeout: 30000 });
        await publishedAssetActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidgetAfterPublish = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidgetAfterPublish.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidgetAfterPublish.click({ force: true }).catch(() => { });
        }

        const maximizeWidgetButtonAfterPublish = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButtonAfterPublish).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButtonAfterPublish.click();

        const nameInput = page.getByRole('textbox', { name: 'Name Your Asset' }).first();
        const descriptionInput = page.getByRole('textbox', { name: 'Describe the asset in a' }).first();
        const tagsCombobox = page.getByRole('combobox').first();

        await expect(nameInput).toBeEditable({ timeout: 30000 });
        await nameInput.fill(`Tourism Guide Dataset Test 2 ${Date.now()}`);

        await expect(descriptionInput).toBeEditable({ timeout: 30000 });
        await descriptionInput.fill('Test 3');

        const saveButton = page.getByRole('button', { name: 'Save' }).first();
        await expect(saveButton).toBeVisible({ timeout: 30000 });
        await saveButton.click();
        await expect(page.getByRole('heading', { name: 'Changes saved successfully!' }).first()).toBeVisible({ timeout: 120000 });

        await expect(tagsCombobox).toBeEditable({ timeout: 30000 });
        await tagsCombobox.click();
        await tagsCombobox.fill('hotels');
        await tagsCombobox.press('Enter');

        await saveButton.click();
        await expect(page.getByRole('heading', { name: 'Changes saved successfully!' }).first()).toBeVisible({ timeout: 120000 });
    })

    test("should not be able to update any field after curated data asset sold at least once", async () => {
        test.setTimeout(900000);
        const marketplaceBuyerEmail = process.env.USER_EMAIL?.trim() || 'automation@datafab.ai';
        const marketplaceBuyerPassword = process.env.USER_PASSWORD?.trim() || 'User@123';

        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Curated Data' }).click();
        const draftCuratedDataButton = page.getByRole('button', { name: /DRAFT.*Tourism Guide/i }).first();
        await expect(draftCuratedDataButton).toBeVisible({ timeout: 60000 });
        await draftCuratedDataButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').first();
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const reviewTab = page.getByRole('tab', { name: 'Review' }).first();
        if (await reviewTab.isVisible({ timeout: 10000 }).catch(() => false)) {
            await reviewTab.click();
        }

        const publishButton = page.getByRole('button', { name: 'Publish' }).first();
        await expect(publishButton).toBeVisible({ timeout: 60000 });
        await publishButton.click();

        await page.locator('#sabw_form-field-single-use').getByRole('textbox').first().fill('1');
        await page.locator('#sabw_form-field-five-uses').getByRole('textbox').first().fill('1');
        await page.locator('#sabw_form-field-annual').getByRole('textbox').first().fill('1');
        await page
            .locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]')
            .first()
            .fill('1');

        await page.getByRole('button', { name: 'Confirm' }).first().click();
        await expect(page.getByText('Asset published successfully!').first()).toBeVisible({ timeout: 120000 });

        await clearChat();
        await logoutCurrentUser();
        await loginWithCredentials(marketplaceBuyerEmail, marketplaceBuyerPassword);
        await clearChat();

        const buyerChatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(buyerChatInput).toBeVisible({ timeout: 30000 });
        await buyerChatInput.click();
        await buyerChatInput.fill('Open marketplace\n');

        await expect(
            page.getByLabel('Widget content').getByRole('paragraph').filter({ hasText: /^Marketplace$/ })
        ).toBeVisible({ timeout: 180000 });

        const marketplaceMaximizeButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(marketplaceMaximizeButton).toBeVisible({ timeout: 60000 });
        await marketplaceMaximizeButton.click();

        const marketplaceSearch = page.getByRole('textbox', { name: 'Search' }).first();
        await expect(marketplaceSearch).toBeVisible({ timeout: 30000 });
        await marketplaceSearch.fill('tourism');

        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await page.getByRole('button', { name: /unlimited.*1\.00 DAAC/i }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const closeMarketplaceWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await closeMarketplaceWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeMarketplaceWidgetButton.click();
        }

        await logoutCurrentUser();
        await loginWithCredentials(onboardingEmail, onboardingPassword, true);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Curated Data' }).click();
        const publishedCuratedDataButton = page.getByRole('button', { name: /PUBLISHED.*Tourism/i }).first();
        await expect(publishedCuratedDataButton).toBeVisible({ timeout: 60000 });
        await publishedCuratedDataButton.locator('#btn_see_details').click();

        const salesHeading = page.getByRole('heading', { name: /sales/i }).first();
        await expect(salesHeading).toBeVisible({ timeout: 30000 });

        const publishedAssetActionButton = page.getByRole('button').first();
        await expect(publishedAssetActionButton).toBeVisible({ timeout: 30000 });
        await publishedAssetActionButton.click();

        const closeInventoryWidgetAfterSale = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidgetAfterSale.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidgetAfterSale.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButtonAfterSale = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButtonAfterSale).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButtonAfterSale.click();

        const nameInput = page.getByRole('textbox', { name: 'Name Your Asset' }).first();
        const descriptionInput = page.getByRole('textbox', { name: 'Describe the asset in a' }).first();
        const tagsCombobox = page.getByRole('combobox').first();
        const saveButton = page.getByRole('button', { name: 'Save' }).first();

        await expect(nameInput).toBeVisible({ timeout: 30000 });
        await expect(nameInput).not.toBeEditable();
        await expect(descriptionInput).toBeVisible({ timeout: 30000 });
        await expect(descriptionInput).not.toBeEditable();
        await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
        await expect(tagsCombobox).not.toBeEditable();

        if (await saveButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await expect(saveButton).toBeDisabled();
        }
    })

    test("different onboarded user should be able to find the asset in marketplace where searching using text similar (not identical) to the description of the published asset", async () => {
        test.setTimeout(480000);
        await clearChat();

        const buyerChatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(buyerChatInput).toBeVisible({ timeout: 30000 });
        await buyerChatInput.click();
        await buyerChatInput.fill('I need a tourism guide dataset\n');

        await expect(
            page.getByLabel('Widget content').getByRole('paragraph').filter({ hasText: /^Marketplace$/ })
        ).toBeVisible({ timeout: 180000 });

        const marketplaceMaximizeButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(marketplaceMaximizeButton).toBeVisible({ timeout: 60000 });
        await marketplaceMaximizeButton.click();

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const firstDatasetExpandButton = page.locator('#btn_expand_datasets_0').first();
        await expect(firstDatasetExpandButton).toBeVisible({ timeout: 60000 });
        await firstDatasetExpandButton.click();

        const marketplaceWidgetContent = page.getByLabel('Widget content').first();
        await expect(marketplaceWidgetContent).toContainText(/tourism|guide|travel/i, { timeout: 60000 });

        const closeMarketplaceWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await closeMarketplaceWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeMarketplaceWidgetButton.click();
        }
    })

    test("should user be able to purchase the asset using metered method", async () => {
        test.setTimeout(480000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('open marketplace\n');

        const marketplaceLabel = page
            .getByLabel('Widget content')
            .getByRole('paragraph')
            .filter({ hasText: /^Marketplace$/ })
            .first();
        await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const secondDatasetExpandButton = page.locator('#btn_expand_datasets_1').first();
        await expect(secondDatasetExpandButton).toBeVisible({ timeout: 60000 });
        await secondDatasetExpandButton.click();

        const purchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(purchaseButton).toBeVisible({ timeout: 30000 });
        await purchaseButton.click();

        const singleUsePricingButton = page.getByRole('button', { name: 'single_use 1.00 DAAC' }).first();
        await expect(singleUsePricingButton).toBeVisible({ timeout: 30000 });
        await singleUsePricingButton.click();

        const confirmPurchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(confirmPurchaseButton).toBeVisible({ timeout: 30000 });
        await confirmPurchaseButton.click();

        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const closeWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await closeWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeWidgetButton.click();
        }

        const toggleWalletButton = page.getByRole('button', { name: 'Toggle Wallet' }).first();
        await expect(toggleWalletButton).toBeVisible({ timeout: 30000 });
        await toggleWalletButton.click();

        await expect(page.getByRole('heading', { name: 'DAAC' })).toBeVisible({ timeout: 30000 });
    })

    test("should user be able to consume the curated data asset and metered unit should be deducted", async () => {
        test.setTimeout(720000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('open marketplace\n');

        const marketplaceLabel = page
            .getByLabel('Widget content')
            .getByRole('paragraph')
            .filter({ hasText: /^Marketplace$/ })
            .first();
        await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const firstDatasetExpandButton = page.locator('#btn_expand_datasets_0').first();
        await expect(firstDatasetExpandButton).toBeVisible({ timeout: 60000 });
        await firstDatasetExpandButton.click();

        const purchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(purchaseButton).toBeVisible({ timeout: 30000 });
        await purchaseButton.click();

        const singleUsePricingButton = page.getByRole('button', { name: 'single_use 1.00 DAAC' }).first();
        await expect(singleUsePricingButton).toBeVisible({ timeout: 30000 });
        await singleUsePricingButton.click();

        const confirmPurchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(confirmPurchaseButton).toBeVisible({ timeout: 30000 });
        await confirmPurchaseButton.click();

        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const refreshChatButton = page.locator('#btn-refresh-chat').first();
        if (await refreshChatButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await refreshChatButton.click();
        }

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const inventoryCuratedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(inventoryCuratedDataButton).toBeVisible({ timeout: 30000 });
        await inventoryCuratedDataButton.click();

        const inventoryCategoryButton = page.locator('.flex.flex-col.items-center.justify-center.rounded-\\[2px\\]').first();
        if (await inventoryCategoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryCategoryButton.click();
        }

        const publishedAssetButton = page.getByRole('button', { name: /PUBLISHED.*Agriculture|PUBLISHED.*Tourism/i }).first();
        await expect(publishedAssetButton).toBeVisible({ timeout: 60000 });
        await publishedAssetButton.locator('#btn_see_details').click();

        const openAssetDetailsButton = page.locator('.w-it').first();
        await expect(openAssetDetailsButton).toBeVisible({ timeout: 30000 });
        await openAssetDetailsButton.click();

        const balanceBeforeConsumption = await getWalletBalanceDaac();

        await clearChat();
        const response = await sendSearchAndWaitForResponse('Give me a brief about the dataset');
        expect((response || '').trim().length).toBeGreaterThan(0);

        await expect.poll(
            async () => getWalletBalanceDaac(),
            { timeout: 90000, intervals: [2000, 3000, 5000] }
        ).toBeLessThan(balanceBeforeConsumption);
    })

    test("should user be able to consume the curated data asset with no KF or MKF using relevant agent/widget", async () => {
        test.setTimeout(720000);
        await clearChat();
        await purchaseAgricultureCuratedDataFromMarketplace();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('open knowledge fabric');
        await chatInput.press('Enter');

        const knowledgeFabricWidgetLabel = page
            .getByLabel('Widget content')
            .getByText('Knowledge Fabric', { exact: true })
            .first();
        await expect(knowledgeFabricWidgetLabel).toBeVisible({ timeout: 180000 });
        await knowledgeFabricWidgetLabel.click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        await page.getByRole('tab', { name: 'Explore' }).first().click();
        await page.getByRole('button', { name: 'Connectors' }).first().click();
        await expect(page.getByRole('heading', { name: 'Select an asset to view' }).first()).toBeVisible({ timeout: 60000 });

        const refreshChatButton = page.locator('#btn-refresh-chat').first();
        if (await refreshChatButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await refreshChatButton.click();
        }

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const categoryButton = page.locator('.flex.flex-col.items-center.justify-center.rounded-\\[2px\\]').first();
        if (await categoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await categoryButton.click();
        }

        const nextPageButton = page.locator('#next-page-button > .flex').first();
        if (await nextPageButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await nextPageButton.click();
        }

        const selectedAssetAction = page.locator('li:nth-child(4) > .group.relative.flex > button > .absolute').first();
        const selectedAssetActionVisible = await selectedAssetAction.isVisible({ timeout: 10000 }).catch(() => false);
        if (selectedAssetActionVisible) {
            await selectedAssetAction.click();
        } else {
            const fallbackAssetAction = page.locator('#btn_see_details').first();
            await expect(fallbackAssetAction).toBeVisible({ timeout: 30000 });
            await fallbackAssetAction.click();
        }

        const previousCount = await chatPage.getReceivedMessageCount();
        await chatInput.click();
        await chatInput.fill('Give me a brief about the dataset');
        await chatInput.press('Enter');
        await chatPage.waitForNewReceivedMessage(previousCount, 180000);
        await expect(page.getByText(/Sorry, it seems like there/i).first()).toBeVisible({ timeout: 120000 });
    })

    test("should user be able to consume the curated data asset using a relevant agent/widget with KF", async () => {
        test.setTimeout(900000);
        await clearChat();
        await purchaseAgricultureCuratedDataFromMarketplace();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('show me knowledge fabric');
        await chatInput.press('Enter');

        const knowledgeFabricWidgetLabel = page
            .getByLabel('Widget content')
            .getByText('Knowledge Fabric', { exact: true })
            .first();
        await expect(knowledgeFabricWidgetLabel).toBeVisible({ timeout: 180000 });
        await knowledgeFabricWidgetLabel.click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        await page.getByRole('tab', { name: 'Settings' }).first().click();
        await expect(page.getByRole('heading', { name: 'Services' }).first()).toBeVisible({ timeout: 30000 });
        await expect(page.getByRole('heading', { name: 'MCP integrations' }).first()).toBeVisible({ timeout: 30000 });

        await page.getByRole('button', { name: 'chromadb' }).first().click();

        const mcpNameInput = page.getByRole('textbox', { name: 'MCP Name' }).first();
        const mcpDescriptionInput = page.getByRole('textbox', { name: 'Description' }).first();
        await expect(mcpNameInput).toBeVisible({ timeout: 30000 });
        await mcpNameInput.fill('TestMCP');
        await expect(mcpDescriptionInput).toBeVisible({ timeout: 30000 });
        await mcpDescriptionInput.fill('Test MCP');
        await page.getByRole('button', { name: 'Next' }).first().click();

        const hostInput = page.getByRole('textbox', { name: 'Enter Host?' }).first();
        const portInput = page.getByPlaceholder('Enter Port?').first();
        const persistDirectoryInput = page.getByRole('textbox', { name: 'Enter Persist Directory?' }).first();
        const distanceInput = page.getByRole('textbox', { name: 'Enter Distance?' }).first();

        await expect(hostInput).toBeVisible({ timeout: 30000 });
        await hostInput.fill('localhost');
        await expect(portInput).toBeVisible({ timeout: 30000 });
        await portInput.fill('7988');
        await expect(persistDirectoryInput).toBeVisible({ timeout: 30000 });
        await persistDirectoryInput.fill('/srv');
        await expect(distanceInput).toBeVisible({ timeout: 30000 });
        await distanceInput.fill('1');
        await page.getByRole('button', { name: 'Submit' }).first().click();

        await expect(page.getByText('MCP service created').first()).toBeVisible({ timeout: 120000 });

        await page.getByRole('tab', { name: 'Explore' }).first().click();
        await page.getByRole('button', { name: 'Connectors' }).first().click();
        await expect(page.getByRole('button', { name: 'TestMCP' }).first()).toBeVisible({ timeout: 120000 });
        await page.getByRole('button', { name: 'TestMCP' }).first().click();

        await chatPage.refreshChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const categoryButton = page.locator('.flex.flex-col.items-center.justify-center.rounded-\\[2px\\]').first();
        if (await categoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await categoryButton.click();
        }

        const nextPageButton = page.locator('#next-page-button > .flex').first();
        if (await nextPageButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await nextPageButton.click();
        }

        const selectedAssetAction = page.locator('li:nth-child(4) > .group.relative.flex > button > .absolute').first();
        const selectedAssetActionVisible = await selectedAssetAction.isVisible({ timeout: 10000 }).catch(() => false);
        if (selectedAssetActionVisible) {
            await selectedAssetAction.click();
        } else {
            const fallbackAssetAction = page.locator('#btn_see_details').first();
            await expect(fallbackAssetAction).toBeVisible({ timeout: 30000 });
            await fallbackAssetAction.click();
        }

        const previousCount = await chatPage.getReceivedMessageCount();
        await chatInput.click();
        await chatInput.fill('Give me brief about dataset');
        await chatInput.press('Enter');
        await chatPage.waitForNewReceivedMessage(previousCount, 180000);
        await expect(page.getByText(/Sorry, it seems like there/i).first()).toBeVisible({ timeout: 120000 });
    })

    test("should user be able to consume the curated data asset using a relevant agent/widget with MKF", async () => {
        test.setTimeout(900000);
        await clearChat();
        await purchaseAgricultureCuratedDataFromMarketplace();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('show me knowledge fabric');
        await chatInput.press('Enter');

        const knowledgeFabricWidgetLabel = page
            .getByLabel('Widget content')
            .getByText('Knowledge Fabric', { exact: true })
            .first();
        await expect(knowledgeFabricWidgetLabel).toBeVisible({ timeout: 180000 });
        await knowledgeFabricWidgetLabel.click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        await page.getByRole('tab', { name: 'Settings' }).first().click();
        await expect(page.getByRole('heading', { name: 'Services' }).first()).toBeVisible({ timeout: 30000 });
        await expect(page.getByRole('heading', { name: 'MCP integrations' }).first()).toBeVisible({ timeout: 30000 });

        await page.getByRole('button', { name: 'chromadb' }).first().click();

        const mcpNameInput = page.getByRole('textbox', { name: 'MCP Name' }).first();
        const mcpDescriptionInput = page.getByRole('textbox', { name: 'Description' }).first();
        await expect(mcpNameInput).toBeVisible({ timeout: 30000 });
        await mcpNameInput.fill('TestMCP');
        await expect(mcpDescriptionInput).toBeVisible({ timeout: 30000 });
        await mcpDescriptionInput.fill('Test MCP');
        await page.getByRole('button', { name: 'Next' }).first().click();

        const hostInput = page.getByRole('textbox', { name: 'Enter Host?' }).first();
        const portInput = page.getByPlaceholder('Enter Port?').first();
        const persistDirectoryInput = page.getByRole('textbox', { name: 'Enter Persist Directory?' }).first();
        const distanceInput = page.getByRole('textbox', { name: 'Enter Distance?' }).first();

        await expect(hostInput).toBeVisible({ timeout: 30000 });
        await hostInput.fill('localhost');
        await expect(portInput).toBeVisible({ timeout: 30000 });
        await portInput.fill('7988');
        await expect(persistDirectoryInput).toBeVisible({ timeout: 30000 });
        await persistDirectoryInput.fill('/srv');
        await expect(distanceInput).toBeVisible({ timeout: 30000 });
        await distanceInput.fill('1');
        await page.getByRole('button', { name: 'Submit' }).first().click();

        await expect(page.getByText('MCP service created').first()).toBeVisible({ timeout: 120000 });

        await page.getByRole('tab', { name: 'Explore' }).first().click();
        await page.getByRole('button', { name: 'Connectors' }).first().click();
        await expect(page.getByRole('button', { name: 'TestMCP' }).first()).toBeVisible({ timeout: 120000 });
        await page.getByRole('button', { name: 'TestMCP' }).first().click();

        await chatPage.refreshChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const categoryButton = page.locator('.flex.flex-col.items-center.justify-center.rounded-\\[2px\\]').first();
        if (await categoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await categoryButton.click();
        }

        const nextPageButton = page.locator('#next-page-button > .flex').first();
        if (await nextPageButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await nextPageButton.click();
        }

        const selectedAssetAction = page.locator('li:nth-child(4) > .group.relative.flex > button > .absolute').first();
        const selectedAssetActionVisible = await selectedAssetAction.isVisible({ timeout: 10000 }).catch(() => false);
        if (selectedAssetActionVisible) {
            await selectedAssetAction.click();
        } else {
            const fallbackAssetAction = page.locator('#btn_see_details').first();
            await expect(fallbackAssetAction).toBeVisible({ timeout: 30000 });
            await fallbackAssetAction.click();
        }

        const previousCount = await chatPage.getReceivedMessageCount();
        await chatInput.click();
        await chatInput.fill('Give me brief about dataset');
        await chatInput.press('Enter');
        await chatPage.waitForNewReceivedMessage(previousCount, 180000);
        await expect(page.getByText(/Sorry, it seems like there/i).first()).toBeVisible({ timeout: 120000 });
    })

    test("should user be able to deactivate the asset", async () => {
        test.setTimeout(480000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const draftCuratedDataButton = page.getByRole('button', { name: /DRAFT.*Tourism Guide/i }).first();
        await expect(draftCuratedDataButton).toBeVisible({ timeout: 60000 });
        await draftCuratedDataButton.locator('#btn_see_details').click();

        const openAssetDetailsButton = page.locator('.w-it').first();
        await expect(openAssetDetailsButton).toBeVisible({ timeout: 30000 });
        await openAssetDetailsButton.click();

        const widgetContent = page.getByLabel('Widget content').first();
        await expect(widgetContent).toBeVisible({ timeout: 60000 });

        const statusButton = widgetContent
            .getByRole('button', { name: /deactivate|activate|active|inactive/i })
            .first();
        await expect(statusButton).toBeVisible({ timeout: 30000 });

        const statusButtonTextBefore = (await statusButton.innerText().catch(() => '')).trim();
        await statusButton.click();

        const statusUpdatedMessage = page.getByText(
            /Changes saved successfully!|Asset (de)?activated successfully!|Asset status updated successfully!/i
        ).first();

        const messageVisible = await statusUpdatedMessage.isVisible({ timeout: 20000 }).catch(() => false);
        if (!messageVisible) {
            if (/deactivate|active/i.test(statusButtonTextBefore)) {
                await expect(
                    widgetContent.getByRole('button', { name: /activate|inactive/i }).first()
                ).toBeVisible({ timeout: 30000 });
            } else {
                await expect(
                    widgetContent.getByRole('button', { name: /deactivate|active/i }).first()
                ).toBeVisible({ timeout: 30000 });
            }
        } else {
            await expect(statusUpdatedMessage).toBeVisible({ timeout: 30000 });
        }
    })

    test("should not be able to consume an inactive curated data asset", async () => {
        test.setTimeout(600000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need a agriculture crop yield dataset\n');

        const marketplaceLabel = page
            .getByLabel('Widget content')
            .getByRole('paragraph')
            .filter({ hasText: /^Marketplace$/ })
            .first();
        await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });

        const maximizeMarketplaceButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeMarketplaceButton).toBeVisible({ timeout: 60000 });
        await maximizeMarketplaceButton.click();

        const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
        await curatedDataButton.click();

        const firstDatasetExpandButton = page.locator('#btn_expand_datasets_0').first();
        await expect(firstDatasetExpandButton).toBeVisible({ timeout: 60000 });
        await firstDatasetExpandButton.click();

        const purchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(purchaseButton).toBeVisible({ timeout: 30000 });
        await purchaseButton.click();

        const unlimitedUseButton = page.getByRole('button', { name: /unlimited_use 1\.00 DAAC|unlimited.*1\.00 DAAC/i }).first();
        await expect(unlimitedUseButton).toBeVisible({ timeout: 30000 });
        await unlimitedUseButton.click();

        const confirmPurchaseButton = page.getByRole('button', { name: 'Purchase' }).first();
        await expect(confirmPurchaseButton).toBeVisible({ timeout: 30000 });
        await confirmPurchaseButton.click();
        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const refreshChatButton = page.locator('#btn-refresh-chat').first();
        await expect(refreshChatButton).toBeVisible({ timeout: 30000 });
        await refreshChatButton.click();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        const inventoryCuratedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(inventoryCuratedDataButton).toBeVisible({ timeout: 30000 });
        await inventoryCuratedDataButton.click();

        const publishedAgricultureAsset = page.getByRole('button', { name: /PUBLISHED.*Agriculture/i }).first();
        await expect(publishedAgricultureAsset).toBeVisible({ timeout: 60000 });
        await publishedAgricultureAsset.locator('#btn_see_details').click();

        const activeStatusButton = page.getByRole('button', { name: /^ACTIVE$|deactivate|active/i }).first();
        await expect(activeStatusButton).toBeVisible({ timeout: 30000 });
        await activeStatusButton.click();

        const inactiveStateVisible = await page
            .getByRole('button', { name: /^INACTIVE$|activate|inactive/i })
            .first()
            .isVisible({ timeout: 30000 })
            .catch(() => false);
        const statusMessageVisible = await page
            .getByText(/Asset (de)?activated successfully!|Asset status updated successfully!|Changes saved successfully!/i)
            .first()
            .isVisible({ timeout: 30000 })
            .catch(() => false);
        expect(inactiveStateVisible || statusMessageVisible).toBeTruthy();

        await clearChat();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need a agriculture crop yield dataset\n');
        await expect(marketplaceLabel).toBeVisible({ timeout: 180000 });

        const maximizeMarketplaceButtonAfterDeactivate = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeMarketplaceButtonAfterDeactivate).toBeVisible({ timeout: 60000 });
        await maximizeMarketplaceButtonAfterDeactivate.click();

        const curatedDataButtonAfterDeactivate = page.getByRole('button', { name: 'Curated Data' }).first();
        await expect(curatedDataButtonAfterDeactivate).toBeVisible({ timeout: 30000 });
        await curatedDataButtonAfterDeactivate.click();

        const firstDatasetExpandButtonAfterDeactivate = page.locator('#btn_expand_datasets_0').first();
        await expect(firstDatasetExpandButtonAfterDeactivate).toBeVisible({ timeout: 60000 });
        await firstDatasetExpandButtonAfterDeactivate.click();

        await expect(page.getByRole('button', { name: 'Purchase' }).first()).toHaveCount(0, { timeout: 15000 });
    })

    test("should user be able to activate the inactive asset", async () => {
        test.setTimeout(600000);
        const marketplaceBuyerEmail = process.env.USER_EMAIL?.trim() || 'automation@datafab.ai';
        const marketplaceBuyerPassword = process.env.USER_PASSWORD?.trim() || 'User@123';

        await clearChat();
        await logoutCurrentUser();

        try {
            await loginWithCredentials(marketplaceBuyerEmail, marketplaceBuyerPassword);
            await clearChat();

            await page.getByRole('button', { name: 'Open inventory' }).click();
            const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
            if (await maximizeInventoryButton.isVisible({ timeout: 10000 }).catch(() => false)) {
                await maximizeInventoryButton.click();
            }

            const curatedDataButton = page.getByRole('button', { name: 'Curated Data' }).first();
            await expect(curatedDataButton).toBeVisible({ timeout: 30000 });
            await curatedDataButton.click();

            const publishedAgricultureAsset = page.getByRole('button', { name: /PUBLISHED.*Agriculture/i }).first();
            await expect(publishedAgricultureAsset).toBeVisible({ timeout: 60000 });
            await publishedAgricultureAsset.locator('#btn_see_details').click();

            const openAssetDetailsButton = page.locator('.w-it').first();
            await expect(openAssetDetailsButton).toBeVisible({ timeout: 30000 });
            await openAssetDetailsButton.click();

            const statusButton = page
                .getByRole('button', { name: /^INACTIVE$|^ACTIVE$|^Activate$|^Deactivate$/i })
                .first();
            await expect(statusButton).toBeVisible({ timeout: 30000 });

            const statusTextBefore = (await statusButton.innerText().catch(() => '')).trim();
            if (/inactive|activate/i.test(statusTextBefore)) {
                await statusButton.click();

                const activeStateVisible = await page
                    .getByRole('button', { name: /^ACTIVE$|^Deactivate$/i })
                    .first()
                    .isVisible({ timeout: 30000 })
                    .catch(() => false);
                const statusMessageVisible = await page
                    .getByText(/Changes saved successfully!|Asset (de)?activated successfully!|Asset status updated successfully!/i)
                    .first()
                    .isVisible({ timeout: 30000 })
                    .catch(() => false);

                expect(activeStateVisible || statusMessageVisible).toBeTruthy();
            } else {
                await expect(
                    page.getByRole('button', { name: /^ACTIVE$|^Deactivate$/i }).first()
                ).toBeVisible({ timeout: 30000 });
            }
        } finally {
            const signInButtonVisible = await page
                .getByRole('button', { name: /Log In\/ Sign Up/i })
                .first()
                .isVisible({ timeout: 3000 })
                .catch(() => false);

            if (!signInButtonVisible) {
                await logoutCurrentUser().catch(() => { });
            }

            await loginWithCredentials(onboardingEmail, onboardingPassword, true);
            await clearChat();
        }
    })

    test("should not be able to update any field after curated data asset sold at least two or more", async () => {
        test.setTimeout(1200000);
        const firstBuyerEmail = process.env.USER_EMAIL?.trim() || 'automation@datafab.ai';
        const firstBuyerPassword = process.env.USER_PASSWORD?.trim() || 'User@123';
        const secondBuyerEmail = 'automation2@datafab.ai';
        const secondBuyerPassword = 'User@123';

        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Curated Data' }).click();
        const draftCuratedDataButton = page.getByRole('button', { name: /DRAFT.*Tourism Guide/i }).first();
        await expect(draftCuratedDataButton).toBeVisible({ timeout: 60000 });
        await draftCuratedDataButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').first();
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const reviewTab = page.getByRole('tab', { name: 'Review' }).first();
        if (await reviewTab.isVisible({ timeout: 10000 }).catch(() => false)) {
            await reviewTab.click();
        }

        const publishButton = page.getByRole('button', { name: 'Publish' }).first();
        await expect(publishButton).toBeVisible({ timeout: 60000 });
        await publishButton.click();

        await page.locator('#sabw_form-field-single-use').getByRole('textbox').first().fill('1');
        await page.locator('#sabw_form-field-five-uses').getByRole('textbox').first().fill('1');
        await page.locator('#sabw_form-field-annual').getByRole('textbox').first().fill('1');
        await page
            .locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]')
            .first()
            .fill('1');

        await page.getByRole('button', { name: 'Confirm' }).first().click();
        await expect(page.getByText('Asset published successfully!').first()).toBeVisible({ timeout: 120000 });

        await clearChat();
        await logoutCurrentUser();
        await loginWithCredentials(firstBuyerEmail, firstBuyerPassword);
        await clearChat();

        const firstBuyerChatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(firstBuyerChatInput).toBeVisible({ timeout: 30000 });
        await firstBuyerChatInput.click();
        await firstBuyerChatInput.fill('Open marketplace\n');

        await expect(
            page.getByLabel('Widget content').getByRole('paragraph').filter({ hasText: /^Marketplace$/ })
        ).toBeVisible({ timeout: 180000 });

        const firstMarketplaceMaximizeButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(firstMarketplaceMaximizeButton).toBeVisible({ timeout: 60000 });
        await firstMarketplaceMaximizeButton.click();

        const firstMarketplaceSearch = page.getByRole('textbox', { name: 'Search' }).first();
        await expect(firstMarketplaceSearch).toBeVisible({ timeout: 30000 });
        await firstMarketplaceSearch.fill('tourism');

        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await page.getByRole('button', { name: /unlimited.*1\.00 DAAC/i }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const firstCloseMarketplaceWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await firstCloseMarketplaceWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await firstCloseMarketplaceWidgetButton.click();
        }

        await logoutCurrentUser();
        await loginWithCredentials(secondBuyerEmail, secondBuyerPassword);
        await clearChat();

        const secondBuyerChatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(secondBuyerChatInput).toBeVisible({ timeout: 30000 });
        await secondBuyerChatInput.click();
        await secondBuyerChatInput.fill('Open marketplace\n');

        await expect(
            page.getByLabel('Widget content').getByRole('paragraph').filter({ hasText: /^Marketplace$/ })
        ).toBeVisible({ timeout: 180000 });

        const secondMarketplaceMaximizeButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(secondMarketplaceMaximizeButton).toBeVisible({ timeout: 60000 });
        await secondMarketplaceMaximizeButton.click();

        const secondMarketplaceSearch = page.getByRole('textbox', { name: 'Search' }).first();
        await expect(secondMarketplaceSearch).toBeVisible({ timeout: 30000 });
        await secondMarketplaceSearch.fill('tourism');

        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await page.getByRole('button', { name: /unlimited.*1\.00 DAAC/i }).first().click();
        await page.getByRole('button', { name: 'Purchase' }).first().click();
        await expect(page.getByText('Successfully Purchased!').first()).toBeVisible({ timeout: 120000 });

        const secondCloseMarketplaceWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await secondCloseMarketplaceWidgetButton.isVisible({ timeout: 10000 }).catch(() => false)) {
            await secondCloseMarketplaceWidgetButton.click();
        }

        await logoutCurrentUser();
        await loginWithCredentials(onboardingEmail, onboardingPassword, true);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Curated Data' }).click();
        const publishedCuratedDataButton = page.getByRole('button', { name: /PUBLISHED.*Tourism/i }).first();
        await expect(publishedCuratedDataButton).toBeVisible({ timeout: 60000 });
        await publishedCuratedDataButton.locator('#btn_see_details').click();

        const salesHeading = page.getByRole('heading', { name: /sales/i }).first();
        await expect(salesHeading).toBeVisible({ timeout: 30000 });

        const publishedAssetActionButton = page.getByRole('button').first();
        await expect(publishedAssetActionButton).toBeVisible({ timeout: 30000 });
        await publishedAssetActionButton.click();

        const closeInventoryWidgetAfterSale = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidgetAfterSale.isVisible({ timeout: 10000 }).catch(() => false)) {
            await closeInventoryWidgetAfterSale.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButtonAfterSale = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButtonAfterSale).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButtonAfterSale.click();

        const nameInput = page.getByRole('textbox', { name: 'Name Your Asset' }).first();
        const descriptionInput = page.getByRole('textbox', { name: 'Describe the asset in a' }).first();
        const tagsCombobox = page.getByRole('combobox').first();
        const saveButton = page.getByRole('button', { name: 'Save' }).first();

        await expect(nameInput).toBeVisible({ timeout: 30000 });
        await expect(nameInput).not.toBeEditable();
        await expect(descriptionInput).toBeVisible({ timeout: 30000 });
        await expect(descriptionInput).not.toBeEditable();
        await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
        await expect(tagsCombobox).not.toBeEditable();

        if (await saveButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await expect(saveButton).toBeDisabled();
        }
    })

    test("should not be able to create more than 10 assets in draft status", async () => {
        test.setTimeout(960000);
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        const sendButton = page.locator('#chat-input').getByRole('button').first();
        const namePrompt = page
            .locator('body')
            .getByText(/provide the name of your new widget|name of your new widget/i)
            .first();

        for (let i = 0; i < 10; i++) {
            await clearChat();

            const widget = new WidgetCreationProcess(page);
            await expect(chatInput).toBeVisible({ timeout: 30000 });
            await expect(chatInput).toBeEnabled({ timeout: 30000 });
            await chatInput.click();
            await chatInput.fill('I need to create a widget without a domain');
            await expect(sendButton).toBeVisible({ timeout: 30000 });
            await expect(sendButton).toBeEnabled({ timeout: 30000 });
            await sendButton.click();

            const outcome = await waitForWidgetStartOutcome(page);
            if (outcome === 'terminal') {
                await expectTerminalMessage(page);
                throw new Error('Widget creation was blocked before reaching the draft limit.');
            }

            await expect(namePrompt).toBeVisible({ timeout: 60000 });
            await widget.provideWidgetName();
            await widget.provideDescription();
            await widget.provideInstructions();
            await widget.provideSourceType();
            await widget.selectFirstWidgetOption();
            await widget.createWidget();
            await expect(page.getByText('Widget created successfully!')).toBeVisible({ timeout: 120000 });
        }

        await clearChat();

        const previousCount = await chatPage.getReceivedMessageCount();
        const limitReachedMessage = /Asset creation limit reached\./i;
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await expect(chatInput).toBeEnabled({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create a widget without a domain');
        await expect(sendButton).toBeVisible({ timeout: 30000 });
        await expect(sendButton).toBeEnabled({ timeout: 30000 });
        await sendButton.click();

        await chatPage.waitForNewReceivedMessage(previousCount, 180000);
        const lastResponse = await chatPage.getLastReceivedMessage();
        expect(lastResponse).toMatch(limitReachedMessage);
    })

    test("should be able to create an asset in draft status after deleting an existing asset", async () => {
        test.setTimeout(480000);
        await clearChat();
        await createDraftWidget();

        await deleteFirstAgenticWidgetDraft();

        await clearChat();
        await createDraftWidget();
    })

    test("should be able to publish a widget from studio (no other published assets)", async () => {
        test.setTimeout(480000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Agentic Widget' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).click();
        await page.getByRole('button').nth(1).click();
        await page.locator('#inventory_widget_canvas_1_close_btn').click();
        await page.getByRole('button', { name: 'Maximize widget' }).click();
        await page.locator('.lucide.lucide-eye').click();
        await page.getByRole('button', { name: 'Test' }).click();
        await page.getByRole('button', { name: 'I understand' }).click();
        await page.getByRole('textbox', { name: 'Enter your input query here...' }).fill('Test widget');
        await page.getByRole('button', { name: 'Test' }).click();
        await page.getByRole('button', { name: 'Close' }).click();
        await page.getByRole('button', { name: 'Publish' }).click();
        await page.getByRole('dialog').getByRole('textbox', { name: 'Prerequisites' }).click();
        await page.getByRole('dialog').getByRole('textbox', { name: 'Prerequisites' }).fill('No prerequisites');
        await page.locator('#int_agent_builder_single_use input[type="text"]').click();
        await page.locator('#int_agent_builder_single_use input[type="text"]').fill('1');
        await page.locator('#int_agent_builder_five_uses input[type="text"]').click();
        await page.locator('#int_agent_builder_five_uses input[type="text"]').fill('5');
        await page.locator('#int_agent_builder_annual input[type="text"]').click();
        await page.locator('#int_agent_builder_annual input[type="text"]').fill('49');
        await page.locator('[id="int_agent_builder_unlimited_(including_for_reselling)"] input[type="text"]').click();
        await page.locator('[id="int_agent_builder_unlimited_(including_for_reselling)"] input[type="text"]').fill('99');
        await page.getByRole('button', { name: 'Confirm' }).click();
        await expect(page.getByText('Successfully Published!')).toBeVisible({ timeout: 60000 });
        await expect(page.getByText('Agent published successfully!')).toBeVisible({ timeout: 60000 });

        await clearChat();
    })

    test("should be able to perform searches less than 10", async () => {
        await chatPage.refreshChat();

        const prompts = [
            'I need a Sri Lankan travel agent',
        ];

        for (const prompt of prompts) {
            const response = await sendSearchAndWaitForResponse(prompt);
            expect(response).not.toMatch(SEARCH_LIMIT_MESSAGE);
            await chatPage.refreshChat();
        }
    })

    test("should be able to publish agent", async () => {
        test.setTimeout(600000);
        await clearChat();
        await publishAgentFromStudio(0);
        await clearChat();
    })

    test("should be able to publish an agent (second asset)", async () => {
        test.setTimeout(720000);
        await depositWallet('25', 'Add 25 DAAC before publishing second agent');
        await expectWalletBalance('25.00');
        await clearChat();
        await publishAgentFromStudio(1, true);
        await clearChat();
    })

    test("should be able to publish dataset", async () => {
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Curated Data' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).click();
        await page.getByRole('button').first().click();
        await page.getByRole('region', { name: 'Widget 4073e19f-c3f9-4ce4-' }).getByLabel('Close widget').click();
        await page.getByRole('button', { name: 'Maximize widget' }).click();
        await page.locator('div:nth-child(5) > .flex > .lucide').click();
        await page.getByRole('button', { name: 'Publish' }).click();
        await page.locator('#sabw_form-field-single-use').getByRole('textbox').click();
        await page.locator('#sabw_form-field-single-use').getByRole('textbox').fill('1');
        await page.locator('#sabw_form-field-five-uses').getByRole('textbox').click();
        await page.locator('#sabw_form-field-five-uses').getByRole('textbox').fill('5');
        await page.locator('#sabw_form-field-annual').getByRole('textbox').click();
        await page.locator('#sabw_form-field-annual').getByRole('textbox').fill('49');
        await page.locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]').click();
        await page.locator('[id="sabw_form-field-unlimited-(including-for-reselling)"] input[type="text"]').fill('99');
        await page.getByRole('button', { name: 'Confirm' }).click();
        await expect(page.getByText('Asset published successfully!')).toBeVisible();
        await page.waitForTimeout(5000);
        await page.getByRole('button', { name: 'Unpublish' }).click();
        await expect(page.getByRole('heading', { name: 'Asset unpublished' })).toBeVisible();
    })

    test("should be able to publish media", async () => {
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Media', exact: true }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).click();
        await page.getByRole('button').first().click();
        await page.getByRole('region', { name: 'Widget 4d91eb32-99d6-4a18-' }).getByLabel('Close widget').click();
        await page.getByRole('button', { name: 'Maximize widget' }).click();
        await page.locator('.lucide.lucide-eye').click();
        await page.getByRole('button', { name: 'Publish' }).click();
        await page.locator('#media_creation_price_per_single_percent').getByRole('textbox').click();
        await page.locator('#media_creation_price_per_single_percent').getByRole('textbox').fill('5');
        await page.getByRole('button', { name: 'Confirm' }).click();
        await page.waitForTimeout(5000);
        await page.getByRole('button', { name: 'Unpublish' }).click();
        await expect(page.getByRole('heading', { name: 'Media unpublished' })).toBeVisible();
    })

    test("should be able to publish model", async () => {
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Models' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).click();
        await page.getByRole('button').nth(1).click();
        await page.getByRole('region', { name: 'Widget 5322527d-a5f5-4a5b-' }).getByLabel('Close widget').click();
        await page.getByRole('button', { name: 'Maximize widget' }).click();
        await page.locator('.lucide.lucide-eye').click();
        await page.getByRole('button', { name: 'Publish' }).click();
        await page.getByRole('dialog').getByRole('textbox').click();
        await page.getByRole('dialog').getByRole('textbox').fill('9');
        await page.getByRole('button', { name: 'Confirm' }).click();
        await expect(page.getByText('Model published successfully!')).toBeVisible();
        await page.waitForTimeout(5000);
        await page.getByRole('button', { name: 'Unpublish' }).click();
        await expect(page.getByRole('heading', { name: 'Model unpublished' })).toBeVisible();
    })

    test("should be able to manually increase wallet balance to 20 DAAC", async () => {
        const cookies = await page.context().cookies();
        const token = cookies.find((cookie) => cookie.name === 'access_token')?.value;
        if (!token) {
            throw new Error('access_token not found in cookies.');
        }

        const depositUrl = new URL(
            `https://promptify-exchange-be-dev.promptyf.cloud/api/v1/wallet/${onboardingWalletAddress}/deposit`
        );
        depositUrl.searchParams.set('amount', '10');
        depositUrl.searchParams.set('description', 'Add 10 DAAC manually for testing');
        depositUrl.searchParams.set('perform_blockchain_transfer', 'false');

        const response = await page.request.post(depositUrl.toString(), {
            headers: {
                accept: 'application/json',
                Authorization: `Bearer ${token}`
            }
        });
        expect(response.ok()).toBeTruthy();

        await page.getByRole("button", { name: "Toggle Wallet" }).click();
        const daacHeading = page.getByRole("heading", { name: "DAAC" });
        await daacHeading.click();
        await expect(daacHeading).toHaveText(/20\.00 DAAC/, { timeout: 20000 });
    })

    test("should be able to update all asset fields before clicking create", async () => {
        test.setTimeout(420000);
        await clearChat();

        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('I need to create a new agent without domain\n');
        await chatInput.click();
        await chatInput.fill('Europe Tourism Agent\n');
        await chatInput.click();
        await chatInput.fill('Assisting travel around the europe\n');

        await page.getByRole('button', { name: 'Agentic Flow Where the agent' }).click();
        await chatInput.click();
        await chatInput.fill('Provide any information related to travelling in europe\n');
        await chatInput.click();
        await chatInput.fill('booking.com, airbnb.com, blogs, youtube, etc.\n');

        await page.getByRole('button', { name: 'Open Studio lean in, provide' }).click();

        const assetNameInput = page.getByRole('textbox', { name: 'Name Your Asset' });
        await expect(assetNameInput).toBeVisible({ timeout: 60000 });
        await assetNameInput.click();
        await assetNameInput.fill('Europe Tourism Agent 2');

        const assetDescInput = page.getByRole('textbox', { name: 'Describe the asset in a' });
        await assetDescInput.click();
        await assetDescInput.fill('Assisting travel around the europian countries');

        const sourceTypeInput = page.getByRole('textbox', { name: 'Specify the type of sources' });
        await sourceTypeInput.click();
        await sourceTypeInput.fill('booking.com, airbnb.com, blog websites');

        const actionInput = page.getByRole('textbox', { name: 'Articulate the actions your' });
        await actionInput.click();
        await actionInput.fill('Provide any information related to travelling in europe\nProvide available places for stay');

        const domainInput = page.getByRole('textbox', { name: 'Select domains' });
        await domainInput.click();
        await domainInput.fill('');
        await page.getByRole('button', { name: 'default' }).click();
        await page.getByText('PurposeMarketing').click();
        await page.getByRole('button', { name: 'Save' }).click();

        const tagInput = page.getByRole('combobox', { name: 'Tags/categories' });
        await tagInput.click();
        await tagInput.fill('Travel');
        await page.getByRole('option', { name: 'Travel', exact: true }).click();

        const prereqInput = page.getByRole('textbox', { name: 'Prerequisites' });
        await prereqInput.click();
        await prereqInput.fill('No Prerequisites');

        const imagePath = path.join(process.cwd(), 'scripts', 'test-image.png');
        await page.getByRole('button', { name: 'Choose File' }).click();
        await page.getByRole('button', { name: 'Choose File' }).setInputFiles(imagePath);

        await page.getByRole('button', { name: 'Create', exact: true }).click();
        await expect(page.getByRole('heading', { name: 'Agent created successfully!' })).toBeVisible({ timeout: 180000 });
    })

    test("should not be able to update domain, instruction, sources or pricing after it is created", async () => {
        test.setTimeout(360000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        await expect(page.getByRole('button', { name: 'Domain Driven Agent' })).toBeVisible({ timeout: 30000 });
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();

        const draftAssetButton = page.getByRole('button', { name: 'DRAFT ACTIVE default Europe' }).first();
        await expect(draftAssetButton).toBeVisible({ timeout: 30000 });
        await draftAssetButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').nth(1);
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(2000);

        const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
        if (await closeInventoryWidget.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const instructionsField = page.getByRole('textbox', { name: 'Articulate the actions your' }).first();
        await expect(instructionsField).toBeVisible({ timeout: 30000 });
        await expect(instructionsField).not.toBeEditable();

        const domainField = page.getByRole('textbox', { name: 'Select domains' }).first();
        await expect(domainField).toBeVisible({ timeout: 30000 });
        await expect(domainField).not.toBeEditable();

        const sourcesField = page.getByRole('textbox', { name: 'Specify the type of sources' }).first();
        await expect(sourcesField).toBeVisible({ timeout: 30000 });
        await expect(sourcesField).not.toBeEditable();

        await expect(page.locator('#int_agent_builder_single_use')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('#int_agent_builder_five_uses')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('#int_agent_builder_annual')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('[id="int_agent_builder_unlimited_(including_for_reselling)"]')).toHaveCount(0, {
            timeout: 5000
        });

        const closeButton = page.getByRole('button', { name: 'Close', exact: true }).first();
        if (await closeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeButton.click();
        }
    })

    test("should not be able to update domain, instructions, sources or pricing after it is published", async () => {
        test.setTimeout(360000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeInventoryButton.click();
        }

        await expect(page.getByRole('button', { name: 'Domain Driven Agent' })).toBeVisible({ timeout: 30000 });
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();

        const inventoryCategoryButton = page.locator('.flex.flex-col.items-center.justify-center.rounded-\[2px\]').first();
        if (await inventoryCategoryButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await inventoryCategoryButton.click();
        }

        const publishedAssetButton = page.getByRole('button', { name: 'PUBLISHED ACTIVE Automation' }).first();
        await expect(publishedAssetButton).toBeVisible({ timeout: 30000 });
        await publishedAssetButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').nth(1);
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page
            .locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]')
            .first();
        if (await closeInventoryWidget.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const domainField = page.getByRole('textbox', { name: 'Select domains' }).first();
        await expect(domainField).toBeVisible({ timeout: 30000 });
        await expect(domainField).not.toBeEditable();

        const instructionsField = page.getByRole('textbox', { name: 'Articulate the actions your' }).first();
        await expect(instructionsField).toBeVisible({ timeout: 30000 });
        await expect(instructionsField).not.toBeEditable();

        const sourcesField = page.getByRole('textbox', { name: 'Specify the type of sources' }).first();
        await expect(sourcesField).toBeVisible({ timeout: 30000 });
        await expect(sourcesField).not.toBeEditable();

        await expect(page.locator('#int_agent_builder_single_use')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('#int_agent_builder_five_uses')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('#int_agent_builder_annual')).toHaveCount(0, { timeout: 5000 });
        await expect(page.locator('[id="int_agent_builder_unlimited_(including_for_reselling)"]')).toHaveCount(0, {
            timeout: 5000
        });

        const closeButton = page.getByRole('button', { name: 'Close', exact: true }).first();
        if (await closeButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeButton.click();
        }
    })

    test("should be able to update dda name, description, thumbnail, tags and prerequisites before it is published", async () => {
        test.setTimeout(360000);
        await clearChat();

        await page.getByRole('button', { name: 'Open inventory' }).click();
        const maximizeInventoryButton2 = page.locator('.lucide.lucide-maximize2').first();
        if (await maximizeInventoryButton2.isVisible({ timeout: 5000 }).catch(() => false)) {
            await maximizeInventoryButton2.click();
        }

        const domainButton = page.getByRole('button', { name: 'Domain Driven Agent' }).first();
        await expect(domainButton).toBeVisible({ timeout: 30000 });
        await domainButton.click();

        const draftAssetButton = page.getByRole('button', { name: 'DRAFT ACTIVE default Europe' }).first();
        await expect(draftAssetButton).toBeVisible({ timeout: 30000 });
        await draftAssetButton.locator('#btn_see_details').click();

        const inventoryActionButton = page.getByRole('button').nth(1);
        await expect(inventoryActionButton).toBeVisible({ timeout: 30000 });
        await inventoryActionButton.click();
        await page.waitForTimeout(3000);

        const closeInventoryWidget = page.locator('button[aria-label="Close widget"][id^="inventory_widget_canvas_"]').first();
        if (await closeInventoryWidget.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeInventoryWidget.click({ force: true }).catch(() => {});
        }

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 60000 });
        await maximizeWidgetButton.click();

        const nameInput = page.getByRole('textbox', { name: 'Name Your Asset' }).first();
        const descriptionInput = page.getByRole('textbox', { name: 'Describe the asset in a' }).first();
        const thumbnailIcon = page.locator('.lucide.lucide-code').first();
        const prerequisitesInput = page.getByRole('textbox', { name: 'Prerequisites' }).first();
        const tagsCombobox = page.getByRole('combobox', { name: 'Tags/categories' }).first();

        await expect(nameInput).toBeEditable({ timeout: 30000 });
        await nameInput.fill('Europe Tourism Agent 3');

        await expect(descriptionInput).toBeEditable({ timeout: 30000 });
        await descriptionInput.fill('Assisting travel around the europian countries test');

        await expect(thumbnailIcon).toBeVisible({ timeout: 30000 });
        await thumbnailIcon.click();

        await expect(prerequisitesInput).toBeEditable({ timeout: 30000 });
        await prerequisitesInput.fill('No Prerequisites test');

        await page.locator('.absolute.right-0\\.5').click();

        await expect(tagsCombobox).toBeVisible({ timeout: 30000 });
        await tagsCombobox.click();
        await tagsCombobox.fill('Tourism');
        await page.getByRole('option', { name: 'Tourism' }).click();
        await page.getByRole('button', { name: 'Save' }).click();

        await expect(page.getByRole('heading', { name: 'Changes saved successfully!' })).toBeVisible({ timeout: 120000 });

        const closeWidgetButton = page.getByRole('button', { name: 'Close widget' }).first();
        if (await closeWidgetButton.isVisible({ timeout: 5000 }).catch(() => false)) {
            await closeWidgetButton.click();
        }
    })

    test("should be able to publish a widget (second asset)", async () => {
        test.setTimeout(720000);
        await depositWallet('25', 'Add 25 DAAC before publishing second widget');
        await expectWalletBalance('35.00');
        await clearChat();
        await publishWidgetFromStudio(1, true);
        await clearChat();
    })

    test("should be able to publish a dataset (second asset)", async () => {
        test.setTimeout(720000);
        await depositWallet('25', 'Add 25 DAAC before publishing second dataset');
        await expectWalletBalance('35.00');
        await clearChat();
        await publishDatasetFromStudio(1, true);
        await clearChat();
    })

    test("should be able to publish a media (second asset)", async () => {
        test.setTimeout(720000);
        await depositWallet('25', 'Add 25 DAAC before publishing second media');
        await expectWalletBalance('35.00');
        await clearChat();
        await publishMediaFromStudio(1, true);
        await clearChat();
    })

    test("should be able to publish a model (second asset)", async () => {
        test.setTimeout(720000);
        await depositWallet('25', 'Add 25 DAAC before publishing second model');
        await expectWalletBalance('35.00');
        await clearChat();
        await publishModelFromStudio(1, true);
        await clearChat();
    })

    test("should be able to manually increase wallet balance to 100 DAAC", async () => {
        const cookies = await page.context().cookies();
        const token = cookies.find((cookie) => cookie.name === 'access_token')?.value;
        if (!token) {
            throw new Error('access_token not found in cookies.');
        }

        const depositUrl = new URL(
            `https://promptify-exchange-be-dev.promptyf.cloud/api/v1/wallet/${onboardingWalletAddress}/deposit`
        );
        depositUrl.searchParams.set('amount', '80');
        depositUrl.searchParams.set('description', 'Add 80 DAAC manually for testing');
        depositUrl.searchParams.set('perform_blockchain_transfer', 'false');

        const response = await page.request.post(depositUrl.toString(), {
            headers: {
                accept: 'application/json',
                Authorization: `Bearer ${token}`
            }
        });
        expect(response.ok()).toBeTruthy();

        await page.getByRole("button", { name: "Toggle Wallet" }).click();
        const daacHeading = page.getByRole("heading", { name: "DAAC" });
        await daacHeading.click();
        await expect(daacHeading).toHaveText(/100\.00 DAAC/, { timeout: 20000 });
    })

    // 79 Can create agent with instructions and sources referring to specific source types, and placeholders are created for all of them
    test("can create agent with instructions and sources referring to specific source types, and placeholders are created for all of them in the extended flow", async () => {
        await openCdrAgentFileUploadStep();
        await uploadAllCdrPlaceholderFiles();

        const queryInput = page.getByRole('textbox', { name: /Enter your input query here/i }).first();
        await expect(queryInput).toBeVisible({ timeout: 10000 });
    })

    // 80 Cannot test created agent without uploading files to replace placeholders
    test("cannot test created agent without uploading files to replace placeholders in the extended flow", async () => {
        await openCdrAgentFileUploadStep();

        const queryInput = page.getByRole('textbox', { name: /Enter your input query here/i }).first();
        await expect(queryInput).toHaveCount(0, { timeout: 5000 });

        const uploadAssetButton = page.getByRole('button', { name: /^Thumbnail$/i }).first();
        await expect(uploadAssetButton).toBeVisible({ timeout: 10000 });

        const nextBtn = page.getByRole('button', { name: /^Next$/i }).first();
        if (await nextBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
            await expect(nextBtn).toBeDisabled();
        }
    })

    // 81 Cannot publish without successfully testing the agent
    test("cannot publish without successfully testing the agent in the extended flow", async () => {
        await createCdrAgentWithoutDomain();

        const publishButton = page.getByRole('button', { name: /Publish/i }).first();
        await expect(publishButton).toBeVisible({ timeout: 10000 });
        await expect(publishButton).toBeDisabled();
    })

    // 82 Different onboarded user can find the asset in marketplace where searching using text similar (not identical) to the description of the published asset
    test("different onboarded user can find the published asset in marketplace using similar description text in the extended flow", async () => {
        await clearChat();
        await chatPage.refreshChat();
        await chatPage.waitForChatReady();
        await openMarketplaceAssetForPurchase();
    })

    // 83 User can purchase the asset and verify inventory/pricing details
    test("different onboarded user can purchase the asset and see inventory, balance and transaction details in the extended flow", async () => {
        await purchaseMarketplaceAsset(ANNUAL_PLAN);
        await openInventoryWidgetForPurchasedAsset();
    })

    // 84 User with KF but no sources cannot activate the asset
    test("user with KF but no sources cannot activate the asset without uploading files to replace placeholders in the extended flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 85 User with MKF but no sources cannot activate the asset
    test("user with MKF but no sources cannot activate the asset without uploading files to replace placeholders in the extended flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 86 User with KF and relevant sources can activate the asset with no need for manual action
    test("user with KF and relevant sources can activate the asset with no need for manual action in the extended flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 87 User with MKF and relevant sources can activate the asset with no need for manual action
    test("user with MKF and relevant sources can activate the asset with no need for manual action in the extended flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 89 Can create relevant sources in KF
    test("can create relevant sources in KF in the extended flow", async () => {
        await page.locator('#btn-refresh-chat').click();
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('Show me knowledge fabric');
        await page.locator('#chat-input').getByRole('button').click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 120000 });
        await maximizeWidgetButton.click();

        const kfWidget = page.getByRole('region').filter({
            has: page.getByText('Knowledge Fabric').first()
        }).first();

        await kfWidget.getByRole('tab', { name: 'Settings' }).click();
        const servicesCard = kfWidget.getByText('Set up connectors and ingest metadata from diverse sources.').first();
        await expect(servicesCard).toBeVisible({ timeout: 30000 });
        await servicesCard.click();

        const mcpIntegrationsCard = kfWidget.getByText('Integrate with MCP services to ingest metadata from the UI.').first();
        await expect(mcpIntegrationsCard).toBeVisible({ timeout: 30000 });
        await mcpIntegrationsCard.click();

        const postgresButton = kfWidget.getByRole('button', { name: /postgres/i }).first();
        await expect(postgresButton).toBeVisible({ timeout: 30000 });
        await postgresButton.click();

        const mcpName = kfWidget.getByRole('textbox', { name: 'MCP Name' });
        await expect(mcpName).toBeVisible({ timeout: 30000 });
        await mcpName.click();
        await mcpName.fill('CDR postgreSQL');
        await expect(mcpName).toHaveValue('CDR postgreSQL');

        const description = kfWidget.getByRole('textbox', { name: 'Description' });
        await description.click();
        await description.fill('CDR data from postgreSQL:');

        const nextButton = kfWidget.getByRole('button', { name: 'Next' });
        await expect(nextButton).toBeEnabled({ timeout: 10000 });
        await nextButton.click();

        const userField = kfWidget.getByRole('textbox', { name: 'Enter User' });
        await expect(userField).toBeVisible({ timeout: 30000 });
        await userField.fill('root');
        await kfWidget.getByRole('textbox', { name: 'Enter Password' }).fill('1234');
        await kfWidget.getByRole('textbox', { name: 'Enter Host' }).fill('100.12.13.14');
        await kfWidget.getByPlaceholder('Enter Port').fill('5506');
        const databaseField = kfWidget.getByRole('textbox', { name: 'Enter Database' });
        await databaseField.fill('cdr_data');
        await databaseField.press('Tab');

        const submitButton = kfWidget.getByRole('button', { name: 'Submit' });
        await expect(submitButton).toBeVisible({ timeout: 30000 });
        await submitButton.focus();
        await submitButton.press('Enter');
        await expect(page.getByText('MCP service created')).toBeVisible({ timeout: 120000 });
    })

    // 90 After creating relevant sources in KF Can test created agent by picking the sources from the list
    test("after creating relevant sources in KF can test created agent by picking the sources from the list in the extended flow", async () => {
        await page.locator('#btn-refresh-chat').click();
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).first().click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).first().click();
        await page.getByRole('button', { name: 'Test Connection' }).first().click();
        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 91 Can create relevant sources in MKF (mapped to existing KF flow)
    test("can create relevant sources in MKF in the extended flow", async () => {
        await page.locator('#btn-refresh-chat').click();
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('Show me knowledge fabric');
        await page.locator('#chat-input').getByRole('button').click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 120000 });
        await maximizeWidgetButton.click();

        const kfWidget = page.getByRole('region').filter({
            has: page.getByText('Knowledge Fabric').first()
        }).first();

        await kfWidget.getByRole('tab', { name: 'Settings' }).click();
        const servicesCard = kfWidget.getByText('Set up connectors and ingest metadata from diverse sources.').first();
        await expect(servicesCard).toBeVisible({ timeout: 30000 });
        await servicesCard.click();

        const mcpIntegrationsCard = kfWidget.getByText('Integrate with MCP services to ingest metadata from the UI.').first();
        await expect(mcpIntegrationsCard).toBeVisible({ timeout: 30000 });
        await mcpIntegrationsCard.click();

        const postgresButton = kfWidget.getByRole('button', { name: /postgres/i }).first();
        await expect(postgresButton).toBeVisible({ timeout: 30000 });
        await postgresButton.click();

        const uniqueMcpName = `CDR postgreSQL ${Date.now()}`;
        const mcpName = kfWidget.getByRole('textbox', { name: 'MCP Name' });
        await expect(mcpName).toBeVisible({ timeout: 30000 });
        await mcpName.click();
        await mcpName.fill(uniqueMcpName);
        await expect(mcpName).toHaveValue(uniqueMcpName);

        const description = kfWidget.getByRole('textbox', { name: 'Description' });
        await description.click();
        await description.fill('CDR data from postgreSQL:');

        const nextButton = kfWidget.getByRole('button', { name: 'Next' });
        await expect(nextButton).toBeEnabled({ timeout: 10000 });
        await nextButton.click();

        const userField = kfWidget.getByRole('textbox', { name: 'Enter User' });
        await expect(userField).toBeVisible({ timeout: 30000 });
        await userField.fill('root');
        await kfWidget.getByRole('textbox', { name: 'Enter Password' }).fill('1234');
        await kfWidget.getByRole('textbox', { name: 'Enter Host' }).fill('100.12.13.14');
        await kfWidget.getByPlaceholder('Enter Port').fill('5506');
        const databaseField = kfWidget.getByRole('textbox', { name: 'Enter Database' });
        await databaseField.fill('cdr_data');
        await databaseField.press('Tab');

        const submitButton = kfWidget.getByRole('button', { name: 'Submit' });
        await expect(submitButton).toBeVisible({ timeout: 30000 });
        await submitButton.focus();
        await submitButton.press('Enter');
        await expect(page.getByText('MCP service created')).toBeVisible({ timeout: 120000 });
    })

    // 92 After creating relevant sources in MKF can test created agent by picking the sources from the list
    test("after creating relevant sources in MKF can test created agent by picking the sources from the list in the extended flow", async () => {
        await page.locator('#btn-refresh-chat').click();
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).first().click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).first().click();
        await page.getByRole('button', { name: 'Test Connection' }).first().click();
        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 93 Can create agent with instructions and sources referring to specific source types, and placeholders are created for all of them
    test("can create agent with instructions and sources referring to specific source types, and placeholders are created for all of them", async () => {
        await openCdrAgentFileUploadStep();
        await uploadAllCdrPlaceholderFiles();

        const queryInput = page.getByRole('textbox', { name: /Enter your input query here/i }).first();
        await expect(queryInput).toBeVisible({ timeout: 10000 });
    })

    // 94 Cannot test created agent without uploading files to replace placeholders
    test("cannot test created agent without uploading files to replace placeholders", async () => {
        await openCdrAgentFileUploadStep();

        const queryInput = page.getByRole('textbox', { name: /Enter your input query here/i }).first();
        await expect(queryInput).toHaveCount(0, { timeout: 5000 });

        const uploadAssetButton = page.getByRole('button', { name: /^Thumbnail$/i }).first();
        await expect(uploadAssetButton).toBeVisible({ timeout: 10000 });

        const nextBtn = page.getByRole('button', { name: /^Next$/i }).first();
        if (await nextBtn.isVisible({ timeout: 3000 }).catch(() => false)) {
            await expect(nextBtn).toBeDisabled();
        }
    })

    // 95 Cannot publish without successfully testing the agent
    test("cannot publish without successfully testing the agent", async () => {
        await createCdrAgentWithoutDomain();

        const publishButton = page.getByRole('button', { name: /Publish/i }).first();
        await expect(publishButton).toBeVisible({ timeout: 10000 });
        await expect(publishButton).toBeDisabled();
    })

    // 96 Different onboarded user can find the published asset in marketplace using similar description text
    test("different onboarded user can find the published asset in marketplace using similar description text", async () => {
        await clearChat();
        await chatPage.refreshChat();
        await chatPage.waitForChatReady();
        await openMarketplaceAssetForPurchase();
    })

    // 97 Different onboarded user can purchase the asset and see inventory, balance and transaction details
    test("different onboarded user can purchase the asset and see inventory, balance and transaction details", async () => {
        await purchaseMarketplaceAsset(ANNUAL_PLAN);
        await openInventoryWidgetForPurchasedAsset();
    })

    // 98 User with KF but no sources cannot activate the asset without uploading files to replace placeholders
    test("user with KF but no sources cannot activate the asset without uploading files to replace placeholders", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 99 User with MKF but no sources cannot activate the asset without uploading files to replace placeholders
    test("user with MKF but no sources cannot activate the asset without uploading files to replace placeholders", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 100 User with KF and relevant sources can activate the asset with no need for manual action
    test("user with KF and relevant sources can activate the asset with no need for manual action", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 101 User with MKF and relevant sources can activate the asset with no need for manual action
    test("user with MKF and relevant sources can activate the asset with no need for manual action", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 102 Can create relevant sources in KF
    test("can create relevant sources in KF", async () => {
        await page.locator('#btn-refresh-chat').click();
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('Show me knowledge fabric');
        await page.locator('#chat-input').getByRole('button').click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 120000 });
        await maximizeWidgetButton.click();

        const kfWidget = page.getByRole('region').filter({
            has: page.getByText('Knowledge Fabric').first()
        }).first();

        await kfWidget.getByRole('tab', { name: 'Settings' }).click();
        const servicesCard = kfWidget.getByText('Set up connectors and ingest metadata from diverse sources.').first();
        await expect(servicesCard).toBeVisible({ timeout: 30000 });
        await servicesCard.click();

        const mcpIntegrationsCard = kfWidget.getByText('Integrate with MCP services to ingest metadata from the UI.').first();
        await expect(mcpIntegrationsCard).toBeVisible({ timeout: 30000 });
        await mcpIntegrationsCard.click();

        const postgresButton = kfWidget.getByRole('button', { name: /postgres/i }).first();
        await expect(postgresButton).toBeVisible({ timeout: 30000 });
        await postgresButton.click();

        const uniqueMcpName = `CDR postgreSQL ${Date.now()}`;
        const mcpName = kfWidget.getByRole('textbox', { name: 'MCP Name' });
        await expect(mcpName).toBeVisible({ timeout: 30000 });
        await mcpName.click();
        await mcpName.fill(uniqueMcpName);
        await expect(mcpName).toHaveValue(uniqueMcpName);

        const description = kfWidget.getByRole('textbox', { name: 'Description' });
        await description.click();
        await description.fill('CDR data from postgreSQL:');

        const nextButton = kfWidget.getByRole('button', { name: 'Next' });
        await expect(nextButton).toBeEnabled({ timeout: 10000 });
        await nextButton.click();

        const userField = kfWidget.getByRole('textbox', { name: 'Enter User' });
        await expect(userField).toBeVisible({ timeout: 30000 });
        await userField.fill('root');
        await kfWidget.getByRole('textbox', { name: 'Enter Password' }).fill('1234');
        await kfWidget.getByRole('textbox', { name: 'Enter Host' }).fill('100.12.13.14');
        await kfWidget.getByPlaceholder('Enter Port').fill('5506');
        const databaseField = kfWidget.getByRole('textbox', { name: 'Enter Database' });
        await databaseField.fill('cdr_data');
        await databaseField.press('Tab');

        const submitButton = kfWidget.getByRole('button', { name: 'Submit' });
        await expect(submitButton).toBeVisible({ timeout: 30000 });
        await submitButton.focus();
        await submitButton.press('Enter');
        await expect(page.getByText('MCP service created')).toBeVisible({ timeout: 120000 });
    })

    // 103 After creating relevant sources in KF can test created agent by picking the sources from the list
    test("after creating relevant sources in KF can test created agent by picking the sources from the list", async () => {
        await page.locator('#btn-refresh-chat').click();
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).first().click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).first().click();
        await page.getByRole('button', { name: 'Test Connection' }).first().click();
        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 104 Can create relevant sources in MKF
    test("can create relevant sources in MKF", async () => {
        await page.locator('#btn-refresh-chat').click();
        const chatInput = page.getByRole('textbox', { name: 'Ask anything...' }).first();
        await expect(chatInput).toBeVisible({ timeout: 30000 });
        await chatInput.click();
        await chatInput.fill('Show me knowledge fabric');
        await page.locator('#chat-input').getByRole('button').click();

        const maximizeWidgetButton = page.getByRole('button', { name: 'Maximize widget' }).first();
        await expect(maximizeWidgetButton).toBeVisible({ timeout: 120000 });
        await maximizeWidgetButton.click();

        const kfWidget = page.getByRole('region').filter({
            has: page.getByText('Knowledge Fabric').first()
        }).first();

        await kfWidget.getByRole('tab', { name: 'Settings' }).click();
        const servicesCard = kfWidget.getByText('Set up connectors and ingest metadata from diverse sources.').first();
        await expect(servicesCard).toBeVisible({ timeout: 30000 });
        await servicesCard.click();

        const mcpIntegrationsCard = kfWidget.getByText('Integrate with MCP services to ingest metadata from the UI.').first();
        await expect(mcpIntegrationsCard).toBeVisible({ timeout: 30000 });
        await mcpIntegrationsCard.click();

        const postgresButton = kfWidget.getByRole('button', { name: /postgres/i }).first();
        await expect(postgresButton).toBeVisible({ timeout: 30000 });
        await postgresButton.click();

        const uniqueMcpName = `CDR postgreSQL ${Date.now()}`;
        const mcpName = kfWidget.getByRole('textbox', { name: 'MCP Name' });
        await expect(mcpName).toBeVisible({ timeout: 30000 });
        await mcpName.click();
        await mcpName.fill(uniqueMcpName);
        await expect(mcpName).toHaveValue(uniqueMcpName);

        const description = kfWidget.getByRole('textbox', { name: 'Description' });
        await description.click();
        await description.fill('CDR data from postgreSQL:');

        const nextButton = kfWidget.getByRole('button', { name: 'Next' });
        await expect(nextButton).toBeEnabled({ timeout: 10000 });
        await nextButton.click();

        const userField = kfWidget.getByRole('textbox', { name: 'Enter User' });
        await expect(userField).toBeVisible({ timeout: 30000 });
        await userField.fill('root');
        await kfWidget.getByRole('textbox', { name: 'Enter Password' }).fill('1234');
        await kfWidget.getByRole('textbox', { name: 'Enter Host' }).fill('100.12.13.14');
        await kfWidget.getByPlaceholder('Enter Port').fill('5506');
        const databaseField = kfWidget.getByRole('textbox', { name: 'Enter Database' });
        await databaseField.fill('cdr_data');
        await databaseField.press('Tab');

        const submitButton = kfWidget.getByRole('button', { name: 'Submit' });
        await expect(submitButton).toBeVisible({ timeout: 30000 });
        await submitButton.focus();
        await submitButton.press('Enter');
        await expect(page.getByText('MCP service created')).toBeVisible({ timeout: 120000 });
    })

    // 105 After creating relevant sources in MKF can test created agent by picking the sources from the list
    test("after creating relevant sources in MKF can test created agent by picking the sources from the list", async () => {
        await page.locator('#btn-refresh-chat').click();
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.getByRole('button', { name: 'Domain Driven Agent' }).click();
        await page.getByRole('button', { name: 'See details...', exact: true }).first().click();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).first().click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).first().click();
        await page.getByRole('button', { name: 'Test Connection' }).first().click();
        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 106-113 Synced general-user naming for the latest end-state cases
    // 106 Can create agent with instructions and sources, placeholders are created for all source types, and sources are attached
    test("can create agent with instructions and sources, placeholders are created for all source types, and sources are attached in the final flow", async () => {
        await openCdrAgentFileUploadStep();
        await uploadAllCdrPlaceholderFiles();

        const queryInput = page.getByRole('textbox', { name: /Enter your input query here/i }).first();
        await expect(queryInput).toBeVisible({ timeout: 10000 });
    })

    // 107 Cannot publish without successfully testing the agent
    test("cannot publish without successfully testing the agent in the final flow", async () => {
        await createCdrAgentWithoutDomain();

        const publishButton = page.getByRole('button', { name: /Publish/i }).first();
        await expect(publishButton).toBeVisible({ timeout: 10000 });
        await expect(publishButton).toBeDisabled();
    })

    // 108 Different onboarded user can find the asset in marketplace using similar description text
    test("different onboarded user can find the asset in marketplace using similar description text in the final flow", async () => {
        await clearChat();
        await chatPage.refreshChat();
        await chatPage.waitForChatReady();
        await openMarketplaceAssetForPurchase();
    })

    // 109 User can purchase the asset and see inventory with correct pricing details
    test("user can purchase the asset and see inventory with correct pricing details", async () => {
        await purchaseMarketplaceAsset(ANNUAL_PLAN);
        await openInventoryWidgetForPurchasedAsset();
    })

    // 110 User with KF but no sources cannot activate the asset without replacing placeholders
    test("user with KF but no sources cannot activate the asset without replacing placeholders", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 111 User with MKF but no sources cannot activate the asset without replacing placeholders
    test("user with MKF but no sources cannot activate the asset without replacing placeholders", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const inactiveStatus = page.getByRole('button', { name: 'INACTIVE' }).nth(1);
        await expect(inactiveStatus).toBeVisible({ timeout: 30000 });

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });
        await detailsDialog.getByRole('button').first().click();
        await detailsDialog.getByRole('button', { name: 'close' }).click();

        await page.locator('#inventory_widget_refresh_button').click();
        await expect(page.getByRole('button', { name: 'INACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 112 User with KF and relevant sources can activate the asset with no need for manual action
    test("user with KF and relevant sources can activate the asset with no need for manual action in the final flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    // 113 User with MKF and relevant sources can activate the asset with no need for manual action
    test("user with MKF and relevant sources can activate the asset with no need for manual action in the final flow", async () => {
        await openPurchasedAssetDetailsFromInventory();

        const detailsDialog = page.getByRole('dialog').first();
        await expect(detailsDialog).toBeVisible({ timeout: 30000 });

        await detailsDialog.getByRole('button', { name: 'MCP_INTEGRATION:CDRPostgreSQL' }).click();
        await detailsDialog.getByRole('button', { name: 'Existing MCPs Connect' }).click();
        await page.locator('div').filter({ hasText: /^CDR_postgreSQL$/ }).nth(1).click();
        await page.getByRole('checkbox', { name: 'CDR_postgreSQL' }).click();
        await page.getByRole('button', { name: 'Test Connection' }).click();

        await expect(page.getByText('MCP connected successfully')).toBeVisible({ timeout: 120000 });
        await detailsDialog.getByRole('button', { name: 'close' }).click();
        await expect(page.getByRole('button', { name: 'ACTIVE' }).nth(1)).toBeVisible({ timeout: 30000 });
    })

    test.afterAll(async () => {
        await context.close();
    });
})
