from dulizhan.test_case.Resource.UI.base_page import BasePage
from dulizhan.test_case.Resource.UI.news_page import NewsPage
import os

import allure
import pytest
from playwright.sync_api import sync_playwright

from dulizhan.test_case.Resource.UI.news_page import NewsPage


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


@pytest.fixture(scope="session")
def browser():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        yield browser
        browser.close()


@pytest.fixture()
def page(browser):
    context = browser.new_context(
        viewport={"width": 1440, "height": 900},
        ignore_https_errors=True,
    )
    page = context.new_page()
    yield page
    context.close()


@allure.feature(CASE_INFO["projectName"])
@allure.story(CASE_INFO["moduleName"])
@allure.title(CASE_INFO["caseName"])
def test_random_click_news_and_capture_content(page):
    screenshot_dir = CASE_INFO["screenshotDir"]
    os.makedirs(screenshot_dir, exist_ok=True)

    news_page = NewsPage(page)

    with allure.step("打开被测页面"):
        news_page.open_home_page()
        news_page.accept_cookie_if_present()
        allure.attach(
            news_page.current_url(),
            name="首页 URL",
            attachment_type=allure.attachment_type.TEXT,
        )

    with allure.step("进入 news 页面"):
        news_page.enter_news_page()
        allure.attach(
            news_page.current_url(),
            name="News 页面 URL",
            attachment_type=allure.attachment_type.TEXT,
        )

    with allure.step("随机点击 news"):
        selected_news = news_page.click_random_news()
        allure.attach(
            str(selected_news),
            name="随机点击的 news 候选信息",
            attachment_type=allure.attachment_type.TEXT,
        )

    with allure.step("截图跳转的 news 内容"):
        news_page.assert_news_content_loaded()
        screenshot_path = news_page.capture_news_content_screenshot(
            screenshot_dir=screenshot_dir,
            case_key=CASE_INFO["caseKey"],
        )
        allure.attach.file(
            screenshot_path,
            name="跳转后的 news 内容截图",
            attachment_type=allure.attachment_type.PNG,
        )

    assert os.path.exists(screenshot_path), f"news 内容截图未生成: {screenshot_path}"
