from __future__ import annotations

import pytest
from playwright.sync_api import Page

from e2e.pages.product_solution_admin_page import ProductSolutionAdminPage
from e2e.utils.product_solution_runtime import load_versioned_app_records_for_product_pack


TARGET_PRODUCT_KEYWORDS = ["自动化产品编辑_", "自动化产品_", "自动化产品"]


@pytest.mark.e2e_standalone
def test_prodsol_flow_005_pack_existing_product_with_versioned_apps(page: Page, settings, bug_reporter) -> None:
    admin = ProductSolutionAdminPage(page, settings.admin_url)
    admin.login(settings.admin_username, settings.admin_password)
    bug_reporter.record_if_errors(account=settings.admin_username, location="SaaS Admin 登录")

    records = load_versioned_app_records_for_product_pack()
    assert records, "PRODSOL-FLOW-005 前置缺失：请先执行 APPVER-FLOW-001+004 产出已新增版本且已绑定资源的应用"
    app_codes = [record["app_code"] for record in records]
    apps = [(record["app_code"], record["app_code"]) for record in records]
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"PRODSOL-FLOW-005 读取 APPVER 前置产物：{','.join(app_codes)}",
    )

    product_code, product_name = admin.pack_existing_product_and_read_back(
        product_name_keywords=TARGET_PRODUCT_KEYWORDS,
        apps=apps,
    )
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"PRODSOL-FLOW-005 既有产品打包并重新进入回读：{product_code}/{product_name}",
    )
