import { test, expect, Page, BrowserContext } from "@playwright/test";
import { RegistrationPage } from "../../pages/RegistrationPage";
import { waitForActivationCode } from "../../utils/ActivationCodeUtils";
import { ChatPage } from "../../pages/ChatPage";
import { WidgetCreationProcess } from "../../pages/widgetCreationProcess";
import {MediaCreationProcess} from "../../pages/mediaCreationProcess";
import {ModelCreationProcess} from "../../pages/modelCreationProcess";
import {DatasetCreationProcess} from "../../pages/datasetCreationProcess";
// @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;

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 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 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.');
}

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 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 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 / B10 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.b10+${Date.now()}@datafab.ai`;
        onboardingPassword = process.env.USER_PASSWORD?.trim() || "User@123";
        onboardingFullName = "Automation B Ten 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(() => {});
        }
    })

    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();
    })

    test("should not be able to update an asset that doesn't created by the current user", async () => {
        test.setTimeout(300000);
        await clearChat();
        await purchaseDdaFromMarketplace();

        await clearChat();
        await page.getByRole('button', { name: 'Open inventory' }).click();
        await page.locator('.lucide.lucide-maximize2').click();
        await page.getByRole('textbox', { name: 'Search' }).click();
        await page.getByRole('textbox', { name: 'Search' }).fill('HrAgent');
        await page.locator('.absolute.right-3').click();

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

    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("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 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 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',
            'I need a Financial Advisor',
            'I need a nutrition agent for daily use',
            'I need a weather agent',
            'I need a loan processing 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 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 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();
    })

    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();
    })

    test.afterAll(async () => {
        await context.close();
    });
})
