"""Conditional table retrieval. No interpolation, thermal solver or installed acceptance."""
import json,re,math
from pathlib import Path

def load_library(path=None):
 return json.loads(Path(path or Path(__file__).with_name('c14-insulation-schedules.json')).read_text())

def select_economic_table(library,material,fuel_value,geometry='pipe-equipment'):
 if not math.isfinite(fuel_value):raise ValueError('Fuel value must be finite')
 if fuel_value<3 or fuel_value>10:raise ValueError('Fuel value outside supplied3–10 USD/MMBtu range')
 choices=[t for t in library['tables'] if t['basis']=='2012' and t['duty']=='economic' and t['material']==material and t['id'].endswith(geometry) and t['fuel_value_USD_per_MMBtu']>=fuel_value]
 if not choices:raise ValueError('Material/geometry has no matching table')
 return min(choices,key=lambda t:t['fuel_value_USD_per_MMBtu'])

def column_at(table,temp_F):
 if not math.isfinite(temp_F):raise ValueError('Temperature must be finite')
 hits=[]
 for i,label in enumerate(table['temperature_labels']):
  if table['basis']=='2001':
   # Both printed units are retained; lookup deliberately uses the printed F axis.
   vals=[float(n.replace('−','-')) for n in re.findall(r'\(\s*([-−]?\d+(?:\.\d+)?)',label)]
  else:vals=[float(n.replace('−','-')) for n in re.findall(r'[-−]?\d+(?:\.\d+)?',label)]
  if label.startswith('Ambient'):lo,hi=1,80
  elif len(vals)==2:lo,hi=sorted(vals)
  elif len(vals)==1:lo=hi=vals[0]
  else:raise ValueError('Unresolved temperature header')
  if lo<=temp_F<=hi:hits.append(i)
 if len(hits)!=1:raise ValueError('No unique printed temperature column; no interpolation or gap guessing')
 return hits[0]

def lookup(library,table_id,size_label,temp_F,*,normal_temperature_F=None,material=None):
 found=[t for t in library['tables'] if t['id']==table_id]
 if len(found)!=1:raise ValueError('Unknown or ambiguous table identity')
 t=found[0];limit=t['maximum_material_service_temperature_F']
 if t['duty']=='hold':
  if normal_temperature_F is None or not math.isfinite(normal_temperature_F):raise ValueError('HOLD lookup requires normal operating temperature for material suitability')
  check_temp=normal_temperature_F
 else:check_temp=temp_F
 if t['material']=='mineral fiber / calcium silicate':
  if material not in ['mineral fiber','calcium silicate']:raise ValueError('Personnel table requires actual selected material')
  limit=850 if material=='mineral fiber' else 1200
 if limit is not None and check_temp>limit:raise ValueError('Material service-temperature maximum exceeded')
 rows=[r for r in t['rows'] if r['size_label']==size_label]
 if len(rows)!=1:raise ValueError('Exact printed size row missing; no size interpolation')
 i=column_at(t,temp_F);cell=rows[0]['cells'][i]
 return {'table':t['id'],'basis':t['basis'],'duty':t['duty'],'size_label':size_label,'temperature_label':t['temperature_labels'][i],'cell':cell,'conditions':library['basis_conditions'][t['basis']],'notes':t['notes'],'interpretation':'Conditional schedule outcome; no installed thermal/economic acceptance'}

if __name__=='__main__':
 import argparse
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('table');p.add_argument('size');p.add_argument('temperature_F',type=float);p.add_argument('--normal-temperature-F',type=float);p.add_argument('--material');args=p.parse_args()
 print(json.dumps(lookup(load_library(),args.table,args.size,args.temperature_F,normal_temperature_F=args.normal_temperature_F,material=args.material),indent=2))
