"""Read UDE's published XLSX sample/slide metadata without executing workbook links."""
import csv,datetime,hashlib,json,re,zipfile,xml.etree.ElementTree as ET
from pathlib import Path
R=Path(__file__).resolve().parents[1];D=R/'datasets/r112-ude-full';O=R/'results/r112/ude-sampling-metadata';O.mkdir(parents=True,exist_ok=True);X=D/'sample-slide-metadata.xlsx';SUP=D/'supplementary.zip';M=Path('/tmp/ude-metadata.csv');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();NS={'x':'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}
def normal(x):
 s=x.strip().replace('\\','/').split('/')[-1].casefold()
 return s[:-5] if s.endswith('.tiff') else s[:-4] if s.endswith('.tif') else s
def parse():
 with zipfile.ZipFile(SUP) as archive:assert archive.read('Supplement Table 1 - Metadata Samples and Slides.xlsx')==X.read_bytes()
 with zipfile.ZipFile(X) as archive:
  ss=[''.join(x.itertext()) for x in ET.fromstring(archive.read('xl/sharedStrings.xml')).findall('x:si',NS)];root=ET.fromstring(archive.read('xl/worksheets/sheet1.xml'));rows=[]
  for row in root.findall('x:sheetData/x:row',NS):
   values=['']*12
   for c in row.findall('x:c',NS):
    address=c.attrib['r'];letters=re.match(r'[A-Z]+',address).group();col=0
    for ch in letters:col=col*26+ord(ch)-64
    assert 1<=col<=12;v=c.find('x:v',NS);text=v.text if v is not None and v.text is not None else '';typ=c.get('t')
    if typ=='s' and text:text=ss[int(text)]
    elif typ=='inlineStr':text=''.join(c.find('x:is',NS).itertext())
    values[col-1]=text
   rows.append(values)
 assert rows[0]==['Slide_filename','Site Code','Year of sampling','Date of sampling','Country','Basin','Stream','Lat.','Long.','Type','Substrate','Treatment'];return rows
rows=parse();data=[]
for v in rows[1:]:
 if not v[0].strip():continue
 date=v[3].strip()
 if re.fullmatch(r'\d+(?:\.0+)?',date):
  n=float(date)
  if 1<=n<100000:date=(datetime.datetime(1899,12,30)+datetime.timedelta(days=n)).date().isoformat()
 data.append({'slide_filename':v[0].strip(),'slide_key':normal(v[0]),'site_code':v[1].strip(),'year':v[2].strip(),'sampling_date':date,'country':v[4].strip(),'basin':v[5].strip(),'stream':v[6].strip(),'latitude':v[7].strip(),'longitude':v[8].strip(),'site_type':v[9].strip(),'substrate':v[10].strip(),'treatment':v[11].strip()})
lookup={};duplicates=[]
for r in data:
 k=r['slide_key']
 if k in lookup:duplicates.append(k)
 lookup.setdefault(k,[]).append(r)
with (O/'slide-metadata.csv').open('w',newline='') as f:
 w=csv.DictWriter(f,fieldnames=list(data[0]));w.writeheader();w.writerows(data)
seen=set();matched=set();missing=set();ambiguous=set();crops=0
with M.open(encoding='utf-8-sig',newline='') as f:
 for r in csv.DictReader(f):
  crops+=1;k=normal(r['image_filename']);seen.add(k);n=len(lookup.get(k,[]));(matched if n==1 else missing if n==0 else ambiguous).add(k)
report={'format':'r112-ude-sampling-metadata-v1','source_article':'https://doi.org/10.1093/gigascience/giae087','source_archive_url':'https://academic.oup.com/gigascience/article/doi/10.1093/gigascience/giae087/7912108','supplement_sha256':sha(SUP),'workbook_sha256':sha(X),'local_ude_metadata_sha256':sha(M),'script_sha256':sha(Path(__file__)),'workbook_rows':len(data),'normalized_duplicate_slide_keys':duplicates,'ude_crop_rows':crops,'ude_distinct_slide_keys':len(seen),'matched_keys':len(matched),'missing_keys':len(missing),'ambiguous_keys':len(ambiguous),'missing_slide_keys':sorted(missing),'ambiguous_slide_keys':sorted(ambiguous),'limits':'Published site code, date, location, substrate and treatment are contextual fields, not guaranteed unique sample identifiers. Exact normalized slide filename match does not prove specimen or biological sample independence. Excel numeric dates are converted using the 1900 system, with original workbook retained. Identifications are source expert-reviewed labels, not independently adjudicated here.'};(O/'parse-report.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps({k:v for k,v in report.items() if k in ('workbook_rows','ude_crop_rows','ude_distinct_slide_keys','matched_keys','missing_keys','ambiguous_keys','normalized_duplicate_slide_keys')},indent=2))
