"""Frozen, bounded research acquisition only; never an application network path."""
from pathlib import Path
import csv
import datetime as dt
import hashlib
import io
import json
import math
import os
import re
import sys
import time
import urllib.parse
import urllib.request

ROOT=Path.cwd().resolve();OUT=ROOT/'build/observer-sweep-20261104'
sys.path.insert(0,str(ROOT/'tools'))
import validate_ephemeris as helper
from validate_precision_window import source_hashes

sha=lambda raw:hashlib.sha256(raw).hexdigest()
now=lambda:dt.datetime.now(dt.timezone.utc).isoformat()
def write_json(path,value):
    with path.open('x',encoding='utf-8',newline='\n') as stream:json.dump(value,stream,indent=2,allow_nan=False);stream.write('\n')

def prepare():
    OUT.mkdir()
    original=ROOT/'tests/fixtures/horizons-observer-20261103'
    sources={}
    for name,code in helper.BODIES.items():
        text=(original/('boston-'+name.lower()+'.txt')).read_text(encoding='utf-8')
        match=re.findall(r'^Target body name:[^\n]*\('+code+r'\)\s+\{source: ([^}]+)\}',text,re.M)
        if len(match)!=1:raise ValueError('retained target source unavailable')
        sources[name]=match[0]
    queries=[]
    for label,when,lat,lon,elev in helper.CASES:
        epochs=[when.replace(month=month,day=15) for month in range(1,13)]
        for name,code in helper.BODIES.items():
            params=dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(helper.horizons_request_url(code,epochs[0],lat,lon,elev)).query))
            jds=[epoch.timestamp()/86400+2440587.5 for epoch in epochs]
            params['TLIST']=' '.join("'"+format(jd,'.12f')+"'" for jd in jds)
            params['QUANTITIES']="'2,4,20,49'"
            url='https://ssd.jpl.nasa.gov/api/horizons.api?'+urllib.parse.urlencode(params,quote_via=urllib.parse.quote)
            queries.append({'id':label.lower()+'-'+name.lower(),'site':label,'body':name,'target':code,
                'target_source':sources[name],'latitude_deg':lat,'longitude_east_deg':lon,'elevation_m':elev,
                'epochs_utc':[epoch.isoformat() for epoch in epochs],'epochs_jd_utc':jds,'request_url':url})
    script=Path(__file__).read_bytes()
    (OUT/'query-helper.py.txt').write_bytes(script)
    (OUT/'query-provider.py.txt').write_bytes((ROOT/'tools/validate_ephemeris.py').read_bytes())
    plan={'schema_version':'observer-seasonal-plan.v1','frozen_at_utc':now(),
          'scope':'Four existing observer sites, 12 monthly 2026 epochs each, nine bodies. New sampled observer characterization only.',
          'limitations':'No continuous/full-span/visibility/navigation or event-time guarantee; future EOP rows remain predictions.',
          'api_documentation':'https://ssd-api.jpl.nasa.gov/doc/horizons.html#tlist-parameter',
          'quantities':[2,4,20,49],'calendar':'Gregorian','time_type':'UT','refraction':'AIRLESS',
          'acceptance':{'sun_planet_arcsec':10.0,'moon_arcsec':12.0,'dut1_seconds':0.003,
                        'range_absolute_floor_km':1.0,'range_relative':1e-5,'au_km':149597870.7},
          'transport':{'queries':36,'attempts_per_query':1,'timeout_seconds':40,'maximum_bytes_per_response':160000,
                       'serial_pacing_seconds':0.3,'https_same_origin_redirects_only':True},
          'helper_sha256':sha(script),'provider_sha256':sha((ROOT/'tools/validate_ephemeris.py').read_bytes()),
          'native_source_sha256':source_hashes(),'queries':queries}
    if len(queries)!=36 or sum(len(q['epochs_utc']) for q in queries)!=432:raise ValueError('incomplete frozen matrix')
    write_json(OUT/'predeclared-plan.json',plan)
    print(json.dumps({'queries':36,'observations':432,'plan_sha256':sha((OUT/'predeclared-plan.json').read_bytes())}),flush=True)

class SameOrigin(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,req,fp,code,msg,headers,newurl):
        if urllib.parse.urlsplit(newurl).scheme!='https' or urllib.parse.urlsplit(newurl).netloc!='ssd.jpl.nasa.gov':
            raise ValueError('unexpected scientific acquisition redirect')
        return super().redirect_request(req,fp,code,msg,headers,newurl)

