"""高级功能测试：规则引擎+搜索+摘要+PDF高亮"""

import pytest


@pytest.mark.asyncio
async def test_rule_presets(client):
    r = await client.get("/api/v1/features/rules/presets")
    assert r.status_code == 200
    presets = r.json()["presets"]
    assert "drug_trial" in presets
    assert "biomarker_study" in presets

@pytest.mark.asyncio
async def test_advanced_search(client, auth_headers):
    r = await client.post("/api/v1/features/search/advanced", json={"query":"EGFR","field":"all"}, headers=auth_headers)
    assert r.status_code in (200, 403)

@pytest.mark.asyncio
async def test_plans_list(client):
    r = await client.get("/api/v1/subscriptions/plans")
    assert r.status_code == 200
    assert len(r.json()["plans"]) == 3

@pytest.mark.asyncio
async def test_my_plan_unauthorized(client):
    r = await client.get("/api/v1/subscriptions/my-plan")
    assert r.status_code == 401

@pytest.mark.asyncio
async def test_digest_send(client, auth_headers):
    r = await client.post("/api/v1/features/digest/send-now", headers=auth_headers)
    assert r.status_code == 200
    assert r.json()["status"] == "sent"

@pytest.mark.asyncio
async def test_highlight_crud(client, auth_headers):
    r = await client.post("/api/v1/highlights/39000101", headers=auth_headers, json={"highlight_type":"highlight","page_number":1,"position":{},"text":"test","color":"#ff0"})
    assert r.status_code in (200, 404)  # 404 if pmid not seeded in test db

@pytest.mark.asyncio
async def test_captcha_flow(client):
    r = await client.get("/api/v1/captcha/generate")
    assert r.status_code == 200
    c = r.json()
    q = c["question"].replace(" = ?","")
    parts = q.split()
    a, b, op = int(parts[0]), int(parts[2]), parts[1]
    ans = a+b if op=="+" else a-b if op=="-" else a*b
    r = await client.post("/api/v1/captcha/verify", json={"captcha_id":c["id"],"captcha_answer":ans})
    assert r.json()["status"] == "ok"

@pytest.mark.asyncio
async def test_journal_list(client):
    r = await client.get("/api/v1/public/journals")
    assert r.status_code == 200
    total = r.json()["total"]
    assert total >= 0  # may be 0 in test env without seed


@pytest.mark.asyncio
async def test_rule_test_drug_trial(client, db):
    """POST /features/rules/test with drug_trial preset rule against a seeded PMID"""
    import uuid
    from app.db import new_uuid
    from app.models.literature import GlobalLiterature

    lit = GlobalLiterature(
        id=new_uuid(), pmid=90000901,
        title="A Phase III Randomized Trial of EGFR Inhibitor in NSCLC",
        abstract="",
        pub_types=["Clinical Trial"],
    )
    db.add(lit)
    await db.commit()

    drug_trial_rule = {
        "type": "and",
        "children": [
            {"type": "keyword", "field": "title_abstract", "keyword": "trial"},
            {"type": "or", "children": [
                {"type": "keyword", "field": "title_abstract", "keyword": "phase"},
                {"type": "keyword", "field": "title_abstract", "keyword": "randomi"},
            ]},
        ],
    }
    r = await client.post("/api/v1/features/rules/test?pmid=90000901",
                          json={"rule": drug_trial_rule})
    assert r.status_code == 200
    data = r.json()
    assert data["pmid"] == 90000901
    assert data["matched"] is True
    assert "EGFR" in data["title"]


@pytest.mark.asyncio
async def test_digest_send_all_superuser(client, db):
    """POST /features/digest/send-all as superuser returns 200"""
    import uuid
    from sqlalchemy import select
    from app.models.user import User

    email = f"admin{uuid.uuid4().hex[:6]}@test.cn"
    resp = await client.post("/api/v1/auth/register", json={
        "email": email, "password": "Admin1234", "display_name": "Admin",
    })
    assert resp.status_code == 200
    data = resp.json()
    user_id = uuid.UUID(data["user"]["id"])

    r = await db.execute(select(User).where(User.id == user_id))
    u = r.scalar()
    u.platform_role = "platform_owner"
    await db.commit()

    # Re-login to get fresh JWT with platform_role
    resp2 = await client.post("/api/v1/auth/login", json={
        "email": email, "password": "Admin1234",
    })
    assert resp2.status_code == 200
    headers = {"Authorization": f"Bearer {resp2.json()['token']['access_token']}"}

    r = await client.post("/api/v1/features/digest/send-all", headers=headers)
    assert r.status_code == 200


@pytest.mark.asyncio
async def test_rule_test_no_auth(client, db):
    """POST /features/rules/test without auth headers"""
    import uuid
    from app.db import new_uuid
    from app.models.literature import GlobalLiterature

    lit = GlobalLiterature(
        id=new_uuid(), pmid=90000902,
        title="EGFR Biomarker Study", abstract="", pub_types=[],
    )
    db.add(lit)
    await db.commit()

    r = await client.post("/api/v1/features/rules/test?pmid=90000902",
                          json={"rule": {"type": "keyword", "field": "title", "keyword": "EGFR"}})
    # The endpoint does not require auth (no Depends(get_current_user)),
    # so a bare POST with no headers succeeds.
    assert r.status_code in (200, 401, 403)
