#!/usr/bin/env python3
"""Create blinded EJIM research manuscript, title-page metadata, and reporting guide."""
from pathlib import Path
import json, re, csv
from collections import OrderedDict
from docx import Document
from docx.shared import Inches,Pt,RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT,WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_BREAK
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.enum.section import WD_SECTION_START
from docx.enum.text import WD_LINE_SPACING

ROOT=Path(__file__).resolve().parents[1]
SUMMARY=json.loads((ROOT/'results'/'tables'/'analysis_summary.json').read_text())

def region(r,s):return next(z for z in SUMMARY['endpoint_regional'] if z['region']==r and z['Sex']==s)
def sexgap(r,y):return next(z for z in SUMMARY['endpoint_sex_gaps'] if z['region']==r and z['Year']==y)
def n(v,d=1):return f'{float(v):.{d}f}'

a=SUMMARY['model_primary'];b=SUMMARY['model_adjusted']
pakm=next(z for z in SUMMARY['pakistan'] if z['Sex']=='Men')
pakw=next(z for z in SUMMARY['pakistan'] if z['Sex']=='Women')
sam=region('South Asia','Men');saw=region('South Asia','Women');mem=region('MENA','Men');mew=region('MENA','Women')

# Original source titles/author information are checked against publisher/PubMed/official records.
BIB=OrderedDict([
('IDF26', 'Genitsaridi I, Salpea P, Salim A, et al (2026) 11th edition of the IDF Diabetes Atlas: global, regional, and national diabetes prevalence estimates for 2024 and projections for 2050. Lancet Diabetes Endocrinol 14:149–156. https://doi.org/10.1016/S2213-8587(25)00299-2'),
('NCD24','NCD Risk Factor Collaboration (NCD-RisC) (2024) Worldwide trends in diabetes prevalence and treatment from 1990 to 2022: a pooled analysis of 1108 population-representative studies with 141 million participants. Lancet 404:2077–2093. https://doi.org/10.1016/S0140-6736(24)02317-1'),
('STAFF25','Stafford LK, Gage A, Xu YY, et al (2025) Global, regional, and national cascades of diabetes care, 2000–23: a systematic review and modelling analysis using findings from the Global Burden of Disease Study. Lancet Diabetes Endocrinol 13:924–934. https://doi.org/10.1016/S2213-8587(25)00217-7'),
('TEUF26','Teufel F, Theilmann M, Marcus ME, et al (2026) Comparing approaches for deriving diabetes care cascades to inform policy: a cross-sectional analysis using national data from 88 countries. Diabetes Care 49:1106–1114. https://doi.org/10.2337/dc26-0267'),
('FLOOD21','Flood D, Seiglie JA, Dunn M, et al (2021) The state of diabetes treatment coverage in 55 low-income and middle-income countries: a cross-sectional study of nationally representative, individual-level data in 680 102 adults. Lancet Healthy Longev 2:e340–e351. https://doi.org/10.1016/S2666-7568(21)00089-1'),
('VARG23','Varghese JS, Anjana RM, Geldsetzer P, et al (2023) National estimates of the adult diabetes care continuum in India, 2019–2021. JAMA Intern Med 183:963–972. https://doi.org/10.1001/jamainternmed.2023.3070'),
('ISLAM23','Islam MT, Bruce M, Alam K (2023) Cascade of diabetes care in Bangladesh, Bhutan and Nepal: identifying gaps in the screening, diagnosis, treatment and control continuum. Sci Rep 13:10285. https://doi.org/10.1038/s41598-023-37519-w'),
('AZAD23','Azadnajafabad S, Ahmadi N, Rezaei N, et al (2023) Evaluation of the diabetes care cascade and compliance with WHO global coverage targets in Iran based on STEPS survey 2021. Sci Rep 13:13528. https://doi.org/10.1038/s41598-023-39433-7'),
('ANJANA23','Anjana RM, Unnikrishnan R, Deepa M, et al (2023) Metabolic non-communicable disease health report of India: the ICMR-INDIAB national cross-sectional study (ICMR-INDIAB-17). Lancet Diabetes Endocrinol 11:474–489. https://doi.org/10.1016/S2213-8587(23)00119-5'),
('BASIT18','Basit A, Fawwad A, Qureshi H, Shera AS (2018) Prevalence of diabetes, pre-diabetes and associated risk factors: second National Diabetes Survey of Pakistan (NDSP), 2016–2017. BMJ Open 8:e020961. https://doi.org/10.1136/bmjopen-2017-020961'),
('LOFF25','Loffreda G, Byström M, El Berri H, et al (2025) Inequities in diabetes prevention and control in fragile, conflict-affected and vulnerable settings: a mixed-methods study from the WHO Eastern Mediterranean Region. BMJ Open 15:e095500. https://doi.org/10.1136/bmjopen-2024-095500'),
('WHO26','World Health Organization (2026) Prevention and control of diabetes mellitus: lessons for service delivery from countries in the WHO South-East Asia Region. WHO Regional Office for South-East Asia. ISBN 978-92-9-022225-5. https://www.who.int/publications/i/item/9789290222255'),
('ADA26','American Diabetes Association Professional Practice Committee for Diabetes (2026) 9. Pharmacologic approaches to glycemic treatment: Standards of Care in Diabetes—2026. Diabetes Care 49(Suppl 1):S183–S215. https://doi.org/10.2337/dc26-S009'),
('LIU26','Liu J, Wang Y, Zhang L, Dang S (2026) Global trends and inequalities in diabetes prevalence and treatment coverage among adults aged ≥45 years, 1990–2040: insights from the NCD-RisC database. Diabetes Metab Res Rev 42:e70164. https://doi.org/10.1002/dmrr.70164'),
('NCDDATA','NCD Risk Factor Collaboration (2024) Code and data for worldwide trends in diabetes prevalence and treatment from 1990 to 2022 [dataset]. Zenodo. https://doi.org/10.5281/zenodo.13987399'),
('WGI26','World Bank (2026) Worldwide Governance Indicators, 2026 update [dataset]. World Bank. https://www.worldbank.org/en/publication/worldwide-governance-indicators. Accessed 31 October 2026'),
('WGIMETHOD','Romano T, Loayza N, Jiang CN, Jain A, Boyce T (2025) The Worldwide Governance Indicators: revised methodology for measuring governance using perception data. World Bank, December 2025. https://www.worldbank.org/content/dam/sites/govindicators/doc/The%20Worldwide%20Governance%20Indicators%202025%20Methodology%20Revision.pdf'),
('WGIREPO','Romano T, Loayza N, Jiang CN, Jain A (2026) Reproducibility package for 2026 update of Worldwide Governance Indicators [dataset and code]. World Bank. https://doi.org/10.60572/zpj8-zz84'),
('WDI26','World Bank (2026) World Development Indicators: GDP per capita (NY.GDP.PCAP.KD) and urban population (SP.URB.TOTL.IN.ZS) [database]. World Bank. https://data.worldbank.org/. Accessed 31 October 2026'),
('MACK23','MacKinnon JG, Nielsen MØ, Webb MD (2023) Fast and reliable jackknife and bootstrap methods for cluster-robust inference. J Appl Econom 38:671–694. https://doi.org/10.1002/jae.2969'),
('CAM08','Cameron AC, Gelbach JB, Miller DL (2008) Bootstrap-based improvements for inference with clustered errors. Rev Econ Stat 90:414–427. https://doi.org/10.1162/rest.90.3.414'),
('STROBE07','von Elm E, Altman DG, Egger M, et al (2007) The Strengthening the Reporting of Observational Studies in Epidemiology (STROBE) statement: guidelines for reporting observational studies. PLoS Med 4:e296. https://doi.org/10.1371/journal.pmed.0040296'),
])
used=OrderedDict()
pat=re.compile(r'\{cite:([A-Z0-9]+)\}')
def C(k):return '{cite:'+k+'}'
def resolve(text):
    def conv(m):
        key=m.group(1)
        if key not in BIB:raise KeyError(key)
        if key not in used:used[key]=len(used)+1
        return '['+str(used[key])+']'
    return pat.sub(conv,text)

