#!/usr/bin/env python3
"""Pouch swelling data contract v0.1. Python 3 stdlib, read-only inputs.
PASS means only the implemented data-contract checks passed, never material approval.
Exit: 0 PASS, 2 FAIL, 3 UNDECIDED. No fitting, unit conversion or data repair.
"""
import argparse, csv, hashlib, io, json, math, re
from pathlib import Path

UNITS={'t_s':'s','displacement_m':'m','current_A':'A','voltage_V':'V','soc':'1','temperature_K':'K','pressure_Pa':'Pa','force_N':'N'}
REQUIRED={
 'constant_pressure_cycling':['t_s','displacement_m','current_A','voltage_V'],
 'free_swelling':['t_s','displacement_m','soc','temperature_K'],
 'fixed_soc_compression':['t_s','displacement_m','pressure_Pa','soc','temperature_K'],
 'stress_relaxation':['t_s','displacement_m','pressure_Pa','soc','temperature_K'],
 'assembly_validation':['t_s','displacement_m','force_N']}
HASH=re.compile(r'^[0-9a-f]{64}$')
def finite(x):return isinstance(x,(int,float)) and not isinstance(x,bool) and math.isfinite(x)
def validate(package,root):
 issues=[];summaries=[];seen={};groups={};cell_roles={};root=Path(root).resolve()
 def issue(level,code,where,message):issues.append(dict(level=level,code=code,where=where,message=message))
 def missing(where,key,value):
  if value is None or value=='':issue('UNDECIDED','MISSING_METADATA',where+'.'+key,'Required identity/reference information not established.');return True
  return False
 if not isinstance(package,dict):issue('FAIL','PACKAGE_TYPE','$','Expected object.');return result(issues,summaries)
 if package.get('schema_version')!='0.1':issue('FAIL','VERSION','$','Expected schema_version 0.1.')
 if not isinstance(package.get('study_id'),str) or not package['study_id'].strip():issue('FAIL','STUDY_ID','$','Nonempty study_id required.')
 datasets=package.get('datasets')
 if not isinstance(datasets,list) or not datasets:issue('FAIL','DATASETS','$','At least one dataset object required.');return result(issues,summaries)
 ids=set()
 for idx,d in enumerate(datasets):
  at='datasets['+str(idx)+']'
  if not isinstance(d,dict):issue('FAIL','DATASET_TYPE',at,'Expected object.');continue
  did=d.get('dataset_id')
  if not isinstance(did,str) or not did.strip():issue('FAIL','DATASET_ID',at,'Nonempty dataset_id required.');did=at
  elif did in ids:issue('FAIL','DUPLICATE_ID',at,'dataset_id is repeated.')
  ids.add(did)
  experiment=d.get('experiment');role=d.get('split_role');kind=d.get('evidence_kind')
  if not isinstance(experiment,str) or experiment not in REQUIRED:issue('FAIL','EXPERIMENT',at,'Unsupported experiment.');continue
  if role not in ['development','calibration','validation']:
   issue('FAIL','ROLE',at,'Unsupported split_role.');role='_invalid'
  if kind not in ['measured','published_processed','synthetic']:issue('FAIL','EVIDENCE_KIND',at,'Unsupported evidence_kind.')
  if kind=='synthetic' and role!='development':issue('FAIL','SYNTHETIC_EVIDENCE',at,'Synthetic fixtures cannot be calibration or physical-validation evidence.')
  for key in ['specimen_id','independence_group','source_series_id']:
   v=d.get(key)
   if not missing(at,key,v) and not isinstance(v,str):issue('FAIL','IDENTITY_TYPE',at+'.'+key,'Identity must be a string or null.')
  for key,registry in [('independence_group',groups),('specimen_id',cell_roles)]:
   v=d.get(key)
   if isinstance(v,str) and v:
    prior=registry.setdefault(v,set());prior.add(role)
    if 'calibration' in prior and 'validation' in prior:issue('FAIL','SPLIT_LEAKAGE',at+'.'+key,'Same specimen/independence group appears in calibration and validation.')
  source=d.get('source');ref=d.get('reference');fixture=d.get('fixture');data=d.get('csv')
  if not all(isinstance(x,dict) for x in [source,ref,fixture,data]):issue('FAIL','STRUCTURE',at,'source, reference, fixture and csv objects required.');continue
  for key in ['uri','selection','processing']:
   if not isinstance(source.get(key),str) or not source[key].strip():issue('UNDECIDED','PROVENANCE',at+'.source.'+key,'Source lineage is missing.')
  if not isinstance(source.get('file_sha256'),str) or not HASH.fullmatch(source['file_sha256']):issue('UNDECIDED','SOURCE_HASH',at,'Original source hash missing or malformed; original bytes are not verified by this tool.')
  for key in ['soc','temperature_K','thickness_m','area_m2','preload_Pa']:
   v=ref.get(key)
   if missing(at+'.reference',key,v):continue
   if not finite(v):issue('FAIL','REFERENCE_NUMBER',at+'.reference.'+key,'Finite numeric value required.')
   elif (key=='soc' and not 0<=v<=1) or (key in ['temperature_K','thickness_m','area_m2'] and v<=0) or (key=='preload_Pa' and v<0):issue('FAIL','REFERENCE_RANGE',at+'.reference.'+key,'Outside declared SI/sign bounds.')
  if d.get('displacement_sign')!='expansion_positive':issue('FAIL','SIGN',at,'displacement_sign must be expansion_positive; transform explicitly before ingestion.')
  if fixture.get('mode') not in ['constant_pressure','low_constraint','fixed_gap','elastic_constraint']:issue('FAIL','FIXTURE_MODE',at,'Unsupported fixture mode.')
  if experiment=='constant_pressure_cycling':
   if fixture.get('mode')!='constant_pressure':issue('FAIL','BOUNDARY_MISMATCH',at,'Experiment requires constant_pressure fixture.')
   p=fixture.get('nominal_pressure_Pa')
   if p is None:issue('UNDECIDED','PRESSURE',at,'Nominal pressure unknown.')
   elif not finite(p) or p<0:issue('FAIL','PRESSURE',at,'Nominal pressure must be finite and nonnegative.')
  if experiment=='free_swelling' and fixture.get('mode')!='low_constraint':issue('FAIL','BOUNDARY_MISMATCH',at,'Free swelling requires a documented low-constraint measurement.')
  if experiment=='stress_relaxation' and fixture.get('mode')!='fixed_gap':issue('FAIL','BOUNDARY_MISMATCH',at,'Stress relaxation requires fixed_gap with a verified strain hold.')
  for key in ['fixture_id','synchronization','conditioning','reference_definition']:
   missing(at+'.fixture',key,fixture.get(key))
  units=data.get('units')
  if not isinstance(units,dict):issue('FAIL','UNITS',at,'csv.units object required.');continue
  if any(k not in UNITS or units[k]!=UNITS[k] for k in units):issue('FAIL','UNIT_MISMATCH',at,'Use the declared SI canonical channels and units; no implicit conversion.')
  for ch in REQUIRED[experiment]:
   if units.get(ch)!=UNITS[ch]:issue('FAIL','MISSING_CHANNEL',at+'.csv.units','Missing canonical channel '+ch)
  path=data.get('path')
  if not isinstance(path,str) or not path:issue('FAIL','CSV_PATH',at,'Relative CSV path required.');continue
  p=(root/path).resolve()
  if Path(path).is_absolute() or not p.is_relative_to(root):issue('FAIL','PATH_ESCAPE',at,'CSV must remain within package directory.');continue
  if not p.is_file():issue('UNDECIDED','CSV_UNAVAILABLE',at,'CSV does not exist in package.');continue
  b=p.read_bytes();sha=hashlib.sha256(b).hexdigest()
  if data.get('sha256')!=sha:issue('FAIL','HASH_MISMATCH',at,'CSV SHA-256 does not match manifest.')
  try:
   reader=csv.DictReader(io.StringIO(b.decode('utf-8-sig')));headers=reader.fieldnames or [];rows=list(reader)
  except (UnicodeError,csv.Error):issue('FAIL','CSV_FORMAT',at,'Invalid UTF-8 CSV.');continue
  if len(headers)!=len(set(headers)):issue('FAIL','DUPLICATE_HEADER',at,'Duplicate CSV column names.')
  if not rows:issue('FAIL','EMPTY_CSV',at,'No data rows.');continue
  for ch in units:
   if ch not in headers:issue('FAIL','MISSING_HEADER',at,'Declared CSV channel not found: '+ch)
  for h in headers:
   if h in UNITS and h not in units:issue('FAIL','UNDECLARED_CHANNEL',at,'Canonical channel lacks units: '+h)
  if any(None in r or any(v is None for v in r.values()) for r in rows):issue('FAIL','RAGGED_CSV',at,'CSV rows must match the header width.')
  times=[];canonical=[];missing_counts={};invalid_counts={};bounds={}
  for row in rows:
   vals={}
   for ch in units:
    v=row.get(ch)
    if v is None or v.strip()=='':missing_counts[ch]=missing_counts.get(ch,0)+1;vals[ch]=None;continue
    try:fv=float(v)
    except (ValueError,TypeError):invalid_counts[ch]=invalid_counts.get(ch,0)+1;vals[ch]=None;continue
    if not math.isfinite(fv):invalid_counts[ch]=invalid_counts.get(ch,0)+1;vals[ch]=None;continue
    vals[ch]=fv
    if ch=='soc' and not 0<=fv<=1 or ch=='temperature_K' and fv<=0 or ch=='pressure_Pa' and fv<0:bounds[ch]=bounds.get(ch,0)+1
   times.append(vals.get('t_s'));canonical.append(vals)
  if missing_counts:issue('UNDECIDED','MISSING_VALUES',at,str(missing_counts))
  if invalid_counts:issue('FAIL','NONFINITE_OR_TEXT',at,str(invalid_counts))
  if bounds:issue('FAIL','CHANNEL_RANGE',at,str(bounds))
  # Never drop gaps then treat separated samples as contiguous.
  reversals=sum(a is not None and b is not None and b<a for a,b in zip(times,times[1:]));duplicates=sum(a is not None and b is not None and b==a for a,b in zip(times,times[1:]))
  if reversals:issue('FAIL','TIME_REVERSAL',at,str(reversals)+' adjacent reversals; no sorting performed.')
  if duplicates:issue('UNDECIDED','DUPLICATE_TIME',at,str(duplicates)+' equal adjacent timestamps; disambiguate acquisition order.')
  if len(rows)<2:issue('UNDECIDED','TOO_SHORT',at,'At least two samples needed for time checks.')
  canonical_sha=hashlib.sha256(json.dumps(canonical,sort_keys=True,allow_nan=False).encode()).hexdigest()
  for typ,key in [('csv_sha256',sha),('canonical_series_sha256',canonical_sha),('source_series_id',d.get('source_series_id'))]:
   if isinstance(key,str) and key:
    old=seen.get((typ,key))
    if old is not None:issue('FAIL','DUPLICATE_SERIES',at,typ+' duplicates '+old+'; deduplicate or document nonoverlapping source selections.')
    else:seen[(typ,key)]=did
  summaries.append({'dataset_id':did,'rows':len(rows),'csv_sha256':sha,'canonical_series_sha256':canonical_sha,'missing_values':missing_counts,'time_reversals':reversals,'duplicate_times':duplicates})
 return result(issues,summaries)
