"""MATH-03: set operations, counterexamples and missingness.
실행: python math03-reproduce.py / Run with standard-library Python.
The universe is explicitly the set of rows with recorded mass.
"""
from pathlib import Path
import csv, json

ROOT=Path(__file__).resolve().parent
with (ROOT/'실제데이터/penguins.csv').open(encoding='utf-8-sig',newline='') as f:
    rows=list(csv.DictReader(f))
missing=[int(r['row_id']) for r in rows if r['body_mass_g'].strip()=='']
known={int(r['row_id']):r for r in rows if r['body_mass_g'].strip()!=''}
U=set(known)
def evaluate(species,threshold):
    A={i for i,r in known.items() if r['species']==species}
    B={i for i,r in known.items() if float(r['body_mass_g'])>=threshold}
    Ac,Bc=U-A,U-B
    # Verify identities as row-number sets, not just matching counts.
    assert U-(A&B)==Ac|Bc
    assert U-(A|B)==Ac&Bc
    assert len(A|B)==len(A)+len(B)-len(A&B)
    assert (A&B)|(A-B)|(B-A)|(U-(A|B))==U
    return dict(A=len(A),B=len(B),both=len(A&B),aOnly=len(A-B),bOnly=len(B-A),
                neither=len(U-(A|B)),union=len(A|B),exactlyOne=len(A^B),
                firstPimpliesQCounterexample=min(A-B) if A-B else None,
                firstQimpliesPCounterexample=min(B-A) if B-A else None)

main=evaluate('Adelie',4000)
assert len(U)==342 and missing==[4,272]
assert [main[k] for k in ['both','aOnly','bOnly','neither']]==[39,112,138,53]
assert main['union']==289 and main['exactlyOne']==250
gentoo_bad=[i for i,r in known.items() if r['species']=='Gentoo' and float(r['body_mass_g'])<4000]
assert min(gentoo_bad)==193
empty=[r for r in known.values() if float(r['body_mass_g'])>=7000]
assert len(empty)==0
# Universal truth over an empty selection supplies no observed witness.
empty_all=all(float(r['body_mass_g'])>=4000 for r in empty)
empty_exists=any(float(r['body_mass_g'])>=4000 for r in empty)
assert empty_all is True and empty_exists is False
for species in ['Adelie','Chinstrap','Gentoo']:
    for threshold in [0,3750,4000,4500,7000]:
        evaluate(species,threshold)

result=dict(rows=len(rows),universe=len(U),missingRowIds=missing,main=main,
            gentooCounterexampleRow=min(gentoo_bad),
            assignment=evaluate('Gentoo',4500),
            emptySelection=dict(n=0,all=empty_all,exists=empty_exists))
(ROOT/'math03-results.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False,indent=2))