title='Diabetes medication treatment coverage, sex gaps and geographic dispersion in South Asia and the Middle East and North Africa, 2000–2022: a 28-country longitudinal ecological study'

doc=Document()
sec=doc.sections[0];sec.top_margin=Inches(.8);sec.bottom_margin=Inches(.78);sec.left_margin=Inches(.93);sec.right_margin=Inches(.9)
# Enable one continuous line numbering sequence, no page breaks.
sect=sec._sectPr
ln=OxmlElement('w:lnNumType');ln.set(qn('w:countBy'),'1');ln.set(qn('w:start'),'1');ln.set(qn('w:distance'),'240');ln.set(qn('w:restart'),'continuous');sect.append(ln)
styles=doc.styles
st=styles['Normal'];st.font.name='Times New Roman';st.font.size=Pt(11);st.paragraph_format.line_spacing=2.0;st.paragraph_format.space_after=Pt(0)
for style in ['Heading 1','Heading 2']:
 s=styles[style];s.font.name='Times New Roman';s.font.color.rgb=RGBColor(25,38,50);s.font.bold=True
 s.font.size=Pt(13 if style=='Heading 1' else 11)
 s.paragraph_format.space_before=Pt(12);s.paragraph_format.space_after=Pt(5);s.paragraph_format.keep_with_next=True
if 'Legend' not in styles:
 stl=styles.add_style('Legend',WD_STYLE_TYPE.PARAGRAPH)
 stl.font.name='Times New Roman';stl.font.size=Pt(9)
 stl.paragraph_format.line_spacing=1.1;stl.paragraph_format.space_after=Pt(7)
if 'Small Note' not in styles:
 stl=styles.add_style('Small Note',WD_STYLE_TYPE.PARAGRAPH);stl.font.name='Times New Roman';stl.font.size=Pt(9);stl.paragraph_format.line_spacing=1.15
footer=sec.footer.paragraphs[0];footer.alignment=WD_ALIGN_PARAGRAPH.RIGHT
fld=OxmlElement('w:fldSimple');fld.set(qn('w:instr'),'PAGE');footer._p.append(fld)

def p(s):
    t=doc.add_paragraph(resolve(s));return t

def h(s,level=1):doc.add_heading(s,level)

def cap(s):doc.add_paragraph(resolve(s),style='Legend')

def note(s):doc.add_paragraph(resolve(s),style='Small Note')

def tab(headers,rows,widths=None):
    t=doc.add_table(rows=1,cols=len(headers));t.style='Table Grid';t.alignment=WD_TABLE_ALIGNMENT.CENTER
    for i,val in enumerate(headers):t.rows[0].cells[i].text=val
    for row in rows:
        cells=t.add_row().cells
        for i,val in enumerate(row):cells[i].text=str(val)
    for row in t.rows:
        for cell in row.cells:
            cell.vertical_alignment=WD_CELL_VERTICAL_ALIGNMENT.CENTER
            for paragraph in cell.paragraphs:
                paragraph.paragraph_format.line_spacing=1
                paragraph.paragraph_format.space_after=Pt(2)
                paragraph.paragraph_format.space_before=Pt(2)
                for run in paragraph.runs:run.font.name='Times New Roman';run.font.size=Pt(8.4)
    for c in t.rows[0].cells:
        for pa in c.paragraphs:
            for run in pa.runs:run.font.bold=True
    headtr=t.rows[0]._tr;trPr=headtr.get_or_add_trPr();rep=OxmlElement('w:tblHeader');rep.set(qn('w:val'),'true');trPr.append(rep)
    if widths:
        for row in t.rows:
            for c,w in zip(row.cells,widths):c.width=Inches(w)
    doc.add_paragraph('')

