"""MIT. Independent saved-shell integration; no Cloudy/library/atomic table bundled."""
import argparse
import hashlib
import json
import math
from decimal import Decimal,localcontext,ROUND_FLOOR,ROUND_CEILING
from pathlib import Path

PI_LO=Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899')
PI_HI=Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620900')
LABELS=['H1-Hbeta','H1-Halpha','CaB-Hbeta','CaB-Halpha']

def directed(operation,rounding):
    with localcontext() as context:
        context.prec=70;context.rounding=rounding;return operation()

def token_bounds(token):
    value=Decimal(token);place=Decimal(10)**value.as_tuple().exponent;half=place/2
    return max(Decimal(0),value-half),value+half

def numeric_lines(path):
    lines=path.read_text().splitlines();return [line.split() for line in lines if line.strip() and not line.lstrip().startswith('#')]

def integrate(folder):
    radial=folder/'first.rad';emission=folder/'first.emis'
    if not radial.read_text().splitlines()[0].startswith('#NZONE\tradius\tdepth\tdr'):
        raise ValueError('Expected named C25 radius/depth/dr save columns')
    header=emission.read_text().splitlines()[0]
    if not all(label in header for label in ['4861.32A','6562.80A','Ca B']):raise ValueError('Missing named line columns')
    radii=numeric_lines(radial);values=numeric_lines(emission)
    if not radii or len(radii)!=len(values):raise ValueError('Empty or mismatched saved zones')
    point=[0.]*4;bounds=[[Decimal(0),Decimal(0)] for _ in LABELS]
    with localcontext() as context:
        context.prec=70
        for index,(row,emis) in enumerate(zip(radii,values),1):
            if len(row)!=4 or len(emis)!=5 or int(row[0])!=index:raise ValueError('Unexpected zone schema/order')
            radius,width=float(row[1]),float(row[3])
            if not math.isfinite(radius+width) or width<=0 or radius<width/2:raise ValueError('Invalid shell geometry')
            # Both saves are midpoint depth coordinates but have different print precision.
            dlo,dhi=token_bounds(row[2]);elo,ehi=token_bounds(emis[0])
            if max(dlo,elo)>min(dhi,ehi):raise ValueError('Depth print intervals do not overlap')
            rlo,rhi=token_bounds(row[1]);wlo,whi=token_bounds(row[3])
            volume=4*math.pi*(radius*radius*width+width**3/12)
            vlo=directed(lambda:4*PI_LO*(rlo*rlo*wlo+wlo**3/12),ROUND_FLOOR)
            vhi=directed(lambda:4*PI_HI*(rhi*rhi*whi+whi**3/12),ROUND_CEILING)
            for line,token in enumerate(emis[1:]):
                eta=float(token)
                if not math.isfinite(eta) or eta<0:raise ValueError('Non-finite or negative energy emissivity')
                low,high=token_bounds(token);point[line]+=eta*volume
                bounds[line][0]=directed(lambda:bounds[line][0]+low*vlo,ROUND_FLOOR)
                bounds[line][1]=directed(lambda:bounds[line][1]+high*vhi,ROUND_CEILING)
    return {'scope':'Saved-zone energy-volume integration only; not charge/source/diffuse or full-grid certification',
        'zones':len(radii),'units':{'radius':'cm','emissivity':'erg cm^-3 s^-1','luminosity':'erg s^-1'},
        'files':{path.name:{'bytes':path.stat().st_size,'sha256':hashlib.sha256(path.read_bytes()).hexdigest()} for path in [radial,emission]},
        'lines':{name:{'pointErgPerS':point[i],'roundingIntervalErgPerS':[str(x) for x in bounds[i]]} for i,name in enumerate(LABELS)},
        'intervalMeaning':'Independent per-token half-last-place enclosure; positive midpoint-shell volume polynomial, directed70-digit arithmetic and explicit pi bracket. Printed-model enclosure, not formal atomic/physical certification.',
        'newNativeRuns':0,'newHttpBytes':0}

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--model-dir',required=True,type=Path);parser.add_argument('--output',type=Path,default=Path('results/native-integral.json'));args=parser.parse_args()
    result=integrate(args.model_dir);args.output.parent.mkdir(parents=True,exist_ok=True);args.output.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))

if __name__=='__main__':main()
