"""EDA：运行 python 01_eda.py，检查跨月漂移与事后字段。"""
from collections import Counter
from random import Random
from statistics import quantiles

rng = Random(15)

def make_rows(month, n=400):
    rows = []
    for i in range(n):
        channel = rng.choices(["app", "web", "partner"], [5, 5, 0] if month == 1 else [5, 2, 3])[0]
        order_time = month * 30 + i // 15
        label = int(rng.random() < (0.36 if channel == "partner" else 0.16))
        rows.append(dict(order_id=f"{month}-{i}", user_id=i % (200 if month == 1 else 250),
                         time=order_time, channel=channel,
                         amount=None if rng.random() < (0.23 if channel == "partner" else 0.06)
                         else round(rng.lognormvariate(3.8, 0.7), 2), y=label,
                         closed_time=order_time + 3 if label else None))
    return rows

train, test = make_rows(1), make_rows(2)
known = {r["channel"] for r in train}
for name, rows in (("train", train), ("test", test)):
    assert len({r["order_id"] for r in rows}) == len(rows)
    print(name, "channel:", Counter(r["channel"] for r in rows))
    print("amount_missing:", sum(r["amount"] is None for r in rows) / len(rows))
    print("amount_quartiles:", quantiles([r["amount"] for r in rows if r["amount"] is not None]))
    print("unknown_channel:", sum(r["channel"] not in known for r in rows) / len(rows))
print("overlapping users:", len({r["user_id"] for r in train} & {r["user_id"] for r in test}))
future = [r for r in train + test if r["closed_time"] is not None and r["closed_time"] > r["time"]]
print("rows with a future observation:", len(future))
assert future and all(int(r["closed_time"] is not None) == r["y"] for r in train)
print("closed_time missingness perfectly reveals the synthetic training label: exclude it.")

