from __future__ import annotations
import json, urllib.parse
from .common import fetch_json, cache_payload, normalized_source, clean_text

BASE="https://eutils.ncbi.nlm.nih.gov/entrez/eutils"

def research(name: str, cache_dir, missing_domains=None):
    domains=missing_domains or ["renal dosing","CRRT","extended infusion","stability"]
    query=f'"{name}" AND ({" OR ".join(domains)})'
    s_url=f"{BASE}/esearch.fcgi?db=pubmed&retmode=json&retmax=12&sort=relevance&term={urllib.parse.quote(query)}"
    search,meta=fetch_json(s_url)
    ids=search.get("esearchresult",{}).get("idlist",[]) or []
    cache_payload(cache_dir,"pubmed_search",name,s_url,json.dumps(search).encode(),meta)
    if not ids:
        return normalized_source(connector="pubmed",title=f"PubMed search: {query}",url=s_url,source_type="literature_search",sections=[],warnings=["No PubMed results returned."])
    sum_url=f"{BASE}/esummary.fcgi?db=pubmed&retmode=json&id={','.join(ids)}"
    summary,smeta=fetch_json(sum_url)
    cm=cache_payload(cache_dir,"pubmed_summary",name,sum_url,json.dumps(summary).encode(),smeta)
    sections=[]
    result=summary.get("result",{})
    for pmid in ids:
        rec=result.get(pmid,{})
        sections.append({"section":"Search result","subsection":clean_text(rec.get("fulljournalname") or rec.get("source")),"locator":f"PMID {pmid}","text":clean_text(rec.get("title")),"data":{"pmid":pmid,"pubdate":rec.get("pubdate",""),"authors":rec.get("authors",[])}})
    return normalized_source(connector="pubmed",title=f"PubMed research results for {name}",url=s_url,source_type="literature_search",sections=sections,raw_meta=cm,identifiers={"pmids":ids},warnings=["Literature search results are research leads, not validated claims."])
