"""Offline point-in-time feature example. All records and probabilities are fictional.
Run: python3 look-ahead-bias.py. No dependencies, network, accounts or orders.
This tests one feature join, not a complete backtesting/training/execution system.
"""
from datetime import datetime
from decimal import Decimal as D


def stamp(text):
    value = datetime.fromisoformat(text.replace("Z", "+00:00"))
    if value.tzinfo is None or value.utcoffset() is None:
        raise ValueError("Use timezone-aware timestamps")
    return value


def select_as_of(rows, decision_at):
    decision = stamp(decision_at)
    eligible, seen = [], set()
    for row in rows:
        observed = stamp(row["observed_at"])
        published = stamp(row["published_at"])
        ingested = stamp(row["ingested_at"])
        if not observed <= published <= ingested:
            raise ValueError("Fixture requires observation <= publication <= ingestion")
        available = max(published, ingested)
        key = (observed, available)
        if key in seen:
            raise ValueError("Ambiguous versions at the same observation/availability time")
        seen.add(key)
        value = D(row["value"])
        if not value.is_finite():
            raise ValueError("Nonfinite feature")
        if observed <= decision and available <= decision:
            eligible.append((observed, available, row["version"], value))
    # Latest observable period, then latest version actually available for it.
    return max(eligible, key=lambda x: (x[0], x[1])) if eligible else None


if __name__ == "__main__":
    rows = [
        {"version":"v1", "observed_at":"2026-11-01T00:00:00Z", "published_at":"2026-11-02T10:00:00Z", "ingested_at":"2026-11-02T10:05:00Z", "value":"0.60"},
        {"version":"v2", "observed_at":"2026-11-01T00:00:00Z", "published_at":"2026-11-05T10:00:00Z", "ingested_at":"2026-11-05T10:05:00Z", "value":"0.90"},
        {"version":"next", "observed_at":"2026-11-04T00:00:00Z", "published_at":"2026-11-06T10:00:00Z", "ingested_at":"2026-11-06T10:05:00Z", "value":"0.70"},
    ]
    before = select_as_of(rows, "2026-11-02T10:04:00Z")
    decision = select_as_of(rows, "2026-11-04T12:00:00Z")
    release_not_ingested = select_as_of(rows, "2026-11-05T10:02:00Z")
    revision_available = select_as_of(rows, "2026-11-05T10:05:00Z")
    next_period = select_as_of(rows, "2026-11-06T10:05:00Z")
    assert before is None
    assert decision[2:] == ("v1", D("0.60"))
    assert release_not_ingested[2] == "v1"
    assert revision_available[2:] == ("v2", D("0.90"))
    assert next_period[2:] == ("next", D("0.70"))
    assert select_as_of(list(reversed(rows)), "2026-11-04T12:00:00Z") == decision
    # Equal-time availability is explicitly inclusive in this teaching fixture.
    # An original frozen teaching mapping is p=feature, evaluated later at y=1.
    honest_score = (decision[3] - 1) ** 2
    leaked_score = (D("0.90") - 1) ** 2
    assert honest_score == D("0.16") and leaked_score == D("0.01")
    assert honest_score - leaked_score == D("0.15")
    try:
        stamp("2026-11-04T12:00:00")
    except ValueError:
        pass
    else:
        raise AssertionError("Naive timestamp must be rejected")
    try:
        select_as_of(rows + [dict(rows[0])], "2026-11-04T12:00:00Z")
    except ValueError:
        pass
    else:
        raise AssertionError("Ambiguous duplicate version must be rejected")
    print("Nov4 decision: v1, feature/probability0.60; later revision0.90 excluded.")
    print("Correct Brier0.16; leaked Brier0.01; artificial improvement0.15.")
    print("Missing, ingestion lag, inclusive boundary, revision, row order and duplicate checks passed.")
