#!/usr/bin/env python3
"""Reproduce display values and CSV from the transcribed BLS published tables.
No external dependencies or network calls. Run beside data.json.
This is NOT a microdata estimator; the source estimates are supplied by BLS.
"""
from pathlib import Path
from decimal import Decimal, ROUND_HALF_UP
import csv, json
ROOT = Path(__file__).resolve().parent

def minutes(hours):
    return int((Decimal(str(hours)) * 60).quantize(Decimal('1'), rounding=ROUND_HALF_UP))

def duration(hours):
    n = minutes(hours)
    return f'{n // 60}h {n % 60:02d}m'

def main():
    d=json.loads((ROOT/'data.json').read_text())
    rows=[('overall',d['overall'])]+[(group,row) for group in ['ages','households','day_types'] for row in d[group]]
    fields=['group','label','age_base','awake_hours','alone_hours','others_present_hours','information_not_collected_hours','alone_display','source']
    with (ROOT/'time-alone-2025.csv').open('w',newline='') as f:
        writer=csv.DictWriter(f,fieldnames=fields);writer.writeheader()
        for group,row in rows:
            assert abs(sum(row[k] for k in ['alone','others','unknown'])-row['awake']) < .011
            writer.writerow(dict(group=group,label=row['label'],age_base=row.get('base','Age 15+'),awake_hours=f"{row['awake']:.2f}",alone_hours=f"{row['alone']:.2f}",others_present_hours=f"{row['others']:.2f}",information_not_collected_hours=f"{row['unknown']:.2f}",alone_display=duration(row['alone']),source=d['source_a9' if group=='households' else 'source_a8']))
    print(json.dumps({'rows':len(rows),'overall_alone':duration(d['overall']['alone']),'weekday_minus_weekend_minutes':minutes(Decimal(str(d['day_types'][0]['alone']))-Decimal(str(d['day_types'][1]['alone']))),'living_alone_minus_with_children_minutes':minutes(Decimal(str(d['households'][0]['alone']))-Decimal(str(d['households'][2]['alone'])))},indent=2))
if __name__=='__main__':main()
