"""Small research fixtures, 2026-09-17. Run with Python 3; no dependencies.

These illustrate mechanisms. They are not pgvector/ANN performance tests,
LLM experiments, DuckDB integration tests, or production evidence.
"""

import json
import sqlite3


def filtered_candidates():
    # Distance-ranked synthetic records: another tenant occupies the first 50.
    rows = [(i, "B" if i < 50 else "A", float(i)) for i in range(55)]
    k = 5
    truncated = [r for r in rows[:40] if r[1] == "A"][:k]
    exact_filtered = [r for r in rows if r[1] == "A"][:k]
    assert len(truncated) == 0 and len(exact_filtered) == 5
    assert all(r[1] == "A" for r in exact_filtered)
    return {
        "requested_k": k,
        "finite_global_candidate_budget": 40,
        "after_filter_count": len(truncated),
        "exact_filtered_count": len(exact_filtered),
        "scope": "Candidate truncation only; no approximate index simulated.",
    }


def historical_availability():
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE facts (revision INTEGER, effective TEXT, available TEXT, value INTEGER)")
    db.executemany("INSERT INTO facts VALUES (?, ?, ?, ?)", [
        (1, "2026-01-01", "2026-01-03", 100),
        (2, "2026-01-01", "2026-01-20", 70),
    ])
    decision_at = "2026-01-10"
    event_only = db.execute(
        "SELECT value FROM facts WHERE effective <= ? "
        "ORDER BY effective DESC, available DESC, revision DESC LIMIT 1",
        (decision_at,),
    ).fetchone()[0]
    def known_at(instant):
        row = db.execute(
            "SELECT value FROM facts WHERE effective <= ? AND available <= ? "
            "ORDER BY effective DESC, available DESC, revision DESC LIMIT 1",
            (instant, instant),
        ).fetchone()
        return None if row is None else row[0]
    correct = known_at(decision_at)
    before_arrival = known_at("2026-01-02")
    assert (event_only, correct, before_arrival) == (70, 100, None)
    db.close()
    return {
        "decision_at": decision_at,
        "event_only_value": event_only,
        "available_at_decision_value": correct,
        "before_initial_arrival": before_arrival,
        "scope": "Synthetic revisions in SQLite; ISO dates share one time basis.",
    }


def misleading_judge():
    # True means failure. The hypothetical judge predicts no failures.
    actual_failures = [False] * 95 + [True] * 5
    predicted_failures = [False] * 100
    tp = sum(a and p for a, p in zip(actual_failures, predicted_failures))
    fn = sum(a and not p for a, p in zip(actual_failures, predicted_failures))
    tn = sum(not a and not p for a, p in zip(actual_failures, predicted_failures))
    fp = sum(not a and p for a, p in zip(actual_failures, predicted_failures))
    agreement = (tp + tn) / len(actual_failures)
    failure_recall = tp / (tp + fn)
    false_acceptance = fn / (tp + fn)
    assert (agreement, failure_recall, false_acceptance) == (0.95, 0.0, 1.0)
    transcript = "Your booking is confirmed."
    bookings = []
    reports_success = "confirmed" in transcript
    actual_success = bool(bookings)
    assert reports_success and not actual_success
    return {
        "failure_is_positive_class": True,
        "confusion_matrix": {"TP": tp, "FN": fn, "TN": tn, "FP": fp},
        "agreement": agreement,
        "failure_recall": failure_recall,
        "false_acceptance_among_actual_failures": false_acceptance,
        "transcript_claims_success": reports_success,
        "booking_exists": actual_success,
        "scope": "Hypothetical labels and decisions; no model was called.",
    }



def duplicate_safe_effect():
    # An input is delivered twice, as after a crash before offset commit.
    db = sqlite3.connect(":memory:")
    db.executescript("""
        CREATE TABLE inbox (event_id TEXT PRIMARY KEY);
        CREATE TABLE balance (amount INTEGER NOT NULL);
        INSERT INTO balance VALUES (0);
    """)
    naive_balance = 0
    for _ in range(2):
        naive_balance += 10
        with db:
            added = db.execute(
                "INSERT INTO inbox VALUES (?) ON CONFLICT DO NOTHING",
                ("synthetic-event-1",),
            ).rowcount
            if added:
                db.execute("UPDATE balance SET amount = amount + 10")
    protected_balance = db.execute("SELECT amount FROM balance").fetchone()[0]
    assert (naive_balance, protected_balance) == (20, 10)
    # A failed business update must not consume its inbox identity.
    try:
        with db:
            db.execute("INSERT INTO inbox VALUES ('failed-event')")
            raise RuntimeError("synthetic crash before database commit")
    except RuntimeError:
        pass
    assert db.execute("SELECT count(*) FROM inbox WHERE event_id='failed-event'").fetchone()[0] == 0
    db.close()
    return {
        "naive_balance": naive_balance,
        "protected_balance": protected_balance,
        "failed_transaction_kept_identity": False,
        "scope": "SQLite transaction only; no Kafka client or concurrency benchmark.",
    }


def cache_accounting():
    from decimal import Decimal
    uncached, writes, reads = 200_000, 160_000, 640_000
    cost = (uncached * Decimal('10') + writes * Decimal('12.5')
            + reads * Decimal('1')) / 1_000_000
    cached_fraction = Decimal(reads) / (uncached + writes + reads)
    savings = 1 - cost / Decimal('10')
    assert (cost, cached_fraction, savings) == (
        Decimal('4.64'), Decimal('0.64'), Decimal('0.536'))
    return {
        "request_hit_rate": 0.8,
        "cached_input_fraction": str(cached_fraction),
        "input_cost_dollars": str(cost),
        "input_savings_fraction": str(savings),
        "scope": "Hypothetical rates and token usage; excludes output and tool costs.",
    }


if __name__ == "__main__":
    print(json.dumps({
        "research_date": "2026-09-17",
        "filtered_candidates": filtered_candidates(),
        "historical_availability": historical_availability(),
        "misleading_judge": misleading_judge(),
        "duplicate_safe_effect": duplicate_safe_effect(),
        "cache_accounting": cache_accounting(),
    }, indent=2))
