#!/usr/bin/env python3

import importlib.machinery
import importlib.util
import pathlib
import sys
import unittest
from unittest.mock import Mock


ROOT = pathlib.Path(__file__).resolve().parents[2]
HELPER = ROOT / "config/dot/quickshell/scripts/calendar-agenda"
sys.dont_write_bytecode = True

loader = importlib.machinery.SourceFileLoader("calendar_agenda", str(HELPER))
spec = importlib.util.spec_from_loader(loader.name, loader)
calendar_agenda = importlib.util.module_from_spec(spec)
loader.exec_module(calendar_agenda)


class CalendarAgendaBridgeTest(unittest.TestCase):
    def test_meeting_url_allowlist(self):
        meeting_url = "https://meet.google.com/abc-defg-hij"

        self.assertEqual(calendar_agenda.find_join_url([f"Planning: {meeting_url}"]), meeting_url)
        self.assertEqual(calendar_agenda.find_join_url(["https://example.com/private"]), "")
        self.assertEqual(calendar_agenda.find_join_url(["http://zoom.us/j/123"]), "")

    def test_stable_instance_id_includes_recurrence(self):
        self.assertEqual(
            calendar_agenda.stable_event_id("source", "uid", "20260817T133000Z"),
            "source:uid:20260817T133000Z",
        )

    def test_snapshot_sort_order(self):
        events = [
            {"id": "b", "start": 20, "end": 30, "allDay": False},
            {"id": "a", "start": 10, "end": 20, "allDay": True},
        ]

        self.assertEqual([event["id"] for event in calendar_agenda.sort_events(events)], ["a", "b"])

    def test_normalizes_an_all_day_recurrence_instance(self):
        recurrence_id = Mock()
        recurrence_id.is_null_time.return_value = False
        recurrence_id.as_ical_string.return_value = "20260817"
        component = Mock()
        component.get_uid.return_value = "uid"
        component.get_recurrenceid.return_value = recurrence_id
        component.get_summary.return_value = "Synthetic event"
        component.get_location.return_value = ""
        component.get_description.return_value = ""
        component.get_first_property.return_value = None
        start = Mock()
        start.as_timet.return_value = 1786924800
        start.is_date.return_value = True
        end = Mock()
        end.as_timet.return_value = 1787011200
        end.is_date.return_value = True

        event = calendar_agenda.normalize_instance(
            {"id": "source", "name": "Synthetic", "color": "#82aaff"},
            component,
            start,
            end,
        )

        self.assertTrue(event["allDay"])
        self.assertEqual(event["id"], "source:uid:20260817")


if __name__ == "__main__":
    unittest.main()
