"""Independent medium comparisons. Python 3 standard library, MIT license.
Run: python3 media_reference.py --out media-results
Writes space.csv and termination.csv. No network or external dependencies.
Reference: ITU-R P.525-5 eq.4; MIT Electromagnetic Fields and Energy 14.6.
20 dBm source; isotropic transmitter; receive aperture fixed or isotropic.
Line: lossless, resistive load, unit peak incident voltage; steady state only.
"""
import argparse,cmath,csv,math
from pathlib import Path
C=299792458

def space(f_ghz,d_m,fixed_area):
    lam=C/(f_ghz*1e9)
    area=(C/1e9 if fixed_area else lam)**2/(4*math.pi)
    flux=.1/(4*math.pi*d_m*d_m)  # W/m^2 from 20 dBm
    return 10*math.log10(flux*area/.001)

def line(z,r,x):
    # Solve V=1+b, I=(1-b)/z, V=r I via boundary equations.
    if r is None: b=1.0; v=2.0; i=0.0; p=0.0
    else:
        i=2/(r+z);v=r*i;b=v-1;p=v*i/2
    incident=1/(2*z)
    wave=cmath.exp(2j*math.pi*x)+b*cmath.exp(-2j*math.pi*x)
    return b,v,p/incident,abs(wave)

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--out',default='media-results');args=parser.parse_args();out=Path(args.out);out.mkdir(parents=True,exist_ok=True)
    with (out/'space.csv').open('w',newline='') as f:
        w=csv.writer(f);w.writerow(['f_GHz','d_m','fixed_area','received_dBm'])
        for freq in [1,2,2.4,5,10]:
            for dist in [100,1000,2000,10000]:
                for fixed in [False,True]:w.writerow([freq,dist,int(fixed),space(freq,dist,fixed)])
    with (out/'termination.csv').open('w',newline='') as f:
        w=csv.writer(f);w.writerow(['z0','load','x_wavelength','gamma','voltage','absorbed','envelope'])
        for z in [50,75,120]:
            for r in [0,z,240,None]:
                for x in [i/20 for i in range(21)]:w.writerow([z,'open' if r is None else r,x,*line(z,r,x)])
    print('Wrote 40 free-space and 252 termination rows to',out)
if __name__=='__main__':main()
