from src.domain.feature_packs.composition import (
    composed_library_slugs,
    library_slugs_from_entries,
)
from src.domain.manifest.schemas import ManifestFeaturePack


_CONTACT_CAPTURE_FUNCTIONS = [
    {
        "library_slug": "contact-capture-notify",
        "project_slug": "contact-capture-notify",
        "trigger_config": {
            "event_type": "record.created",
            "static_env_vars": {"NOTIFY_TO_EMAIL": "$config.notify_to_email"},
        },
    },
    {
        "library_slug": "contact-capture-retry",
        "project_slug": "contact-capture-retry",
        "trigger_config": {
            "cron": "0 * * * *",
            "static_env_vars": {"NOTIFY_TO_EMAIL": "$config.notify_to_email"},
        },
    },
]


def test_library_slugs_from_string_and_object_entries():
    assert library_slugs_from_entries(["booking-create", "booking-cancel"]) == [
        "booking-create",
        "booking-cancel",
    ]
    assert library_slugs_from_entries(_CONTACT_CAPTURE_FUNCTIONS) == [
        "contact-capture-notify",
        "contact-capture-retry",
    ]
    assert composed_library_slugs({"function_slugs": _CONTACT_CAPTURE_FUNCTIONS}) == [
        "contact-capture-notify",
        "contact-capture-retry",
    ]


def test_manifest_feature_pack_accepts_contact_capture_composition():
    pack = ManifestFeaturePack(
        id="pack-1",
        slug="contact-capture",
        name="Contact Capture",
        version="1.1.0",
        composes=_CONTACT_CAPTURE_FUNCTIONS,
        requires=[],
        status="available",
    )
    assert pack.composes == ["contact-capture-notify", "contact-capture-retry"]


def test_pack_config_merge_keeps_notify_email_on_empty_reinstall():
    from src.domain.feature_packs.config import merge_pack_config, union_notify_emails

    previous = {"notify_to_email": "mohsin@pie-solutions.com, duffyace@gmail.com", "notify_email": True}
    merged = merge_pack_config(previous, {})
    assert merged["notify_to_email"] == "mohsin@pie-solutions.com, duffyace@gmail.com"
    assert merge_pack_config(previous, {"notify_to_email": ""})["notify_to_email"] == previous["notify_to_email"]
    assert union_notify_emails("ops@example.com", previous["notify_to_email"]).startswith("ops@example.com")
    assert "mohsin@pie-solutions.com" in union_notify_emails("ops@example.com", previous["notify_to_email"])