def fig(fname,width=6.35):
    pr=doc.add_paragraph();pr.alignment=WD_ALIGN_PARAGRAPH.CENTER
    pr.paragraph_format.line_spacing=1
    pr.add_run().add_picture(str(ROOT/'results'/'figures'/fname),width=Inches(width))

# Title and abstract; no author information in blinded manuscript.
pp=doc.add_paragraph(title);pp.style='Title';pp.alignment=WD_ALIGN_PARAGRAPH.LEFT
for rr in pp.runs:rr.font.name='Times New Roman';rr.font.size=Pt(15);rr.font.bold=True
h('Abstract')
p(f'Background: Medication treatment coverage among adults with diabetes captures a clinically consequential dimension of access to care. We characterized 2000–2022 inequalities in modeled treatment coverage across 28 South Asian and Middle East/North African countries and examined exploratory associations with changes in government effectiveness.')
p(f'Results: The study included 1,288 country–sex–year estimates (eight South Asian and 20 Middle East/North African countries). Between-country 90th–10th percentile coverage gaps increased from {n(sam["p10_p90_gap_2000"])} to {n(sam["p10_p90_gap_2022"])} percentage points for South Asian men and from {n(saw["p10_p90_gap_2000"])} to {n(saw["p10_p90_gap_2022"])} for South Asian women; corresponding changes in the Middle East and North Africa were {n(mem["p10_p90_gap_2000"])} to {n(mem["p10_p90_gap_2022"])} and {n(mew["p10_p90_gap_2000"])} to {n(mew["p10_p90_gap_2022"])}. Pakistan’s treatment coverage changed from {n(pakm["treat_2000"])}% to {n(pakm["treat_2022"])}% for men and {n(pakw["treat_2000"])}% to {n(pakw["treat_2022"])}% for women. A fixed-effects regression of 140 country-period observations found a government-effectiveness coefficient of {a["coef_per_one_WGI_score_point_year"]:.4f} percentage points/year per one-score-point/year change (95% confidence interval, conditional on modeled outcomes: {a["ci95_low_conditional"]:.3f} to {a["ci95_high_conditional"]:.3f}; wild cluster bootstrap p={a["wild_cluster_bootstrap_p"]:.3f}). Source-estimate uncertainty was not propagated to regression intervals.')
p('Conclusions: Country-level treatment-coverage point estimates suggest increasing geographic dispersion in both regions alongside heterogeneous sex gaps. The governance association was not distinguishable from zero in this ecological analysis; the evidence does not support a causal interpretation. Clinical-service monitoring should include treatment access, continuity and glycaemic outcomes, supported by primary data.')
p('Keywords: diabetes mellitus; medication treatment coverage; South Asia; Middle East and North Africa; health inequality; ecological analysis; government effectiveness')

h('Background')
p('Diabetes has an expanding global health burden: the International Diabetes Federation estimates that 589 million adults aged 20–79 years had diabetes in 2024, while cross-national clinical care remains highly uneven '+C('IDF26')+'. Diabetes medication can prevent symptomatic hyperglycaemia and reduce diabetes-related complications, but the proportion of individuals with diabetes receiving pharmacological therapy is a distinct indicator from disease prevalence or glycaemic control '+C('NCD24')+'. Treatment coverage also represents only one point in the care continuum; it cannot reveal the adequacy of prescribed regimens or the durability of clinical follow-up.')
p('Global analyses have already documented large differences in treatment and diagnosis across settings '+C('STAFF25')+'. Care-cascade denominators and diabetes definitions can substantially alter apparently comparable treatment estimates '+C('TEUF26')+'. Individual-level research in 55 low-income and middle-income countries found important unmet need for both glucose-lowering and cardiovascular risk reduction therapy '+C('FLOOD21')+'. Those findings motivate transparent, outcome-specific comparisons rather than conflation of medication use, clinical control and composite health-system performance.')
p('Within South Asia, national research from India has documented considerable subnational and socioeconomic differences in diagnosis, medication treatment and glycaemic control '+C('VARG23')+'. Surveys from Bangladesh, Bhutan and Nepal reveal additional gaps along the treatment continuum '+C('ISLAM23')+'. Iranian population-survey evidence provides related context for the Middle East '+C('AZAD23')+'. National metabolic-disease data from India '+C('ANJANA23')+' and the second National Diabetes Survey of Pakistan '+C('BASIT18')+' emphasize why changes in population burden must be considered separately from treatment coverage.')
p('Regional policy analyses additionally describe service-delivery constraints across fragile Eastern Mediterranean settings '+C('LOFF25')+' and practical approaches to improving continuous diabetes care in South and Southeast Asia '+C('WHO26')+'. Pharmacological practice recommendations require individualized treatment choices and continuing reassessment; a treatment-coverage percentage alone cannot measure those standards '+C('ADA26')+'.')
p('The present analysis focused on between-country distributional changes and sex gaps within a defined panel of eight South Asian and 20 Middle East/North African settings from 2000 to 2022. Its distinct descriptive estimands were changes in the distribution of country-specific coverage estimates, rather than another global prevalence calculation. An exploratory ecological model examined whether contemporaneous changes in a broad government-effectiveness index tracked coverage changes after country and interval adjustment. We expected any such association to be difficult to interpret clinically because government effectiveness does not directly measure drug procurement, clinic performance or treatment continuity.')

