from __future__ import annotations

from datetime import datetime

import pytest
from playwright.sync_api import Page

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


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


@pytest.mark.e2e_standalone
def test_appver_001_004_then_prodsol_005_chain(page: Page, settings, bug_reporter) -> None:
    version_name = f"自动化版本_{datetime.now().strftime('%Y%m%d%H%M%S')}"
    version_description = "自动化新增应用版本并绑定资源"

    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 登录")

    app_code, resource_name = admin.find_visible_app_with_bindable_version_resource(max_rows=20)

    admin.create_app_version(version_name, version_description)
    admin.assert_version_visible(version_name)
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"APPVER-FLOW-001 新增有资源应用版本：{app_code}/{version_name}/{resource_name}",
    )

    admin.select_app_version(version_name)
    admin.search_version_resource(resource_name)
    admin.select_all_filtered_version_resources()
    admin.save_current_version_resources()
    admin.assert_version_resource_checked(resource_name, checked=True)
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"APPVER-FLOW-004 新增版本绑定资源并回读：{app_code}/{version_name}/{resource_name}",
    )

    admin.assert_operation_log(target_type="应用", target_code=app_code, operation_info="新建应用版本")
    admin.assert_operation_log(target_type="应用", target_code=app_code, operation_info="保存应用版本菜单")
    record_versioned_app_for_product_pack(
        app_code=app_code,
        version_name=version_name,
        resource_name=resource_name,
    )

    product_code, product_name = admin.pack_existing_product_and_read_back(
        product_name_keywords=TARGET_PRODUCT_KEYWORDS,
        apps=[(app_code, app_code)],
    )
    bug_reporter.record_if_errors(
        account=settings.admin_username,
        location=f"PRODSOL-FLOW-005 直接使用前置应用打包回读：{product_code}/{product_name}/{app_code}",
    )
