"""STAT-01: recompute units, missingness and denominators from actual source records.

Run beside the supplied data folders; Python standard library only.
The local archived Palmer/SEC originals are preferred. A public package lacking
these archives uses the explicitly identified actual-data CSV fallback, not case
JSON or a precomputed results table. No input observations are overwritten.
"""
from pathlib import Path
from fractions import Fraction as Q
from decimal import Decimal, localcontext
from html.parser import HTMLParser
from collections import Counter
import csv, hashlib, html, json, re

ROOT = Path(__file__).resolve().parent
WORKSPACE = ROOT.parents[1]
DATA = ROOT / 'stats01-sources'
COMMON = ROOT / '\uC2E4\uC81C\uB370\uC774\uD130'
METRICS, FRACTIONS, AUDIT = {}, {}, []
CHECKS = {'sourceCellComparisons': 0, 'selectedCellComparisons': 0}

def read(path):
    with path.open(encoding='utf-8-sig', newline='') as stream:
        return list(csv.DictReader(stream))

def snapshot(path, purpose, original):
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    AUDIT.append({'file': str(path.relative_to(ROOT)) if path.is_relative_to(ROOT) else str(path.relative_to(WORKSPACE)),
                  'purpose': purpose, 'sha256': digest, 'archivedOriginalUsed': original})
    return digest

def normalize(value):
    return '' if value in ('NA', '') else value

def same(a, b, numeric=False):
    a, b = normalize(a), normalize(b)
    return a == b if not a or not b or not numeric else Q(a) == Q(b)

def metric(key, value):
    METRICS[key] = float(value)
    if isinstance(value, Q): FRACTIONS[key] = str(value)

def assert_value(actual, expected, name):
    assert actual == expected, (name, actual, expected)

wb_path = COMMON / 'worldbank.csv'
wb = read(wb_path); snapshot(wb_path, 'actual retained World Bank country-years', False)
keys = [(r['country'], r['year']) for r in wb]
countries = set(r['country'] for r in wb)
years = sorted(set(int(r['year']) for r in wb))
counts = Counter(r['country'] for r in wb)
assert len(wb) == len(set(keys)) == 720
assert years == list(range(1980, 2025)) and set(counts.values()) == {45}
for name, value in {'country_rows': len(wb), 'country_unique_keys': len(set(keys)),
                    'country_distinct': len(countries), 'country_year_count': len(years),
                    'country_first_year': min(years), 'country_last_year': max(years)}.items(): metric(name, value)
for variable in ['gdp_pc', 'life_expectancy', 'population', 'unemployment']:
    available = sum(bool(r[variable]) for r in wb)
    metric('country_' + variable + '_available', available)
    metric('country_' + variable + '_missing', len(wb) - available)
missing_gdp = [(r['country'], int(r['year'])) for r in wb if not r['gdp_pc']]
assert missing_gdp == [('VNM', year) for year in range(1980, 1984)]
cross = [r for r in wb if r['year'] == '2024']
korea = [r for r in wb if r['country'] == 'KOR' and 2014 <= int(r['year']) <= 2024]
metric('country_2024_rows', len(cross))
metric('country_2024_GDP_available', sum(bool(r['gdp_pc']) for r in cross))
metric('country_KOR_2014_2024_rows', len(korea))
selected_wb_path = DATA / 'worldbank-country-year-units-and-original-missing-values.csv'
selected_wb = read(selected_wb_path); snapshot(selected_wb_path, 'selected teaching CSV checked against common actual data', False)
assert len(selected_wb) == len(wb)
for actual, selected in zip(wb, selected_wb):
    for a, b in [('gdp_pc', 'reported_GDPpc_constant2015USD_per_person'),
                 ('life_expectancy', 'reported_life_expectancy_years'),
                 ('population', 'reported_population_persons'),
                 ('unemployment', 'reported_unemployment_percent')]:
        assert same(actual[a], selected[b], True); CHECKS['selectedCellComparisons'] += 1
    assert selected['record_key'] == actual['country'] + '|' + actual['year']
    assert selected['GDPpc_observed'] == str(bool(actual['gdp_pc']))
    assert selected['selected_2024_cross_section'] == str(actual['year'] == '2024')
    assert selected['is_independent_country_claim'] == 'False'
    CHECKS['selectedCellComparisons'] += 4

