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

BASE="https://api.fda.gov/drug/label.json"
SECTION_MAP = {
 "indications_and_usage":"Indications and Usage", "dosage_and_administration":"Dosage and Administration",
 "contraindications":"Contraindications", "boxed_warning":"Boxed Warning", "warnings_and_cautions":"Warnings and Precautions",
 "drug_interactions":"Drug Interactions", "use_in_specific_populations":"Use in Specific Populations",
 "pregnancy":"Pregnancy", "lactation":"Lactation", "renal_impairment":"Renal Impairment",
 "hepatic_impairment":"Hepatic Impairment", "clinical_pharmacology":"Clinical Pharmacology",
 "how_supplied":"How Supplied", "storage_and_handling":"Storage and Handling"
}

def research(name: str, cache_dir):
    escaped=name.replace('"','')
    search=f'openfda.generic_name:"{escaped}"'
    url=f"{BASE}?search={urllib.parse.quote(search, safe=':+\"')}&limit=5"
    data, meta=fetch_json(url)
    raw=json.dumps(data).encode()
    cm=cache_payload(cache_dir,"openfda",name,url,raw,meta)
    results=data.get("results",[]) or []
    sources=[]
    for idx,item in enumerate(results):
        of=item.get("openfda",{}) or {}
        title=(of.get("brand_name") or of.get("generic_name") or [name])[0]
        sections=[]
        for key,label in SECTION_MAP.items():
            values=item.get(key) or []
            for n,value in enumerate(values):
                sections.append({"section":label,"subsection":"","locator":f"openFDA field {key}[{n}]","text":clean_text(value),"field":key})
        sources.append(normalized_source(connector="openfda", title=f"{title} labeling record", url=url,
            source_type="regulatory_label_api", version=str(item.get("version","")), publication_date=str(item.get("effective_time","")),
            sections=sections, raw_meta=cm, identifiers={"set_id":item.get("set_id","") ,"spl_id":item.get("id","") ,"rxcui":of.get("rxcui",[])},
            warnings=["openFDA reformats submitted labeling; draft claims require review against the underlying SPL."]))
    return sources
