from pathlib import Path

from quota_notification_store import QuotaNotificationStore


def test_exhaustion_is_delivered_once_across_store_restarts(tmp_path: Path) -> None:
    path = tmp_path / "quota_notifications.json"

    assert QuotaNotificationStore(path).record_exhaustion("codex:zync", "5h", "2026-07-23T12:00:00Z")
    assert not QuotaNotificationStore(path).record_exhaustion(
        "codex:zync", "5h", "2026-07-23T12:00:00Z"
    )


def test_reset_is_delivered_once_after_an_alerted_exhaustion(tmp_path: Path) -> None:
    store = QuotaNotificationStore(tmp_path / "quota_notifications.json")

    assert store.record_exhaustion("codex:zync", "5h", "2026-07-23T12:00:00Z")
    assert store.record_reset("codex:zync", "5h", "2026-07-23T17:00:00Z")
    assert not store.record_reset("codex:zync", "5h", "2026-07-23T17:00:00Z")


def test_reset_requires_an_alerted_exhaustion(tmp_path: Path) -> None:
    store = QuotaNotificationStore(tmp_path / "quota_notifications.json")

    assert not store.record_reset("codex:zync", "5h", "2026-07-23T17:00:00Z")


def test_exhaustion_with_drifting_reset_at_is_still_delivered_once(tmp_path: Path) -> None:
    store = QuotaNotificationStore(tmp_path / "quota_notifications.json")

    assert store.record_exhaustion("codex:multideal", "7d", "1785293817.0")
    assert not store.record_exhaustion("codex:multideal", "7d", "1785293999.4")
    assert not store.record_exhaustion("codex:multideal", "7d", "1785294201.7")


def test_new_exhaustion_after_reset_is_delivered_again(tmp_path: Path) -> None:
    store = QuotaNotificationStore(tmp_path / "quota_notifications.json")

    assert store.record_exhaustion("codex:zync", "5h", "cycle-1")
    assert store.record_reset("codex:zync", "5h", "cycle-1")
    assert store.record_exhaustion("codex:zync", "5h", "cycle-2")


def test_legacy_record_without_exhausted_flag_counts_as_exhausted(tmp_path: Path) -> None:
    path = tmp_path / "quota_notifications.json"
    path.write_text(
        '{"codex:multideal:7d": {"exhausted_reset_at": "1785293817.0", "reset_notified_at": null}}\n',
        encoding="utf-8",
    )
    store = QuotaNotificationStore(path)

    assert not store.record_exhaustion("codex:multideal", "7d", "1785293900.0")
    assert store.record_reset("codex:multideal", "7d", "1785293900.0")