pg_common_path = COMMON / 'penguins.csv'
pg_archive = WORKSPACE / 'work' / 'textbooks-2026' / 'raw' / 'penguins.csv'
pg_input = pg_archive if pg_archive.is_file() else pg_common_path
pg = read(pg_input); snapshot(pg_input, 'actual Palmer measurements; original archive preferred', pg_input == pg_archive)
pg_common = read(pg_common_path); snapshot(pg_common_path, 'retained actual Palmer measurements', False)
numeric = ['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g', 'year']
source_columns = ['species', 'island', 'bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g', 'sex', 'year']
assert len(pg) == len(pg_common) == 344
for i, (actual, common) in enumerate(zip(pg, pg_common), 1):
    assert int(common['row_id']) == i
    for key in source_columns:
        assert same(actual[key], common[key], key in numeric)
        CHECKS['sourceCellComparisons'] += 1
measurements = numeric[:4]
mass = [Q(r['body_mass_g']) for r in pg if normalize(r['body_mass_g'])]
known_sex = [r for r in pg if normalize(r['sex'])]
complete4 = [r for r in pg if all(normalize(r[key]) for key in measurements)]
complete4sex = [r for r in complete4 if normalize(r['sex'])]
missing_ids = [i for i, r in enumerate(pg, 1) if not normalize(r['body_mass_g'])]
assert missing_ids == [4, 272]
for key, value in {'penguin_rows': len(pg), 'penguin_mass_available': len(mass),
                   'penguin_mass_missing': len(pg) - len(mass),
                   'penguin_sex_available': len(known_sex),
                   'penguin_sex_missing': len(pg) - len(known_sex),
                   'penguin_four_measurements_available': len(complete4),
                   'penguin_four_measurements_and_sex_available': len(complete4sex),
                   'penguin_mass_sum_g': sum(mass),
                   'penguin_mass_mean_g': sum(mass) / len(mass),
                   'penguin_mass_mean_kg': sum(mass) / len(mass) / 1000,
                   'penguin_incorrect_zero_denominator_mean_g': sum(mass) / len(pg)}.items(): metric(key, value)
for species, count in Counter(r['species'] for r in pg).items(): metric('penguin_species_' + species + '_records', count)
for year, count in Counter(r['year'] for r in pg).items(): metric('penguin_year_' + year + '_records', count)
selected_pg_path = DATA / 'palmer-actual-measurements-and-availability-flags.csv'
selected_pg = read(selected_pg_path); snapshot(selected_pg_path, 'selected Palmer teaching CSV verified cell by cell', False)
assert len(selected_pg) == len(pg)
for i, (actual, selected) in enumerate(zip(pg, selected_pg), 1):
    assert int(selected['row_id']) == i
    for key in source_columns:
        assert same(actual[key], selected[key], key in numeric); CHECKS['selectedCellComparisons'] += 1
    for key, value in {'body_mass_observed': bool(normalize(actual['body_mass_g'])),
                        'sex_observed': bool(normalize(actual['sex'])),
                        'four_size_measurements_observed': all(normalize(actual[k]) for k in measurements)}.items():
        assert selected[key] == str(value); CHECKS['selectedCellComparisons'] += 1

class Tables(HTMLParser):
    def __init__(self): super().__init__(); self.tables = []; self.stack = []; self.row = None; self.cell = None
    def handle_starttag(self, tag, attrs):
        if tag == 'table': self.stack.append([])
        elif tag == 'tr' and self.stack: self.row = []
        elif tag in ('td', 'th') and self.row is not None: self.cell = []
    def handle_data(self, value):
        if self.cell is not None: self.cell.append(value)
    def handle_endtag(self, tag):
        if tag in ('td', 'th') and self.cell is not None:
            self.row.append(' '.join(' '.join(self.cell).split())); self.cell = None
        elif tag == 'tr' and self.row is not None:
            self.stack[-1].append(self.row); self.row = None
        elif tag == 'table' and self.stack: self.tables.append(self.stack.pop())

sec_archive = WORKSPACE / 'work' / 'textbook-rewrite-2026' / 'source-audit-math08' / 'apple-2024.html'
selected_apple_path = DATA / 'apple-category-fiscal-year-actual-observations.csv'
selected_apple = read(selected_apple_path)
snapshot(selected_apple_path, 'public actual Apple category-year values; also checked against SEC when local archive exists', False)
categories = ['iPhone', 'Mac', 'iPad', 'Wearables, Home and Accessories', 'Services']
sales = {}
if sec_archive.is_file():
    snapshot(sec_archive, 'actual official SEC HTML archive', True)
    text = sec_archive.read_text(encoding='utf-8')
    parser = Tables(); parser.feed(text)
    candidates = [t for t in parser.tables if any(r and r[0] == 'iPhone' for r in t)]
    assert len(candidates) >= 1
    for category in categories:
        matches = []
        for t in candidates:
            rows = [r for r in t if r and re.sub(r'\s*\(\d+\)$', '', r[0]) == category]
            if rows:
                numbers = [int(c.replace(',', '')) for c in rows[0][1:] if re.fullmatch(r'\d{1,3}(?:,\d{3})+', c)]
                assert len(numbers) == 3
                matches.append(tuple(numbers))
        assert matches and len(set(matches)) == 1
        for year, value in zip([2024, 2023, 2022], matches[0]): sales[(year, category)] = value
    plain = re.sub(r'\s+', ' ', html.unescape(re.sub(r'<[^>]+>', ' ', text)))
    assert re.search(r'2024 and 2022 spanned\s+52\s+weeks each', plain)
    assert re.search(r'2023 spanned\s+53\s+weeks', plain)
