from __future__ import annotations
from .common import fetch_json, cache_payload, normalized_source, clean_text

BASE = "https://rxnav.nlm.nih.gov/REST"

def research(name: str, cache_dir):
    url = f"{BASE}/drugs.json?name={__import__('urllib.parse').parse.quote(name)}"
    data, meta = fetch_json(url)
    raw = __import__('json').dumps(data).encode()
    cm = cache_payload(cache_dir, "rxnorm", name, url, raw, meta)
    groups = data.get("drugGroup", {}).get("conceptGroup", []) or []
    concepts=[]
    for group in groups:
        tty=group.get("tty","")
        for p in group.get("conceptProperties",[]) or []:
            concepts.append({"rxcui":p.get("rxcui",""),"name":p.get("name",""),"synonym":p.get("synonym",""),"tty":tty})
    sections=[{"section":"Drug concepts","subsection":"RxNorm matches","locator":"conceptProperties","text":clean_text(c.get("name")),"data":c} for c in concepts[:100]]
    return normalized_source(connector="rxnorm", title=f"RxNorm concepts for {name}", url=url,
        source_type="terminology_api", sections=sections, raw_meta=cm,
        identifiers={"rxcuis":sorted({c['rxcui'] for c in concepts if c['rxcui']})}, warnings=[]), concepts