h('Results')
h('Analytic population and data completeness',2)
p('We analyzed 1,288 age-standardized treatment-coverage point estimates representing 28 countries, two sexes and 23 calendar years (2000–2022). Eight countries were assigned to South Asia and 20 to an operational Middle East and North Africa (MENA) grouping. All country–sex–year outcomes and their published marginal uncertainty intervals were present. The descriptive panel therefore comprised a balanced set of 56 country–sex combinations. The 2000, 2005, 2010, 2015, 2019 and 2022 endpoints produced 140 unique country-period observations. Five country-period records lacked complete GDP-per-capita change data—three for Djibouti and two for Yemen—leaving 135 records for adjusted analyses (Additional file 4).')

h('Treatment coverage and geographic dispersion',2)
p(f'Equal-country mean coverage among South Asian men was {n(sam["mean_2000"])}% in 2000 and {n(sam["mean_2022"])}% in 2022, an increase of {n(sam["change_mean_pp"])} percentage points. The corresponding values for South Asian women were {n(saw["mean_2000"])}% and {n(saw["mean_2022"])}% (change {n(saw["change_mean_pp"])} points). In MENA, the respective changes were {n(mem["change_mean_pp"])} percentage points for men ({n(mem["mean_2000"])}% to {n(mem["mean_2022"])}%) and {n(mew["change_mean_pp"])} points for women ({n(mew["mean_2000"])}% to {n(mew["mean_2022"])}%). Table 1 presents regional means and dispersion estimates; Figure 1 shows annual trajectories together with descriptive interquartile ranges across countries.')
cap('Table 1. Regional treatment coverage and between-country dispersion, 2000 and 2022')
t1=[]
for z in [sam,saw,mem,mew]:
 t1.append([z['region'],z['Sex'],n(z['mean_2000']),n(z['mean_2022']),('+' if z['change_mean_pp']>=0 else '')+n(z['change_mean_pp']),n(z['p10_p90_gap_2000']),n(z['p10_p90_gap_2022'])])
tab(['Region','Sex','Mean 2000 (%)','Mean 2022 (%)','Change (pp)','P90–P10 2000 (pp)','P90–P10 2022 (pp)'],t1)
note('Values are equal-country summaries of NCD-RisC model point estimates, not population-weighted regional estimates or confidence intervals. MENA, Middle East and North Africa; pp, percentage points; P90–P10, 90th minus 10th country percentile.')
fig('Figure_1_Regional_Trajectories.png',6.25)
cap('Figure 1. Country-unweighted medication treatment coverage trajectories by region and sex.')
note('Lines are regional means of country point estimates; shaded bands denote the between-country interquartile range and not model-based uncertainty intervals.')
p(f'Between-country dispersion increased on the point-estimate scale. For South Asian men, the P90–P10 gap widened from {n(sam["p10_p90_gap_2000"])} to {n(sam["p10_p90_gap_2022"])} percentage points; for women it widened from {n(saw["p10_p90_gap_2000"])} to {n(saw["p10_p90_gap_2022"])} points. The corresponding gaps in MENA increased from {n(mem["p10_p90_gap_2000"])} to {n(mem["p10_p90_gap_2022"])} points for men and from {n(mew["p10_p90_gap_2000"])} to {n(mew["p10_p90_gap_2022"])} points for women (Figure 2 shows country-level changes and Figure 3 shows annual dispersion). Because these are summaries of modeled estimates, no posterior probability of widening was calculated.')

h('Sex differences and Pakistan-specific estimates',2)
g00=sexgap('South Asia',2000);g22=sexgap('South Asia',2022);m00=sexgap('MENA',2000);m22=sexgap('MENA',2022)
p(f'The mean country-level women-minus-men gap was {n(g00["mean_sex_gap"])} percentage points in South Asia in 2000 and {n(g22["mean_sex_gap"])} in 2022; women had higher modeled coverage in {g00["n_women_higher"]} of eight countries in 2000 and {g22["n_women_higher"]} in 2022. In MENA, mean gaps were {n(m00["mean_sex_gap"])} and {n(m22["mean_sex_gap"])} percentage points, with female coverage higher in {m00["n_women_higher"]} of 20 countries at baseline and {m22["n_women_higher"]} at the endpoint (Table 2). These descriptive comparisons do not establish statistically supported sex inequities within individual countries.')
cap('Table 2. Country-level women-minus-men treatment-coverage gaps at study endpoints')
s2=[]
for z in [g00,g22,m00,m22]:s2.append([z['region'],str(z['Year']),n(z['mean_sex_gap']),n(z['median_sex_gap']),f'{z["n_women_higher"]}/{z["n_countries"]}'])
tab(['Region','Year','Mean gap (pp)','Median gap (pp)','Countries: women higher'],s2)
note('Gap = women’s coverage minus men’s coverage, expressed in percentage points; positive values indicate higher modeled coverage among women. Country contributions have equal weight.')
p(f'For Pakistan, men’s modeled coverage was {n(pakm["treat_2000"])}% in 2000 and {n(pakm["treat_2022"])}% in 2022 (difference {n(pakm["change_pp"])} points). The corresponding women’s estimates were {n(pakw["treat_2000"])}% and {n(pakw["treat_2022"])}% (difference {n(pakw["change_pp"])} points). Pakistan’s women-minus-men coverage gap changed from {n(pakw["treat_2000"]-pakm["treat_2000"])} to {n(pakw["treat_2022"]-pakm["treat_2022"])} points. The original marginal uncertainty bounds are broad: in 2022, {n(pakm["lo_2022"])}–{n(pakm["hi_2022"])}% for men and {n(pakw["lo_2022"])}–{n(pakw["hi_2022"])}% for women (Additional file 2). Neither Pakistan endpoint-change arithmetic envelope excludes zero; these are not posterior credible intervals for change.')

