# ============================================================
# pytest 配置 — 全局 Fixtures & HTML 报告
# ============================================================
import pytest
import datetime
import os
import random
from api_client import ApiClient
from config import (
    API_BASE_URL, ADMIN_USERNAME, ADMIN_PASSWORD, CAPTCHA_ENABLED,
    SELLER_USERNAME, SELLER_PASSWORD, TEST_PASSWORD,
)


# ============================================================
# HTML 报告配置
# ============================================================
def pytest_html_report_title(report):
    report.title = "巴清农资商城 · 端到端全量测试报告"


def pytest_configure(config):
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    config._metadata = {
        "项目": "巴清农资商城 (Baqing Shop)",
        "测试时间": now,
        "测试类型": "端到端全量测试 (E2E)",
        "Python": os.popen("python --version 2>&1").read().strip(),
        "API地址": API_BASE_URL,
        "测试用例数": "124 条 (覆盖 63 个 Controller)",
    }
    for tag in ["admin_flow", "consumer_flow", "seller_flow", "full_chain"]:
        config.addinivalue_line("markers", tag)


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    if report.when in ("call", "setup"):
        doc = item.function.__doc__ or ""
        if doc:
            report.description = doc.strip()


# ============================================================
# 全局 Fixtures
# ============================================================

@pytest.fixture(scope="session")
def client():
    """所有测试共享一个 HTTP 客户端（session 级别）"""
    c = ApiClient()
    yield c
    c.session.close()


@pytest.fixture(scope="session")
def admin_token(client):
    """管理员登录，返回 token（session 级别）"""
    if CAPTCHA_ENABLED:
        pytest.skip("验证码已开启，请在测试环境关闭验证码后再运行")
    resp = client.post("/login", json={
        "username": ADMIN_USERNAME,
        "password": ADMIN_PASSWORD,
        "code": "",
        "uuid": "",
    })
    data = client.assert_ok("管理员登录失败")
    token = data.get("token")
    assert token, f"登录返回中没有 token"
    client.set_admin_token(token)
    print(f"\n  [SETUP] 管理员 {ADMIN_USERNAME} 登录成功")
    return token


@pytest.fixture(scope="session")
def member_token(client):
    """会员注册并登录（session 级别）"""
    mobile = f"138{random.randint(10000000, 99999999)}"

    # 注册
    resp = client.post("/api/member/register", json={
        "mobile": mobile,
        "password": TEST_PASSWORD,
        "confirmPassword": TEST_PASSWORD,
        "nickName": f"E2E测试_{mobile[-4:]}",
        "agreementAccepted": True,
    })
    data = client.assert_ok("会员注册失败")
    member_id = data.get("data")
    print(f"\n  [SETUP] 会员注册成功 memberId={member_id}")

    # 登录
    resp = client.post("/api/member/login", json={
        "account": mobile,
        "password": TEST_PASSWORD,
        "agreementAccepted": True,
    })
    data = client.assert_ok("会员登录失败")
    token = data.get("token")
    assert token, "会员登录返回中没有 token"
    client.set_member_token(token)
    print(f"  [SETUP] 会员登录成功 token={token[:16]}...")
    return token


@pytest.fixture(scope="session")
def seller_token(client):
    """商家登录（session 级别）"""
    if CAPTCHA_ENABLED:
        pytest.skip("验证码已开启")
    resp = client.post("/login", json={
        "username": SELLER_USERNAME,
        "password": SELLER_PASSWORD,
        "code": "",
        "uuid": "",
    })
    data = client.assert_ok("商家登录失败")
    token = data.get("token")
    assert token, "商家登录返回中没有 token"
    client.set_seller_token(token)
    print(f"\n  [SETUP] 商家 {SELLER_USERNAME} 登录成功")
    return token
