from dulizhan.test_case.Resource.UI.base_page import BasePage
from dulizhan.test_case.Resource.UI.news_page import NewsPage
from types import SimpleNamespace

import allure
import pytest
from playwright.sync_api import sync_playwright

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


CASE_INFO = SimpleNamespace(
    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):
    page = browser.new_page(
        viewport={"width": 1440, "height": 1200},
        ignore_https_errors=True,
    )
    yield page
    page.close()


@pytest.fixture()
def case_info():
    return CASE_INFO


@allure.feature(CASE_INFO.projectName)
@allure.story(CASE_INFO.moduleName)
@allure.title(CASE_INFO.caseName)
@pytest.mark.ui
def test_enter_news_random_click_and_screenshot(page, case_info):
    news_page = NewsPage(page, case_info.pageUrl)

    with allure.step("打开被测页面"):
        news_page.open_home()
        news_page.accept_cookie_if_present()
        assert "Joyhub" in news_page.title(), f"首页标题不符合预期，当前标题：{news_page.title()}"

    with allure.step("进入news页面"):
        news_page.enter_news_page()
        assert news_page.is_news_context(), (
            f"未确认进入 news 页面上下文，当前URL：{page.url}，当前标题：{page.title()}。"
            "侦察结果未提供明确 News 导航 selector，如实际路由不是 /news，请调整 NewsPage.NEWS_ROUTE。"
        )

    with allure.step("随机点击news"):
        before_click_url = page.url
        selected_news = news_page.click_random_news_item()
        allure.attach(
            str(selected_news),
            name="随机点击的 news 候选",
            attachment_type=allure.attachment_type.TEXT,
        )
        assert page.url != before_click_url or selected_news.get("href"), (
            f"点击 news 后页面未发生有效跳转，点击前URL：{before_click_url}，点击后URL：{page.url}"
        )

    with allure.step("截图跳转的news内容"):
        screenshot_path = news_page.screenshot_news_content(
            screenshot_dir=case_info.screenshotDir,
            file_name=f"{case_info.caseKey}_news_content.png",
        )
        allure.attach.file(
            screenshot_path,
            name="跳转后的news内容截图",
            attachment_type=allure.attachment_type.PNG,
        )
        assert screenshot_path, "news 内容截图保存失败"
