"""Pytest-based direct test: fetch real articles, store, verify enrichment fields."""
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
import pytest


class TestRealPipelineFields:
    """Test that real PubMed articles pass through the pipeline with enrichment fields."""

    @pytest.mark.asyncio
    async def test_fetch_parsed_article_has_enrichment(self):
        """Verify fetch_articles returns enrichment fields for real PMIDs."""
        from app.services.pubmed_api import fetch_articles

        articles = await fetch_articles([38890137])
        assert len(articles) == 1
        a = articles[0]
        assert "chemical_list" in a
        assert isinstance(a["chemical_list"], list)
        assert len(a["chemical_list"]) > 0, f"Expected chemicals in PMID 38890137 but got {a['chemical_list']}"
        assert a["publication_status"] is not None
        print(f"    chemicals: {len(a['chemical_list'])} → {[c['name'] for c in a['chemical_list'][:3]]}")
        print(f"    status: {a['publication_status']}")

    @pytest.mark.asyncio
    async def test_constructor_stores_enrichment(self, db):
        """Verify GlobalLiterature constructor stores enrichment fields from parsed article."""
        from app.services.pubmed_api import fetch_articles, _update_lit_from_article
        from app.models.literature import GlobalLiterature
        import uuid, hashlib

        articles = await fetch_articles([38890137])
        a = articles[0]

        lit = GlobalLiterature(
            id=uuid.uuid4(), pmid=a["pmid"], title=a["title"],
            abstract=a.get("abstract"), authors=a.get("authors", []),
            doi=a.get("doi"), journal=a.get("journal"),
            chemical_list=a.get("chemical_list", []),
            gene_symbols=a.get("gene_symbols", []),
            num_refs=a.get("num_refs"),
            publication_status=a.get("publication_status"),
            article_date=a.get("article_date"),
            databank_list=a.get("databank_list", []),
            suppl_mesh_list=a.get("suppl_mesh_list", []),
            source="test",
            raw_xml_hash=hashlib.sha256(a["title"].encode()).hexdigest()[:16],
        )
        db.add(lit)
        await db.flush()

        lit2 = await db.get(GlobalLiterature, lit.id)
        assert lit2.chemical_list == a["chemical_list"]
        assert lit2.publication_status == a["publication_status"]
        assert lit2.article_date == a["article_date"]
        print(f"    chemical_list stored: {len(lit2.chemical_list)} items")
        print(f"    publication_status stored: {lit2.publication_status}")
        print(f"    article_date stored: {lit2.article_date}")

        await db.delete(lit2)
        await db.flush()

    @pytest.mark.asyncio
    async def test_update_path_stores_enrichment(self, db):
        """Verify _update_lit_from_article stores enrichment fields."""
        from app.services.pubmed_api import fetch_articles, _update_lit_from_article
        from app.models.literature import GlobalLiterature
        import uuid

        articles = await fetch_articles([38310458])
        a = articles[0]

        lit = GlobalLiterature(
            id=uuid.uuid4(), pmid=99999990, title="Update test",
            source="test", raw_xml_hash="test",
        )
        db.add(lit)
        await db.flush()

        _update_lit_from_article(lit, a)
        assert lit.chemical_list == a.get("chemical_list", [])
        assert lit.publication_status == a.get("publication_status")
        print(f"    update path chemical_list: {lit.chemical_list}")
        print(f"    update path status: {lit.publication_status}")

        await db.delete(lit)
        await db.flush()
