"""Run the evaluation fixed by manifest.yaml. The manifest was sealed and
committed to the public registry before this script produced any number."""
import numpy as np, yaml
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

m = yaml.safe_load(open("manifest.yaml"))
SEED = m["seed"]

rows = [l.split() for l in open("german.data") if l.strip()]
X_raw = [r[:20] for r in rows]
y = np.array([1 if r[20] == "1" else 0 for r in rows])           # 1 = good credit
cat = [i for i in range(20) if X_raw[0][i].startswith("A")]
num = [i for i in range(20) if i not in cat]
X = np.array(X_raw, dtype=object)
sex = np.array(["female" if r[8] == "A92" else "male" for r in rows])

Xtr, Xte, ytr, yte, _, sxte = train_test_split(
    X, y, sex, test_size=0.30, random_state=SEED, stratify=y)      # stratified 70/30

pipe = Pipeline([
    ("prep", ColumnTransformer([
        ("cat", OneHotEncoder(handle_unknown="ignore"), cat),
        ("num", StandardScaler(), num)])),
    ("clf", LogisticRegression(penalty="l2", C=1.0, max_iter=2000, random_state=SEED)),
])
pipe.fit(Xtr.tolist(), ytr)
pred = pipe.predict(Xte.tolist())

sel_f = float((pred[sxte == "female"] == 1).mean())
sel_m = float((pred[sxte == "male"] == 1).mean())
ir = sel_f / sel_m

print(f"  test split       : {len(yte)} applicants "
      f"({int((sxte=='female').sum())} female, {int((sxte=='male').sum())} male)")
print(f"  selection rate   : female {sel_f:.4f}  male {sel_m:.4f}")
print(f"  impact ratio     : {ir:.4f}")
print(f"  threshold        : {m['comparator']} {m['threshold']}")
print(f"  VERDICT          : {'PASS' if ir >= m['threshold'] else 'FAIL'}")
open("result.txt","w").write(
    f"impact_ratio={ir:.6f}\nselection_female={sel_f:.6f}\nselection_male={sel_m:.6f}\n"
    f"n_test={len(yte)}\nn_female={int((sxte=='female').sum())}\nn_male={int((sxte=='male').sum())}\n"
    f"verdict={'PASS' if ir >= m['threshold'] else 'FAIL'}\n")
