"""Тесты правил расчёта часов из графика."""

from datetime import date, time

import pytest

from timesheet.rules import (
    LEGACY_BREAK,
    NO_BREAK,
    BreakRule,
    NightWindow,
    personal_norm,
    split_shift,
)

D = date(2026, 8, 3)


def as_tuples(rows):
    return [(r.work_date, r.hours_day, r.hours_night) for r in rows]


# ---------------------------------------------------------------------------
#  Дневные смены
# ---------------------------------------------------------------------------

def test_day_shift_without_break():
    """09:00–18:00 целиком в дневном интервале — 9 часов."""
    rows = split_shift(D, time(9), time(18), break_rule=NO_BREAK)
    assert as_tuples(rows) == [(D, 9.0, 0.0)]


def test_day_shift_with_legacy_break():
    """Тот же интервал с текущим правилом перерыва — 8 часов."""
    rows = split_shift(D, time(9), time(18), break_rule=LEGACY_BREAK)
    assert as_tuples(rows) == [(D, 8.0, 0.0)]


def test_twelve_hour_day_shift():
    """08:00–20:00 — 12 часов дня, минус перерыв = 11."""
    rows = split_shift(D, time(8), time(20), break_rule=LEGACY_BREAK)
    assert as_tuples(rows) == [(D, 11.0, 0.0)]


def test_short_shift_still_loses_hour_in_legacy_mode():
    """Текущее поведение: даже 4-часовая смена теряет час. Это и есть спорное место."""
    rows = split_shift(D, time(9), time(13), break_rule=LEGACY_BREAK)
    assert as_tuples(rows) == [(D, 3.0, 0.0)]


def test_threshold_protects_short_shift():
    """С порогом 6 часов короткая смена перерыв не теряет."""
    rule = BreakRule(min_shift_hours=6)
    rows = split_shift(D, time(9), time(13), break_rule=rule)
    assert as_tuples(rows) == [(D, 4.0, 0.0)]


# ---------------------------------------------------------------------------
#  Ночь и переход через полночь
# ---------------------------------------------------------------------------

def test_evening_shift_touching_night():
    """16:00–00:00: 6 часов дня (до 22:00) и 2 часа ночи."""
    rows = split_shift(D, time(16), time(0), break_rule=NO_BREAK)
    assert as_tuples(rows) == [(D, 6.0, 2.0)]


def test_night_shift_across_midnight():
    """
    20:00–08:00 разносится на два дня:
      3 августа: 20:00–22:00 день (2 ч), 22:00–24:00 ночь (2 ч)
      4 августа: 00:00–06:00 ночь (6 ч), 06:00–08:00 день (2 ч)
    """
    rows = split_shift(D, time(20), time(8), break_rule=NO_BREAK)
    assert as_tuples(rows) == [
        (date(2026, 8, 3), 2.0, 2.0),
        (date(2026, 8, 4), 2.0, 6.0),
    ]


def test_night_shift_break_goes_to_largest_bucket():
    """Перерыв вычитается из наибольшего интервала — здесь это ночь второго дня."""
    rows = split_shift(D, time(20), time(8), break_rule=LEGACY_BREAK)
    assert as_tuples(rows) == [
        (date(2026, 8, 3), 2.0, 2.0),
        (date(2026, 8, 4), 2.0, 5.0),
    ]


def test_pure_night_shift():
    """23:00–07:00: всё ночное время, кроме часа 06:00–07:00."""
    rows = split_shift(D, time(23), time(7), break_rule=NO_BREAK)
    assert as_tuples(rows) == [
        (date(2026, 8, 3), 0.0, 1.0),
        (date(2026, 8, 4), 1.0, 6.0),
    ]


def test_full_day_shift():
    """Смена ровно в сутки: 8 часов ночи (22–06) и 16 часов дня."""
    rows = split_shift(D, time(0), time(0), break_rule=NO_BREAK)
    assert as_tuples(rows) == [(D, 16.0, 8.0)]


def test_proportional_break_splits_across_buckets():
    rows = split_shift(
        D, time(20), time(8), break_rule=BreakRule(mode="proportional")
    )
    total = sum(r.hours_day + r.hours_night for r in rows)
    assert total == pytest.approx(11.0, abs=0.05)


def test_custom_night_window():
    """Границу ночи можно изменить справочником, а не правкой кода."""
    night = NightWindow(start=time(23), end=time(5))
    rows = split_shift(D, time(20), time(8), night=night, break_rule=NO_BREAK)
    assert as_tuples(rows) == [
        (date(2026, 8, 3), 3.0, 1.0),
        (date(2026, 8, 4), 3.0, 5.0),
    ]


def test_break_never_makes_hours_negative():
    rows = split_shift(D, time(9), time(9, 30), break_rule=LEGACY_BREAK)
    assert all(r.hours_day >= 0 and r.hours_night >= 0 for r in rows)


# ---------------------------------------------------------------------------
#  Норма
# ---------------------------------------------------------------------------

def test_personal_norm_subtracts_excused_hours():
    assert personal_norm(168, 40) == 128.0


def test_personal_norm_never_negative():
    assert personal_norm(168, 200) == 0.0
