"""Cap detection, tested through the scan's own contract.

The owner's account was NOT capped when this was written, so no live cap markup
could be captured. The detector is therefore anchored on the composer's region plus
the cap vocabulary, and these tests pin the two properties that matter: a healthy
session never reports a cap, and a notice that does match is parsed correctly.
"""

from datetime import datetime, timezone

import chat


class FakeMarionette:
    """Answers CAP_SCAN the way the page would: the first region text matching the
    cap vocabulary, or None."""

    def __init__(self, texts: list[str]):
        self.texts = texts

    def sync_script(self, script, args=None):
        import re
        words = re.compile(args[1], re.I)
        for text in self.texts:
            if words.search(text):
                return {"text": text}
        return None


HEALTHY = ["Ask anything", "ChatGPT can make mistakes. Check important info.",
           "Attach files", "Sol · medium"]


def test_healthy_session_reports_no_cap():
    assert chat.detect_cap(FakeMarionette(HEALTHY)) is None


def test_unrelated_use_of_the_word_limit_is_not_a_cap():
    assert chat.detect_cap(FakeMarionette(["there is no limit to what you can ask"])) is None


def test_cap_notice_is_detected_with_its_text():
    state = chat.detect_cap(FakeMarionette(
        HEALTHY + ["You've hit your usage limit. Try again at 3:45 PM."]))
    assert state["kind"] == "usage-cap"
    assert "usage limit" in state["text"]


def test_cap_notice_without_a_time_has_no_resume_at():
    state = chat.detect_cap(FakeMarionette(["You've reached the message limit."]))
    assert state["resume_at"] is None


def test_reset_time_becomes_the_next_occurrence_in_iso_8601():
    now = datetime(2026, 8, 8, 16, 0, tzinfo=timezone.utc)
    assert chat.parse_reset("try again at 3:45 PM", now=now).startswith("2026-08-09T15:45")
    assert chat.parse_reset("resets at 18:30", now=now).startswith("2026-08-08T18:30")


def test_nonsense_clock_time_is_ignored():
    now = datetime(2026, 8, 8, 16, 0, tzinfo=timezone.utc)
    assert chat.parse_reset("resets at 99:99", now=now) is None