h('Country-level heterogeneity',2)
p('The equal-sex mean of country endpoint changes ranged from a decline of 4.8 percentage points in Nepal to an increase of 25.5 points in Jordan (Figure 2). Three countries had negative point-estimate changes in equal-sex mean coverage: Nepal, Bangladesh and Iran. These rankings are descriptive and may be unstable because NCD-RisC marginal uncertainty intervals overlap substantially in many countries. Country-specific changes and simple endpoint uncertainty envelopes appear in Additional file 2.')
fig('Figure_2_Country_Endpoint_Changes.png',6.2)
cap('Figure 2. Country-specific changes in equal-sex medication coverage from 2000 to 2022.')
note('Bars reflect the arithmetic mean of men’s and women’s point-estimate changes within each country, not patient-level trends, posterior probabilities or population-weighted regional estimates.')
fig('Figure_3_Country_Inequality.png',6.2)
cap('Figure 3. Descriptive between-country P90–P10 treatment-coverage differences, 2000–2022.')
note('Lines track the difference between the 90th and 10th country percentiles of modeled point estimates. They are not inferential trends or uncertainty intervals.')

h('Ecological associations and uncertainty checks',2)
p(f'In the primary 140-observation country-period fixed-effects model, a one-point/year greater change in the WGI government-effectiveness score was associated with {a["coef_per_one_WGI_score_point_year"]:.4f} percentage points/year greater treatment-coverage change (country-clustered 95% confidence interval, conditional on source point estimates: {a["ci95_low_conditional"]:.3f} to {a["ci95_high_conditional"]:.3f}; cluster-t p={a["p_cluster_t"]:.3f}). A null-imposed wild cluster bootstrap-t test using 1,999 Rademacher replications gave p={a["wild_cluster_bootstrap_p"]:.3f}. In the 135-observation GDP-and-urbanization-adjusted model, the coefficient was {b["coef_per_one_WGI_score_point_year"]:.4f} (95% conditional confidence interval {b["ci95_low_conditional"]:.3f} to {b["ci95_high_conditional"]:.3f}; cluster-t p={b["p_cluster_t"]:.3f}; bootstrap p={b["wild_cluster_bootstrap_p"]:.3f}; Table 3). Estimates are ecological and cannot be interpreted as individual patient effects.')
cap('Table 3. Fixed-effects associations and prespecified sensitivity analyses')
import pandas as pd
mods=pd.read_csv(ROOT/'results'/'tables'/'table3_regression_and_sensitivity.csv')
mdict={row.model:row for row in mods.itertuples(index=False)}
t3=[]
for lab in ['Primary unadjusted: all available','Unadjusted: adjusted-model common sample','Adjusted: GDP and urbanization','Excluding 2019–2022','Excluding six Gulf economies','South Asia exploratory','MENA exploratory']:
 q=mdict[lab];t3.append([lab,str(q.n_country_period),str(q.n_countries),f'{q.coef_per_one_WGI_score_point_year:+.4f}',f'{q.ci95_low_conditional:+.3f} to {q.ci95_high_conditional:+.3f}',n(q.p_cluster_t,3)])
tab(['Model','Obs.','Countries','Coefficient','95% CI*','p*'],t3)
note('*Confidence intervals and t-reference p-values use country-clustered standard errors with degrees of freedom equal to the number of countries minus one; they condition on NCD-RisC point estimates. Outcome and exposure both represent annualized change; coefficient units are treatment-coverage percentage points per year per one WGI-score point per year. Country and period fixed effects are included; the adjusted model adds log GDP-per-capita and urban-share changes. Regional analyses are exploratory and underpowered.')
p(f'Excluding the pandemic-era 2019–2022 interval produced a primary coefficient of {mdict["Excluding 2019–2022"].coef_per_one_WGI_score_point_year:+.4f}; excluding six Gulf economies produced {mdict["Excluding six Gulf economies"].coef_per_one_WGI_score_point_year:+.4f}. Leave-one-country-out coefficients ranged from {SUMMARY["loo_min"]:+.4f} to {SUMMARY["loo_max"]:+.4f} (Figure 4; Additional file 3). The WGI marginal 90% score intervals at the endpoints of all 140 country-period comparisons overlapped, which illustrates the limited resolution of within-country governance changes; interval overlap is a descriptive diagnostic rather than a formal test of zero change. None of the regression uncertainty results incorporate the covariance or posterior uncertainty of the NCD-RisC outcome estimates.')
fig('Figure_4_Leave_One_Country_Out.png',6.0)
cap('Figure 4. Leave-one-country-out government-effectiveness coefficients in the primary ecological model.')
note('Points and whiskers show country-clustered coefficients and conditional 95% confidence intervals. The dashed vertical line is zero; the dotted line is the full-sample coefficient. Neither source uncertainty nor governance measurement error is propagated.')

