"""Python 3.11+: preserve timestamp strings and derive UTC only with a known offset.
Usage: python iso-offset-to-csv.py input.json new-output.csv
"""
import csv,json,re,sys
from pathlib import Path
from datetime import datetime,timezone
BASE=r'[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,6})?'
def unique(pairs):
    out={}
    for k,v in pairs:
        if k in out: raise ValueError('duplicate key: '+k)
        out[k]=v
    return out
def reject_constant(value): raise ValueError('nonstandard constant: '+value)
def convert(record):
    if set(record)!={'id','created_at'} or not all(isinstance(v,str) for v in record.values()):
        raise ValueError('each record must have only string id and created_at')
    raw=record['created_at']; utc=''; status='unsupported_format'
    if re.fullmatch(BASE,raw): status='missing_offset'
    elif re.fullmatch(BASE+r'(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])',raw):
        if raw.endswith('-00:00'): status='unknown_offset'
        else:
            try:
                d=datetime.fromisoformat(raw)
                utc=d.astimezone(timezone.utc).isoformat().replace('+00:00','Z')
                status='ok'
            except (ValueError,OverflowError): status='invalid_datetime'
    return {'id':record['id'],'created_at_raw':raw,'created_at_utc':utc,'timestamp_status':status}
def main():
    data=Path(sys.argv[1]).read_bytes()
    if len(data)>2000000: raise ValueError('recipe input cap: 2000000 bytes')
    records=json.loads(data.decode('utf-8'),object_pairs_hook=unique,parse_constant=reject_constant)
    if not isinstance(records,list) or not records or not all(isinstance(r,dict) for r in records):
        raise ValueError('expected nonempty array of records')
    rows=[convert(r) for r in records]
    with Path(sys.argv[2]).open('x',encoding='utf-8',newline='') as f:
        w=csv.DictWriter(f,fieldnames=['id','created_at_raw','created_at_utc','timestamp_status'])
        w.writeheader();w.writerows(rows)
if __name__=='__main__': main()
