#!/usr/bin/env python3
"""Retrieve and normalise KNMI hourly station observations without filling missing data."""
from pathlib import Path
from datetime import datetime, timedelta, timezone
import argparse, hashlib, json, math, urllib.parse, urllib.request
HERE=Path(__file__).resolve().parent
URL='https://www.daggegevens.knmi.nl/klimatologie/uurgegevens'
PARAMS={'start':'20250909','end':'20250910','stns':'344','vars':'DD:FH:FF:FX:T:RH'}

def normalise(raw):
    stations={}
    records={}
    for line in raw.splitlines():
        if line.startswith('# 344 '):
            parts=line[1:].split();stations['344']={'id':344,'name':' '.join(parts[4:]),'longitude':float(parts[1]),'latitude':float(parts[2]),'altitude_m':float(parts[3])}
        if not line.strip() or line.startswith('#'):continue
        parts=[x.strip() for x in line.split(',')]
        if len(parts)!=9:raise ValueError('Unexpected KNMI column count')
        stn,date,hh,*values=parts
        if stn!='344':raise ValueError('Unexpected station')
        hour=int(hh)
        if not 1<=hour<=24:raise ValueError('Unexpected KNMI hour')
        stamp=(datetime.strptime(date,'%Y%m%d')+timedelta(hours=hour)).strftime('%Y-%m-%dT%H:%M')
        if not stamp.startswith('2025-09-10T'):continue
        if stamp in records:raise ValueError('Duplicate timestamp')
        dd,fh,ff,fx,t,rh=[int(x) if x else None for x in values]
        if rh is not None and rh < -1:raise ValueError('Invalid precipitation code')
        if any(x is not None and x<0 for x in [fh,ff,fx]):raise ValueError('Negative wind speed')
        records[stamp]={'time':stamp,'wind_direction_degrees':dd if dd not in [0,990] else None,'wind_direction_code':dd,'wind_speed_ms':None if fh is None else fh/10,'wind_last10min_ms':None if ff is None else ff/10,'gust_ms':None if fx is None else fx/10,'temperature_c':None if t is None else t/10,'precipitation_mm':None if rh is None or rh==-1 else rh/10,'precipitation_trace':rh==-1,'precipitation_raw_code':rh}
    expected=[f'2025-09-10T{h:02d}:00' for h in range(24)]
    if sorted(records)!=expected or '344' not in stations:raise ValueError('Missing station metadata or hourly timestamps')
    station=stations['344'];lat,lon=map(math.radians,[52.00884955,4.35676823]);a,b=map(math.radians,[station['latitude'],station['longitude']]);q=math.sin((a-lat)/2)**2+math.cos(lat)*math.cos(a)*math.sin((b-lon)/2)**2
    station['distance_to_ihe_km']=round(6371*2*math.atan2(math.sqrt(q),math.sqrt(1-q)),2)
    rows=[records[t] for t in expected]
    return {'provider':'KNMI','product':'Historical hourly station observations','station':station,'time_zone':'UTC','timestamp_convention':'End of interval. KNMI HH=24 maps to 00:00 UTC on the next calendar day. Window: 10 September 2025 00:00–23:00 UTC, aligned with the existing ERA5 timestamps, not a full 00:00–24:00 rainfall day.','units':{'precipitation_mm':'mm over preceding hour','wind_speed_ms':'hourly mean, m/s','gust_ms':'maximum gust in preceding hour, m/s','wind_direction_degrees':'from direction, last 10 minutes, degrees','temperature_c':'degrees Celsius at 1.50 m, instantaneous at observation time'},'trace_policy':'KNMI RH=-1 means less than 0.05 mm. Stored as null amount with a trace flag, not as negative rain or a measured zero. Visual drops omit traces; trace hours remain labelled. Missing values are null, never filled.','limitations':['One station, not a neighbourhood grid or facade observation.','Station wind is not directly comparable with computed wind at 20 m inside the neighbourhood. No validation claim.','Wind direction is a last-10-minute mean, whereas wind_speed_ms is an hourly mean.','Station relocations and changes in methods can make these series unsuitable for climate-trend analysis.','No radar rainfall field was downloaded. No new OpenFOAM or thermal run was performed.'],'source':{'url':URL,'request_method':'POST','parameters':PARAMS,'documentation':'https://www.knmi.nl/nederland-nu/klimatologie/uurgegevens','raw_sha256':hashlib.sha256(raw.encode()).hexdigest()},'records':rows}

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--raw',type=Path);args=ap.parse_args()
    raw=args.raw.read_text() if args.raw else urllib.request.urlopen(urllib.request.Request(URL,data=urllib.parse.urlencode(PARAMS).encode()),timeout=45).read().decode()
    data=normalise(raw);folder=HERE/'weather';folder.mkdir(exist_ok=True)
    (folder/'knmi-344-20250910.txt').write_text(raw)
    (folder/'knmi-hourly.json').write_text(json.dumps(data,indent=2)+'\n')
    print(json.dumps({'station':data['station'],'hours':len(data['records']),'missing_values':sum(v is None for r in data['records'] for k,v in r.items() if k not in ['wind_direction_degrees']),'traces':sum(r['precipitation_trace'] for r in data['records']),'selected_23UTC':data['records'][-1]},indent=2))
if __name__=='__main__':main()