h('Discussion')
h('Principal findings and clinical interpretation',2)
p('Across a 28-country panel, mean estimated medication treatment coverage increased more in MENA than in South Asia from 2000 to 2022. Nevertheless, the between-country spread of modeled coverage point estimates widened in both analytical regions. This finding is clinically important because aggregate improvements in treatment uptake can coexist with settings in which adults with diabetes remain much less likely to receive glucose-lowering medication. However, these estimates are not measurements of clinical prescribing quality, dose optimization or glycaemic control.')
p('Pakistan illustrates the need for careful interpretation of apparently modest changes. The modeled male coverage proportion was nearly unchanged, whereas the female point estimate increased by several percentage points. Yet the source uncertainty intervals are wide enough that these endpoint differences should not be presented as definitive changes in access or as confirmed sex divergence. The appropriate clinical response is more detailed surveillance through representative surveys, prescribing registries and health-facility supply metrics, with clear denominators and assessment of glycaemic outcomes.')

h('Relation to existing evidence',2)
p('The 2024 global NCD-RisC analysis documented international differences and temporal trends in medication treatment coverage '+C('NCD24')+', while the global care-cascade study extended comparisons to diagnosis and glycaemic control '+C('STAFF25')+'. Liu et al. subsequently used NCD-RisC data to assess global inequalities in diabetes prevalence and treatment coverage among adults aged 45 years or older, reporting slope and relative concentration indices of inequality and projections through 2040 '+C('LIU26')+'. The present study therefore does not claim originality in demonstrating international treatment disparities or widening global inequality. Its narrower contribution is to quantify sex-specific changes in within-panel P90–P10 geographic dispersion and sex gaps across 28 defined South Asian and Middle East/North African countries during 2000–2022, with an exploratory fixed-effects examination of government-effectiveness changes. Unlike Liu et al., it does not calculate global socioeconomic concentration indices or forecast treatment coverage beyond 2022. Differences in target age groups and inequality measures limit direct comparison of effect sizes; the regional dispersion findings here remain descriptive summaries of modeled point estimates, without joint posterior evidence for statistically confirmed widening.')
p('Regional survey research demonstrates that a medication-use percentage is only one layer of health-system performance. India’s continuum research documents differences across districts and demographic groups '+C('VARG23')+'; Bangladesh, Bhutan and Nepal analyses identify screening, diagnosis, treatment and control gaps '+C('ISLAM23')+'; and the Iranian STEPS study examines related cascade deficits '+C('AZAD23')+'. These studies use distinct underlying populations and definitions, and their absolute percentages should not be treated as interchangeable with the NCD-RisC age-standardized treatment series. The 2026 comparative cascade methods study underscores the magnitude of such definitional discrepancies '+C('TEUF26')+'.')

h('Governance and system-level context',2)
p('The ecological association with government effectiveness was centered close to zero in the principal model and remained uncertain after socioeconomic adjustment. A null regression coefficient neither proves that health governance is irrelevant to diabetes care nor supports a policy recommendation to deprioritize governance reform. The World Bank’s government-effectiveness score aggregates broad perceptions about public-service quality and policy implementation, with substantial measurement uncertainty. Drug stock availability, clinician staffing, insurance coverage, referral systems and medication continuity are more proximal determinants of clinical treatment access but were not observed consistently over this panel.')
p('Recent evidence from fragile Eastern Mediterranean settings points to gaps in implementation of diabetes policies, primary-care insulin availability and surveillance infrastructure '+C('LOFF25')+'. WHO service-delivery experience from Southeast Asia similarly highlights the importance of integrated care, diagnostics and essential medicines '+C('WHO26')+'. These mechanisms suggest why generalized governance indicators may be too indirect or slow-moving to detect short-term changes in diabetes medication use. They are hypotheses that require facility-level and patient-level data rather than causal deductions from ecological regression.')

h('Strengths, limitations and interpretation of uncertainty',2)
p('The analysis used a common multi-country outcome definition, 23 annual estimates per country–sex combination, a transparent country-period design without duplicate country-level exposures, direct quantification of cross-country dispersion and sex gaps, and cluster-aware regression sensitivity analyses. Source files, executable scripts, tabular outputs and documentation are supplied for reproducibility. The use of country fixed effects limits confounding by time-invariant country attributes; period fixed effects account for common shocks but not all time-varying confounders.')
p('Several limitations materially constrain the strength of inference. First, the outcome is a Bayesian model-based estimate rather than individual-level observations. The published marginal 95% uncertainty intervals were available, but joint draws and cross-year posterior covariance were not; neither country endpoint changes nor cross-country dispersion trends have calibrated joint posterior intervals. Endpoint arithmetic envelopes computed from marginal bounds are sensitivity descriptors, not 95% credible intervals for change. Second, the governance measure has broad marginal 90% confidence intervals and potential temporal changes in perception sources; classical regression correction for its measurement error was not possible. Third, the annual outcome estimates inherit smoothing and shared-data dependence from NCD-RisC, so the modeled years should not be interpreted as independent samples or newly collected annual clinical records. Fourth, 28 country clusters limit regression precision, and few-country regional analyses are exploratory despite small-cluster methods. Fifth, country means assign equal weights to countries regardless of diabetes population size, and the equal-sex composite is not a population-weighted outcome. Sixth, setting classifications are operational rather than geographic or WHO-region definitions, and changing membership would affect region summaries.')
p('The analysis is ecological and observational; no patient-level confounders were measured and medication treatment among adults 30 years and older cannot be algebraically combined with diabetes prevalence among adults 18 years and older. Missing GDP data were concentrated in Djibouti and Yemen, which could bias the adjusted regression relative to the full panel. Treatment receipt itself cannot reveal adherence, appropriate choice of drug, renal or cardiovascular protection, glycaemic control, or complication outcomes. Consequently, clinical recommendations must be based on direct clinical evidence and monitored quality metrics rather than on the regression coefficient alone.')

