from django.test import SimpleTestCase
from django.utils import timezone
from unittest.mock import Mock

from apps.lyric.templatetags.lyric_extras import display_name, relative_ts, truncate_email


class TruncateEmailTest(SimpleTestCase):
    def test_truncates_neither_short_local_nor_short_domain(self):
        self.assertEqual(truncate_email("abc@d.e"), "abc@d.e")

    def test_truncates_only_long_local_not_short_domain(self):
        self.assertEqual(truncate_email("sesquipedalian@abc.de"), "se…an@abc.de")

    def test_truncates_not_short_local_only_long_domain(self):
        self.assertEqual(truncate_email("abc@longexample.com"), "abc@l…e.com")

    def test_truncates_both_long_local_and_long_domain(self):
        self.assertEqual(truncate_email("onomatopoeia@earthmanrpg.com"), "on…ia@e…g.com")

    def test_boundary_case_longish_segments_no_truncate(self):
        self.assertEqual(truncate_email("abcdefg@gmail.com"), "abcdefg@gmail.com")

    def test_boundary_case_exact_segments_do_truncate(self):
        self.assertEqual(truncate_email("abcdefgh@icloud.com"), "ab…gh@i…d.com")

class DisplayNameFilterTest(SimpleTestCase):
    def test_returns_empty_string_for_none_user(self):
        self.assertEqual(display_name(None), "")

    def test_returns_truncated_email_when_no_username(self):
        user = Mock(username="", email="sesquipedalian@abc.de")
        self.assertEqual(display_name(user), "se…an@abc.de")

    def test_returns_username_when_set(self):
        user = Mock(username="earthman", email="sesquipedalian@abc.de")
        self.assertEqual(display_name(user), "earthman")


class RelativeTsFilterTest(SimpleTestCase):
    def test_returns_empty_string_for_none(self):
        self.assertEqual(relative_ts(None), "")

    def test_returns_time_for_recent_dt(self):
        dt = timezone.now() - timezone.timedelta(hours=1)
        result = relative_ts(dt)
        self.assertRegex(result, r'\d+:\d+')

    def test_returns_weekday_for_2_day_old_dt(self):
        dt = timezone.now() - timezone.timedelta(days=2)
        result = relative_ts(dt)
        self.assertIn(result, ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])

    def test_returns_month_day_for_30_day_old_dt(self):
        dt = timezone.now() - timezone.timedelta(days=30)
        result = relative_ts(dt)
        import re
        self.assertRegex(result, r'^\d{2} \w{3}$')

    def test_returns_month_day_year_for_over_1_year_old_dt(self):
        dt = timezone.now() - timezone.timedelta(days=400)
        result = relative_ts(dt)
        import re
        self.assertRegex(result, r'^\d{2} \w{3} \d{4}$')
