#!/usr/bin/env python3
"""
Ingest a state administrative course record for North Carolina, as a second source beside the FOIA replies.

  .venv-analysis/bin/python -I scripts/ingest_course_records.py              (reads data/raw/ncdpi/course_enrollment.csv if present)
  .venv-analysis/bin/python -I scripts/ingest_course_records.py --selftest   (checks the parser on in-memory rows; writes nothing)

Input schema (CSV, one row per district, course and grade):
  lea_code      three-character NC public school unit code (e.g. 390)
  school_year   e.g. 2026-27
  course_code   state course code; matched by prefix against data/audit/ncdpi_course_codes.csv
  course_title  text
  grade         6, 7 or 8
  students      integer; blank means suppressed or unknown

Coding rule, per district: True if any listed code has students > 0 in grades 6-8; False only if the district has rows for
listed codes and every one reports 0 students; otherwise missing (null). A district absent from the file is missing, not "no course".
"""
import argparse, csv, hashlib, io, json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
RAW = ROOT / 'data/raw/ncdpi/course_enrollment.csv'
CODES = ROOT / 'data/audit/ncdpi_course_codes.csv'
OUT = ROOT / 'data/processed/nc_course_records.json'
COLUMNS = ['lea_code', 'school_year', 'course_code', 'course_title', 'grade', 'students']


def parse(text, codes, psu_to_leaid):
    rd = csv.DictReader(io.StringIO(text))
    missing = [c for c in COLUMNS if c not in (rd.fieldnames or [])]
    if missing:
        raise SystemExit(f'course record file is missing columns: {missing}')
    seen, unknown = {}, set()
    for r in rd:
        if r['grade'].strip() not in ('6', '7', '8') or not any(r['course_code'].strip().upper().startswith(c) for c in codes):
            continue
        leaid = psu_to_leaid.get(r['lea_code'].strip().upper())
        if not leaid:
            unknown.add(r['lea_code'])
            continue
        n = r['students'].strip()
        seen.setdefault(leaid, []).append(int(n) if n else None)
    out = {}
    for leaid, ns in seen.items():
        out[leaid] = True if any(n and n > 0 for n in ns) else (False if all(n == 0 for n in ns) else None)
    return out, sorted(unknown)


def build():
    codes = [r['course_code_prefix'] for r in csv.DictReader(open(CODES))] if CODES.exists() else []
    districts = json.load(open(ROOT / 'story/data/districts.json'))
    psu = {str(d['psu']).upper(): d['leaid'] for d in districts}
    base = {'schema': COLUMNS, 'expected_file': 'data/raw/ncdpi/course_enrollment.csv', 'course_code_prefixes': codes, 'districts_in_scope': len(districts)}
    if not RAW.exists():
        res = {**base, 'available': False, 'status': 'No state course record on file. No public, scriptable district-by-course enrollment file for these codes was located (searched 2026-12-03; the NCDPI Statistical Profile refuses scripted requests and needs a manual export), so every district is missing on this source.', 'by_leaid': {}}
    else:
        raw = RAW.read_bytes()
        by, unknown = parse(raw.decode('utf-8-sig'), codes, psu)
        res = {**base, 'available': True, 'status': f'State course record ingested: {len(by)} districts with a listed code.', 'input_sha256': hashlib.sha256(raw).hexdigest(), 'unknown_lea_codes': unknown, 'by_leaid': by}
    OUT.write_text(json.dumps(res, indent=1, sort_keys=True))
    return res


def selftest():
    head = ','.join(COLUMNS) + '\n'
    rows = head + '390,2026-27,EY12X0,Exploring Financial Literacy,8,25\n010,2026-27,EY12,x,7,0\n020,2026-27,EY12,x,8,\n030,2026-27,ZZ99,x,8,40\n999,2026-27,EY12,x,8,1\n'
    by, unknown = parse(rows, ['EY12'], {'390': 'a', '010': 'b', '020': 'c', '030': 'd'})
    assert by == {'a': True, 'b': False, 'c': None} and unknown == ['999'], (by, unknown)
    print('parser self-test passed')


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('--selftest', action='store_true')
    if ap.parse_args().selftest:
        selftest()
    else:
        print(build()['status'])