h('Implications for internal medicine',2)
p('For clinicians and service planners, the results support tracking medication access alongside diagnosis, persistent use, glycated haemoglobin control and cardio-renal risk management. Contemporary diabetes pharmacotherapy emphasizes individualized selection, reassessment and risk-based prescribing '+C('ADA26')+'. Monitoring in Pakistan and neighboring settings would benefit from representative longitudinal surveys linked, where appropriate, to facility inventories, medication dispensing, insurance coverage and clinical outcomes. Such studies could test whether within-country disparities reflect availability, affordability, continuity or the distribution of diabetes burden, rather than attributing them to a broad governance index.')

h('Conclusions')
p('Within this 28-country South Asia–MENA panel, treatment-coverage point estimates suggest widening between-country dispersion between 2000 and 2022, with heterogeneous sex differences and limited estimated progress for some settings, including Pakistan. The exploratory association between short-term changes in government effectiveness and medication coverage was imprecise and near zero. The evidence supports careful monitoring of geographically unequal diabetes treatment access but does not establish causal health-system determinants. Robust individual- and facility-level data are needed to evaluate clinically actionable mechanisms.')

h('Methods')
h('Study design, target outcome and geographical scope',2)
p('This longitudinal ecological analysis used public model-based estimates for the 23-year period 2000–2022. The unit of the descriptive series was country–sex–year. South Asia was operationally defined as Afghanistan, Bangladesh, Bhutan, India, Maldives, Nepal, Pakistan and Sri Lanka (n=8). MENA comprised Bahrain, Djibouti, Egypt, Iran, Iraq, Jordan, Kuwait, Lebanon, Libya, Morocco, Oman, Palestine, Qatar, Saudi Arabia, Somalia, Sudan, Syria, Tunisia, United Arab Emirates and Yemen (n=20). These operational groups were chosen for regional relevance and were held fixed throughout analysis; they should not be confused with official WHO regional designations.')
p('The outcome was the NCD Risk Factor Collaboration age-standardized proportion of adults aged 30 years and older with diabetes who reported receiving medication for diabetes, by country, sex and year '+C('NCDDATA')+'. We converted fractions to percentages and retained the corresponding published 95% marginal uncertainty limits. These are modeled estimates informed by population-representative studies, not a patient cohort. Disease prevalence among adults aged 18 years and older was not used as a treatment denominator or compared by subtraction. Data were downloaded from the archived 2024 NCD-RisC country-level file and source code/data record.')

h('Governance and socioeconomic variables',2)
p('The contextual exposure was the World Bank Worldwide Governance Indicators (WGI) government-effectiveness absolute score (0–100), obtained from the 2026 update '+C('WGI26')+'. We used the associated marginal 90% confidence bounds to examine endpoint overlap. The revised WGI series incorporates recalculated historical governance scores and updated indicators; governance perceptions are broad measurements of institutional performance rather than specific clinical-service inputs '+C('WGIMETHOD')+'. The available reproducibility record identifies the underlying 2026 WGI data and methodology '+C('WGIREPO')+'. Secondary covariates were log GDP per capita in constant 2015 US dollars and the percentage of the population living in urban areas, both from World Development Indicators '+C('WDI26')+'. Source vintage, original World Bank JSON exports and SHA-256 file hashes are preserved.')

h('Descriptive inequalities and source uncertainty',2)
p('For each region, sex and year, we calculated country-unweighted means, medians, interquartile ranges (75th minus 25th percentile) and 90th–10th percentile gaps from the point estimates. Differences between 2000 and 2022 are arithmetic comparisons of estimates at two endpoints. For each country and year, the sex gap was the female minus male treatment percentage. The regional sex gap was the equal-country average of the country-specific gap. For each country and sex, the simple endpoint-change envelope was [2022 marginal lower limit − 2000 marginal upper limit, 2022 marginal upper limit − 2000 marginal lower limit]. Since cross-year and cross-sex posterior covariance was unavailable, these envelopes do not have 95% joint coverage and are not probability statements. No confidence interval was constructed for regional dispersion changes.')

h('Country-period models',2)
p('For regression, we specified five non-overlapping periods: 2000–2005, 2005–2010, 2010–2015, 2015–2019 and 2019–2022. The annualized dependent variable was the equal-sex average of the male and female changes in medication coverage (percentage points per year) for country c and period p. Equal weighting of sexes was deliberate to avoid the pseudoreplication of a single country-level governance exposure in separate male and female rows; the result is not a population-weighted combined-sex estimate. The main exposure was the annualized change in the WGI absolute score (score points per year).')
p('The primary ordinary least-squares specification was ΔT(c,p) = α(c) + λ(p) + βΔG(c,p) + ε(c,p), containing country and period fixed effects. The adjusted specification added annualized within-period change in log real GDP per capita and change in the percentage urban population. Country-level clustering was used for sandwich covariance estimation, with a t reference using 27 degrees of freedom (number of countries minus one). We also calculated null-imposed Rademacher wild cluster bootstrap-t p-values with 1,999 draws at country level and a fixed reproducibility seed, to assess small-cluster sensitivity '+C('MACK23')+' '+C('CAM08')+'. The bootstrap conditions on the supplied source point estimates and does not solve model-estimation uncertainty or exposure measurement error. The fixed-effects analysis is exploratory and associations are not causal effects.')

