#!/usr/bin/env python3
"""Build data table from captured CDC DHDS response, no network or packages."""
import csv
import json
from pathlib import Path

source_directory = Path(__file__).resolve().parent
raw_records = json.loads(
    (source_directory / 'source-dhds-2022.json').read_text(encoding='utf-8')
)
allowed_locations = set(
    'AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN '
    'MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA '
    'WA WV WI WY DC US'.split()
)
selected_records = [
    record for record in raw_records
    if record['locationabbr'] in allowed_locations
]
assert len(selected_records) == 52
assert len({record['locationabbr'] for record in selected_records}) == 52

measure_fields = (
    'year', 'indicatorid', 'responseid', 'datavaluetypeid', 'stratificationid1'
)
value_fields = ('data_value', 'low_confidence_limit', 'high_confidence_limit')
for record in selected_records:
    assert tuple(record[field] for field in measure_fields) == (
        '2022', 'STATTYPE', 'Q6COG', 'AGEADJPREV', 'BO1'
    )
    assert all(record.get(field) not in (None, '') for field in value_fields)
    assert (
        float(record['low_confidence_limit'])
        <= float(record['data_value'])
        <= float(record['high_confidence_limit'])
    )

selected_records.sort(
    key=lambda record: (record['locationabbr'] != 'US', record['locationdesc'])
)
csv_fields = [
    'locationabbr', 'locationdesc', 'data_value', 'low_confidence_limit',
    'high_confidence_limit', 'number', 'weightednumber', 'rowid'
]
with (source_directory / 'cognitive-difficulty-2022.csv').open(
    'w', newline='', encoding='utf-8'
) as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=csv_fields)
    writer.writeheader()
    writer.writerows(
        {field: record.get(field, '') for field in csv_fields}
        for record in selected_records
    )

table_lines = [
    '| Location | Age-adjusted estimate (%) | 95% CI (%) |',
    '|---|---:|---:|'
]
for record in selected_records:
    table_lines.append(
        f"| {record['locationdesc']} | {record['data_value']} | "
        f"{record['low_confidence_limit']}–{record['high_confidence_limit']} |"
    )
(source_directory / 'table.md').write_text(
    '\n'.join(table_lines) + '\n', encoding='utf-8'
)
print(
    f'Generated {len(selected_records)} rows: US and territories combined, '
    '50 states and DC; no suppressed/missing estimates.'
)
