"""MediaKit 智能选片挪点冲突检测测试（Task G 验收项 1）。

覆盖 _recommended_time_conflicts：
- 区间重叠判定（含 0.3s 边缘间隙扩边）
- 不冲突场景（间隔大于边缘间隙）
- 边缘间隙可配置
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

os.environ.setdefault("JWT_SECRET_KEY", "unit-test-secret-key-for-testing")
os.environ.setdefault("DATABASE_URL", "sqlite:///test.db")

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "apps" / "api"))

from app.api.routes.templates_editor.clips import (
    SEGMENT_EDGE_GAP,
    _recommended_time_conflicts,
)


class TestRecommendedTimeConflicts:
    def test_overlapping_range_conflicts(self):
        """推荐区间与已用区间直接重叠 → 冲突。"""
        assert _recommended_time_conflicts(10.0, 5.0, [(12.0, 17.0)]) is True

    def test_identical_range_conflicts(self):
        assert _recommended_time_conflicts(10.0, 5.0, [(10.0, 15.0)]) is True

    def test_touching_endpoint_conflicts_due_to_edge_gap(self):
        """首尾紧贴（推荐 15 开始，已用 [10,15]）：1.5s 扩边内 → 冲突。"""
        assert _recommended_time_conflicts(15.0, 5.0, [(10.0, 15.0)]) is True

    def test_gap_within_edge_gap_conflicts(self):
        """间隔 0.2s（< 1.5s 边缘间隙）→ 冲突。"""
        assert _recommended_time_conflicts(15.2, 5.0, [(10.0, 15.0)]) is True

    def test_gap_beyond_edge_gap_no_conflict(self):
        """间隔 2.0s（> 1.5s 边缘间隙）→ 不冲突。"""
        assert _recommended_time_conflicts(17.0, 5.0, [(10.0, 15.0)]) is False

    def test_far_apart_no_conflict(self):
        """相隔很远 → 不冲突。"""
        assert _recommended_time_conflicts(20.0, 5.0, [(0.0, 5.0)]) is False

    def test_empty_used_no_conflict(self):
        assert _recommended_time_conflicts(10.0, 5.0, []) is False

    def test_any_one_range_conflicts(self):
        """多个已用区间，任一冲突即返回 True。"""
        used = [(0.0, 5.0), (10.0, 15.0), (20.0, 25.0)]
        assert _recommended_time_conflicts(12.0, 2.0, used) is True
        assert (
            _recommended_time_conflicts(6.5, 2.0, used) is False
        )  # range [6.5,8.5], just outside all expanded used ranges

    def test_custom_edge_gap(self):
        """edge_gap 可配置：gap=0 时紧贴不冲突（端点相接不算重叠）。"""
        # edge_gap=0：15.0 开始与已用 [10,15] 端点相接，区间判定 start<end_gap(15) → False
        assert _recommended_time_conflicts(15.0, 5.0, [(10.0, 15.0)], edge_gap=0.0) is False
        # edge_gap=1.0：0.5 间隔也算冲突
        assert _recommended_time_conflicts(15.5, 5.0, [(10.0, 15.0)], edge_gap=1.0) is True

    def test_default_edge_gap_constant(self):
        """默认边缘间隙常量为 1.5s（配置常量）。"""
        assert SEGMENT_EDGE_GAP == 1.5