h('Missingness, robustness and reporting',2)
p('There were 140 country-period rows in the primary model. GDP-per-capita changes could not be calculated for five country-period records: Djibouti in 2000–2005, 2005–2010 and 2010–2015; and Yemen in 2015–2019 and 2019–2022. The adjusted model used complete cases (n=135); an unadjusted regression on that same analytic sample was also reported. We examined estimates excluding the 2019–2022 period, excluding six Gulf economies, by operational region and after dropping each country in turn. No missing values were imputed. To contextualize WGI measurement uncertainty, we counted whether marginal 90% endpoint intervals overlapped; overlap is not equivalent to a valid hypothesis test for changes. Descriptive summaries and exploratory regression coefficients were produced with Python, pandas, SciPy and statsmodels. Reporting principles were informed by the STROBE observational-study guidance '+C('STROBE07')+'. No formal prospective sample-size or power calculation was applicable because this was an exhaustive secondary panel of the selected country–year estimates.')

h('Computational assistance and research accountability',2)
p('An OpenAI large language model assisted with code construction, statistical execution, literature identification and manuscript writing. The analysis outputs are generated by the supplied reproducible Python scripts using preserved original source files. Scientific interpretation, citation verification and approval of the text for submission remain the responsibility of the named authors.')

h('List of abbreviations')
p('CI, confidence interval; GDP, gross domestic product; MENA, Middle East and North Africa; NCD-RisC, NCD Risk Factor Collaboration; pp, percentage points; P90–P10, 90th minus 10th percentile; WDI, World Development Indicators; WGI, Worldwide Governance Indicators.')

h('Declarations')
h('Ethics approval and consent to participate',2)
p('Not applicable. This study analyzed publicly available country-level aggregated modeled estimates and did not access individual participant records or personally identifiable data.')
h('Consent for publication',2)
p('Not applicable. No identifiable individual information is reported.')
h('Availability of data and materials',2)
p('The data supporting the findings are included within the article and its additional files. Source outcome estimates are publicly available through the NCD Risk Factor Collaboration archive '+C('NCDDATA')+'; the World Bank government-effectiveness and development-indicator series are publicly available through the World Bank '+C('WGI26')+' '+C('WDI26')+'. The accompanying archive contains exact source extracts, derived country–sex and country-period data, source checksums, analysis code, numerical outputs and figures.')
h('Competing interests',2)
# Author-dependent declarations must never be invented. Omit text after headings.
h('Funding',2)
h('Authors’ contributions',2)
h('Acknowledgements',2)

h('Additional files')
p('Additional file 1 (CSV): Country–sex–year treatment estimates and women-minus-men gaps. Additional file 2 (CSV): Country endpoint differences and nonprobabilistic arithmetic uncertainty envelopes. Additional file 3 (CSV): Leave-one-country-out regression coefficients and conditional confidence intervals. Additional file 4 (CSV): Country-period ecological analysis dataset used for statistical modeling.')

h('References')
for key,number in used.items():
    para=doc.add_paragraph(f'{number}. {BIB[key]}');para.paragraph_format.line_spacing=1.15;para.paragraph_format.space_after=Pt(5)
# Sanity ensure every source cited with first-use sequential numbering
(ROOT/'submission'/'references_index.json').write_text(json.dumps([{'number':v,'key':k,'citation':BIB[k]} for k,v in used.items()],indent=2,ensure_ascii=False))

out=ROOT/'submission'/'Research_Manuscript.docx'
doc.save(out)
(ROOT/'submission'/'Research_Manuscript.txt').write_text('\n\n'.join(para.text for para in doc.paragraphs),encoding='utf8')

# Separate title page: only verified, non-identifying publication metadata; author data must be supplied by users.
t=Document();s=t.sections[0];s.top_margin=Inches(1);s.bottom_margin=Inches(.9);s.left_margin=Inches(1);s.right_margin=Inches(1)
t.add_heading('Title page',0)
t.add_paragraph(title)
t.add_paragraph('Article type: Research')
t.add_paragraph('Journal: The Egyptian Journal of Internal Medicine')
t.add_paragraph('Tables: 3; Figures: 4; Additional data files: 4')
# Author identification intentionally omitted; submitting authors provide verified metadata.
t.save(ROOT/'submission'/'Title_Page.docx')

# Author-facing submission facts file: no unconfirmed declarations or author identity inserted into manuscript.
(ROOT/'submission'/'AUTHOR_SUBMISSION_DETAILS.txt').write_text(
    'For author completion prior to journal submission:\n'
    '- Author names, institutional addresses, ORCID identifiers and corresponding-author contact details must be provided on the separate title page.\n'
    '- Provide verified funding disclosures, conflicts of interest, author initials and contribution statements, and acknowledgements if applicable. The corresponding declaration headings in the blinded manuscript intentionally contain no unverified assertions.\n'
    '- Verify ethics wording with institutional policy and all authors; public aggregated data typically do not require participant consent.\n'
    '- Confirm consent from all named authors, that the work has not been submitted elsewhere, and the accuracy of the large-language-model-use disclosure.\n'
    '- Check references and the generated numerical outputs independently before submitting. No editor acceptance is guaranteed.\n',encoding='utf8')

(ROOT/'submission'/'REFERENCE_VERIFICATION.md').write_text('# Bibliographic source index\n\nAll numbered sources below were checked against official publisher, database, PubMed or institutional records as of 31 October 2026. Individual claim-level interpretation remains the responsibility of the submitting authors.\n\n' + '\n'.join(f'{v}. {BIB[k]}' for k,v in used.items())+'\n',encoding='utf8')

print('Created',out,'references=',len(used),'paragraphs=',len(doc.paragraphs),'tables=',len(doc.tables))
print('Reference sequence:',[(k,v) for k,v in used.items()])
