from dulizhan.test_case.Resource.UI.base_page import BasePage
from dulizhan.test_case.Resource.UI.blog_page import BlogPage
from types import SimpleNamespace

import allure
import pytest
from playwright.sync_api import sync_playwright

from dulizhan.test_case.Resource.UI.blog_page import BlogPage


case_info = SimpleNamespace(
    projectId=1001,
    caseId=2001,
    automationType="ui",
    caseKey="TC_dulizhan_ui_api_verify_001",
    moduleName="blog",
    productName="",
    projectName="dulizhan",
    caseName="进入blog页面，随机点击blog，跳转到blog内容后截图，就认为用例执行成功",
    screenshotDir=r"C:\Users\a\smart-management-auto-test\dulizhan\screenshots",
    pageUrl="https://joyhub-website-frontend-test.best-envision.com/",
)


@pytest.fixture(scope="function")
def page():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            viewport={"width": 1440, "height": 900},
            ignore_https_errors=True,
        )
        page = context.new_page()
        yield page
        context.close()
        browser.close()


@allure.feature(case_info.projectName)
@allure.story(case_info.moduleName)
@allure.title(case_info.caseName)
def test_enter_blog_random_click_and_capture_content(page):
    blog_page = BlogPage(page)

    with allure.step("打开被测页面"):
        blog_page.open_home_page()
        assert page.url.startswith(case_info.pageUrl)

    with allure.step("进入blog页面"):
        entered_url = blog_page.enter_blog_page()
        allure.attach(
            entered_url,
            name="进入blog页面后的URL",
            attachment_type=allure.attachment_type.TEXT,
        )

    with allure.step("随机点击blog"):
        click_result = blog_page.click_random_blog()
        allure.attach(
            str(click_result),
            name="随机点击blog结果",
            attachment_type=allure.attachment_type.TEXT,
        )

    with allure.step("截图跳转的blog内容"):
        blog_page.assert_blog_content_page_loaded()
        screenshot_path = blog_page.capture_blog_content_screenshot(
            screenshot_dir=case_info.screenshotDir,
            case_key=case_info.caseKey,
        )

        with open(screenshot_path, "rb") as image_file:
            allure.attach(
                image_file.read(),
                name="blog内容页截图",
                attachment_type=allure.attachment_type.PNG,
            )

        assert screenshot_path, "blog 内容页截图路径为空"
