"""Fixed-schema example: integer strings, explicit units, separate UTC column.
python epoch-json-to-csv.py epoch-sample.json new-output.csv
"""
import csv,json,re,sys
from pathlib import Path
from datetime import datetime,timedelta,timezone

EPOCH=datetime(1970,1,1,tzinfo=timezone.utc)
def derived(raw,unit):
    if unit not in ('seconds','milliseconds'):
        return '', 'unit_unresolved'
    if not isinstance(raw,str) or not re.fullmatch(r'[+-]?[0-9]+',raw):
        return '', 'integer_string_required'
    try:
        number=int(raw)
        delta=timedelta(seconds=number) if unit=='seconds' else timedelta(milliseconds=number)
        stamp=EPOCH+delta
        return stamp.isoformat(timespec='milliseconds').replace('+00:00','Z'), 'converted'
    except (ValueError,OverflowError):
        return '', 'out_of_range'

def export(source,target):
    rows=json.loads(Path(source).read_text(encoding='utf-8'))
    if not isinstance(rows,list) or not rows:
        raise ValueError('expected a nonempty array')
    for row in rows:
        if not isinstance(row,dict) or set(row)!={'id','epoch','unit'}:
            raise ValueError('exactly id, epoch and unit required')
        if not isinstance(row['id'],str) or not isinstance(row['epoch'],str):
            raise ValueError('id and epoch must be strings')
        if row['unit'] is not None and not isinstance(row['unit'],str):
            raise ValueError('unit must be text or null')
    count=0;unresolved=0
    with Path(target).open('x',encoding='utf-8',newline='') as file:
        writer=csv.writer(file)
        writer.writerow(['id','epoch_raw','epoch_unit','utc_iso','conversion_status'])
        for row in rows:
            iso,status=derived(row['epoch'],row['unit'])
            writer.writerow([row['id'],row['epoch'],row['unit'] or '',iso,status])
            count+=1;unresolved+=status!='converted'
    return {'records':count,'columns':5,'converted':count-unresolved,'unresolved':unresolved}
if __name__=='__main__':
    print(json.dumps(export(*sys.argv[1:3])))
