"""Direct test: call fetch_articles, create GlobalLiterature, verify enrichment fields store correctly."""
import os, sys, asyncio
_script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.normpath(os.path.join(_script_dir, "..")))

os.environ["DATABASE_URL"] = "postgresql+asyncpg://scilit:scilit_dev@localhost:5432/scilit"
os.environ["JWT_SECRET"] = "dev-secret-change-in-production"
os.environ["DEBUG"] = "true"
os.environ["SPECIALTY"] = "oncology"

from app.services.pubmed_api import fetch_articles, _update_lit_from_article
from app.core.database import async_session_factory


async def main():
    # 1. Parse real articles
    pmids = [38890137]  # This one had chemicals in debug
    articles = await fetch_articles(pmids)
    a = articles[0]
    print(f"PMID {a['pmid']}: chem={a.get('chemical_list')}, status={a.get('publication_status')}")
    print(f"  article_date={a.get('article_date')}, num_refs={a.get('num_refs')}")
    print(f"  enrichment keys present: {[k for k in a.keys() if k in ('chemical_list','gene_symbols','num_refs','publication_status','article_date','databank_list','suppl_mesh_list')]}")

    # 2. Create GlobalLiterature directly with these fields
    session = async_session_factory()
    db = session()
    await db.__aenter__()

    from app.models.literature import GlobalLiterature
    import uuid as _uid
    import hashlib

    # Test constructor path (simulates _process_article new record creation)
    lit = GlobalLiterature(
        id=_uid.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)
    print(f"\n⏺ Constructor path:")
    print(f"  chemical_list={lit2.chemical_list!r}")
    print(f"  publication_status={lit2.publication_status!r}")
    print(f"  num_refs={lit2.num_refs!r}")
    print(f"  article_date={lit2.article_date!r}")

    assert lit2.chemical_list == a.get("chemical_list"), f"Mismatch: {lit2.chemical_list} vs {a.get('chemical_list')}"
    assert lit2.publication_status == a.get("publication_status"), f"status mismatch"
    print(f"  ✅ Constructor path works!")

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

    # Test update path
    lit3 = GlobalLiterature(
        id=_uid.uuid4(), pmid=99999999, title="Test for update",
        source="test", raw_xml_hash="test123",
    )
    db.add(lit3)
    await db.flush()

    _update_lit_from_article(lit3, a)
    print(f"\n⏺ Update path:")
    print(f"  chemical_list={lit3.chemical_list!r}")
    print(f"  publication_status={lit3.publication_status!r}")

    assert lit3.chemical_list == a.get("chemical_list"), f"Mismatch"
    print(f"  ✅ Update path works!")

    await db.delete(lit3)
    await db.commit()

    await db.__aexit__(None, None, None)
    await session.close()
    print("\n✅ Both paths verified!")


asyncio.run(main())