def verify_response(raw,q):
    text=raw.decode('utf-8')
    if not 0<len(raw)<=160000:raise ValueError('response byte bound')
    versions=re.findall(r'^API VERSION: ([^\n]+)',text,re.M)
    if len(versions)!=1 or versions[0] not in ('1.2','1.3') or not text.startswith('API VERSION: '+versions[0]+'\nAPI SOURCE: NASA/JPL Horizons API\n'):
        raise ValueError('unknown API identity')
    for label,target,source in [('Target',q['target'],q['target_source']),('Center','399','DE441')]:
        values=re.findall(r'^'+label+r' body name:[^\n]*\((\d+)\)\s+\{source: ([^}]+)\}',text,re.M)
        if values!=[(target,source)]:raise ValueError('target/origin/source changed: '+str(values))
    sites=re.findall(r'^Center geodetic\s*:\s*([^{}\n]+)\{E-lon\(deg\),Lat\(deg\),Alt\(km\)\}',text,re.M)
    expected=[q['longitude_east_deg']%360,q['latitude_deg'],q['elevation_m']/1000]
    if len(sites)!=1 or list(map(float,sites[0].split(',')))!=expected:raise ValueError('observer identity changed')
    if re.findall(r'^Atmos refraction:\s+([^\n]+)',text,re.M)!=['NO (AIRLESS)'] \
            or not re.search(r'^Units conversion:\s+1 au=\s*149597870\.700 km,',text,re.M):raise ValueError('quantity scope changed')
    headers=[next(csv.reader([line])) for line in text.splitlines() if line.startswith('Date_________JDUT')]
    expected_header=['Date_________JDUT','','','R.A.__(a-app)','DEC___(a-app)','Azimuth_(a-app)','Elevation_(a-app)','delta','deldot','UT1-UTC','']
    if len(headers)!=1 or [x.strip() for x in headers[0]]!=expected_header:raise ValueError('quantity layout changed: '+str(headers))
    if text.count('$$SOE')!=1 or text.count('$$EOE')!=1 or text.index('$$SOE')>text.index('$$EOE'):raise ValueError('ephemeris block changed')
    rows=list(csv.reader(io.StringIO(text.split('$$SOE')[1].split('$$EOE')[0].strip()),strict=True))
    if len(rows)!=12:raise ValueError('monthly epoch matrix incomplete')
    parsed=[]
    numeric=r'[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[Ee][+-]?\d+)?'
    for row,jd in zip(rows,q['epochs_jd_utc']):
        if len(row)!=11 or row[-1].strip() or any(re.fullmatch(numeric,x.strip()) is None for x in [row[0],*row[3:10]]):raise ValueError('malformed row')
        epoch,*values=map(float,[row[0],*row[3:10]])
        if not all(math.isfinite(x) for x in [epoch,*values]) or abs(epoch-jd)>1e-9:raise ValueError('nonfinite/incorrect epoch')
        ra,dec,az,alt,distance,rate,dut1=values
        if not(0<=ra<=360 and -90<=dec<=90 and 0<=az<=360 and -90<=alt<=90 and distance>0 and abs(dut1)<=.9):raise ValueError('invalid quantity domain')
        parsed.append({'jd_utc':epoch,'ra_deg':ra%360,'dec_deg':dec,'az_deg':az%360,'alt_deg':alt,
                       'observer_range_km':distance*149597870.7,'range_rate_km_s':rate,'dut1_seconds':dut1})
    return versions[0],parsed

def acquire():
    plan= json.loads((OUT/'predeclared-plan.json').read_bytes())
    if sha(Path(__file__).read_bytes())!=plan['helper_sha256'] or source_hashes()!=plan['native_source_sha256'] \
            or sha((ROOT/'tools/validate_ephemeris.py').read_bytes())!=plan['provider_sha256']:raise ValueError('source drift after freeze')
    response_dir=OUT/'responses';response_dir.mkdir()
    progress={'schema_version':'observer-seasonal-acquisition.v1','status':'running','pid':os.getpid(),'started_at_utc':now(),
              'plan_sha256':sha((OUT/'predeclared-plan.json').read_bytes()),'records':[]}
    opener=urllib.request.build_opener(SameOrigin())
    try:
        for q in plan['queries']:
            request=urllib.request.Request(q['request_url'],headers={'User-Agent':'Sol bounded scientific reference validation'})
            with opener.open(request,timeout=40) as response:raw=response.read(160001)
            path=response_dir/(q['id']+'.txt')
            with path.open('xb') as stream:stream.write(raw)
            version,rows=verify_response(raw,q)
            record={'id':q['id'],'request_url':q['request_url'],'path':'responses/'+path.name,'bytes':len(raw),
                    'sha256':sha(raw),'api_version':version,'acquired_at_utc':now(),'rows':rows}
            progress['records'].append(record)
            (OUT/'progress.json').write_text(json.dumps(progress,indent=2,allow_nan=False)+'\n',encoding='utf-8')
            print(json.dumps({'completed':len(progress['records']),'query':q['id'],'bytes':len(raw)}),flush=True)
            time.sleep(.3)
        if source_hashes()!=plan['native_source_sha256']:raise ValueError('native source drift during acquisition')
        if len({r['api_version'] for r in progress['records']})!=1:raise ValueError('API version changed within acquisition')
        progress.update(status='captured_not_qualified',finished_at_utc=now())
    except Exception as exc:
        progress.update(status='failed',error=repr(exc),finished_at_utc=now());raise
    finally:
        write_json(OUT/'acquisition.json',progress)

if __name__=='__main__':
    if sys.argv[1:] == ['prepare']:prepare()
    elif sys.argv[1:] == ['acquire']:acquire()
    else:raise SystemExit('choose prepare or acquire; acquisition is bounded public reference research only')
