"""Quiet-hours parsing and matching, without waiting for 11pm."""

import sys
from datetime import time as dtime
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from bolt_pet import quiet


def test_no_spec_means_never_quiet():
    assert quiet.is_quiet("") is False
    assert quiet.is_quiet("   ") is False


def test_simple_daytime_range():
    ranges = quiet.parse_ranges("13:00-14:00")
    assert quiet.in_ranges(dtime(13, 30), ranges) is True
    assert quiet.in_ranges(dtime(12, 59), ranges) is False
    assert quiet.in_ranges(dtime(14, 0), ranges) is False  # end is exclusive


def test_range_wrapping_past_midnight():
    ranges = quiet.parse_ranges("23:00-08:00")
    for moment in (dtime(23, 0), dtime(23, 59), dtime(0, 0), dtime(7, 59)):
        assert quiet.in_ranges(moment, ranges) is True, moment
    for moment in (dtime(8, 0), dtime(12, 0), dtime(22, 59)):
        assert quiet.in_ranges(moment, ranges) is False, moment


def test_multiple_ranges():
    ranges = quiet.parse_ranges("23:00-08:00, 13:00-14:00")
    assert quiet.in_ranges(dtime(13, 15), ranges) is True
    assert quiet.in_ranges(dtime(2, 0), ranges) is True
    assert quiet.in_ranges(dtime(16, 0), ranges) is False


def test_zero_length_range_is_not_all_day():
    assert quiet.in_ranges(dtime(12, 0), quiet.parse_ranges("09:00-09:00")) is False


def test_malformed_specs_raise_when_parsed_directly():
    for spec in ("nonsense", "25:00-26:00", "13:00", "13:60-14:00"):
        with pytest.raises(quiet.QuietHoursError):
            quiet.parse_ranges(spec)


def test_malformed_spec_is_reported_but_never_mutes_the_pet():
    seen = []
    assert quiet.is_quiet("nonsense", now=dtime(3, 0), on_error=seen.append) is False
    assert len(seen) == 1