def result(issues,summaries):
 levels={x['level'] for x in issues};return {'validator_version':'0.1','status':'FAIL' if 'FAIL' in levels else 'UNDECIDED' if 'UNDECIDED' in levels else 'PASS','meaning':'Only implemented data-contract checks. No material approval, experiment authenticity, unit plausibility or solver validation.','physical_validation':'UNDECIDED','issues':issues,'datasets':summaries,'limits':['Original source URI/hash are recorded, not fetched or authenticated.','Metadata assertions, experiment protocols, reference choices and measurement uncertainty require human review.','Exact complete-series duplication and declared groups are checked; arbitrary overlapping subsets and transformed duplicates may evade detection.','Fixed SOC/temperature/strain holds are not automatically assessed against experiment-specific tolerances.']}
def main():
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('manifest',type=Path);p.add_argument('--output',type=Path);a=p.parse_args()
 try:
  def reject_constant(v):raise ValueError('Nonstandard JSON constant '+v)
  package=json.loads(a.manifest.read_text(),parse_constant=reject_constant);r=validate(package,a.manifest.parent)
 except (OSError,ValueError,TypeError,KeyError) as e:r=result([dict(level='FAIL',code='INPUT_ERROR',where='$',message=str(e))],[])
 text=json.dumps(r,ensure_ascii=False,indent=2,allow_nan=False)
 if a.output:
  target=a.output.resolve();protected={a.manifest.resolve()}
  if isinstance(locals().get('package'),dict):
   for d in (package.get('datasets') if isinstance(package.get('datasets'),list) else []):
    if isinstance(d,dict) and isinstance(d.get('csv'),dict) and isinstance(d['csv'].get('path'),str):protected.add((a.manifest.parent/d['csv']['path']).resolve())
  if target in protected:p.error('Output must not overwrite manifest or input CSV.')
  a.output.parent.mkdir(parents=True,exist_ok=True);a.output.write_text(text)
 else:print(text)
 return {'PASS':0,'FAIL':2,'UNDECIDED':3}[r['status']]
if __name__=='__main__':raise SystemExit(main())