else:
    # This fallback contains source observations, not the computed case JSON.
    for row in selected_apple: sales[(int(row['fiscal_year']), row['category'])] = int(row['reported_net_sales_million_nominal_USD'])
assert len(selected_apple) == 10
for row in selected_apple:
    year = int(row['fiscal_year'])
    assert int(row['reported_net_sales_million_nominal_USD']) == sales[(year, row['category'])]
    assert int(row['weeks_in_fiscal_year']) == (53 if year == 2023 else 52)
    assert row['transaction_or_customer_record'] == 'False' and row['independent_company_count'] == '1'
    CHECKS['selectedCellComparisons'] += 4
for key, value in {'company_count': len(set(r['company'] for r in selected_apple)),
                   'company_category_year_records': len(selected_apple),
                   'company_categories': len(set(r['category'] for r in selected_apple)),
                   'company_matched_category_pairs': len(categories)}.items(): metric(key, value)
for year in [2023, 2024]:
    values = [Q(sales[(year, category)]) for category in categories]
    metric(f'company_FY{year}_net_sales_million_USD', sum(values))
    metric(f'company_FY{year}_fiscal_weeks', 53 if year == 2023 else 52)
    metric(f'company_FY{year}_mean_category_net_sales_million_USD', sum(values) / len(values))
metric('company_total_nominal_sales_change_million_USD', sum(sales[(2024, c)] - sales[(2023, c)] for c in categories))
assert_value(METRICS['country_gdp_pc_available'], 716, 'GDP valid denominator')
assert_value(METRICS['country_unemployment_available'], 544, 'modeled ILO availability')
assert_value(METRICS['penguin_mass_available'], 342, 'mass valid denominator')
assert_value(METRICS['penguin_mass_sum_g'], 1437000, 'actual mass sum')
assert_value(METRICS['company_FY2024_net_sales_million_USD'], 391035, 'actual category total')

audit_rows = read(DATA / 'analysis-unit-and-denominator-audit.csv')
snapshot(DATA / 'analysis-unit-and-denominator-audit.csv', 'denominator audit assertions', False)
expected_audit = [(720,716,4),(720,544,176),(16,16,0),(344,342,2),(344,333,11),(344,342,2),(344,333,11),(10,10,0)]
assert len(audit_rows) == len(expected_audit)
for row, values in zip(audit_rows, expected_audit):
    assert tuple(int(row[k]) for k in ['total_rows','valid_value_rows','missing_value_rows']) == values
    assert row['zero_imputed'] == 'False'; CHECKS['selectedCellComparisons'] += 4

r_path = ROOT / 'stat01-r-results.csv'
if r_path.is_file():
    r_values = {r['metric']: float(r['value']) for r in read(r_path)}
    assert set(r_values) == set(METRICS), (set(r_values) ^ set(METRICS))
    for key, value in METRICS.items(): assert abs(r_values[key]-value) <= 1e-10 * max(1, abs(value)), (key, r_values[key], value)
    CHECKS['RmetricComparisons'] = len(METRICS)
else: CHECKS['RmetricComparisons'] = 0
for entry in AUDIT:
    path = ROOT / entry['file']
    if not path.is_file(): path = WORKSPACE / entry['file']
    assert hashlib.sha256(path.read_bytes()).hexdigest() == entry['sha256']
CHECKS['inputHashesPreserved'] = len(AUDIT)
result = {'chapter':'STAT-01', 'metrics':METRICS, 'exactFractions':FRACTIONS,
          'inputAudit':AUDIT, 'checks':CHECKS,
          'interpretation':'Record availability is not independent sampling. Published unemployment is modeled ILO data; missing values are not zero. The incorrect denominator result is an explicitly labeled error demonstration. Apple aggregates are one company, not customers or transactions.'}
(ROOT/'stat01-results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False)+'\n', encoding='utf-8')
print('STAT-01:',len(METRICS),'numeric metrics; original/common data and selected CSV checks passed. R comparisons:',CHECKS['RmetricComparisons'])
