"""Core ↔ Cloud contract for the membership projection, schema v1 (Workstream G).

Core regenerates the Workstream E payload for a fixed sample and compares it with the fixture
Cloud parses in its own tests. If either side changes the shape, one of these checks fails.
"""

import json
import uuid
from pathlib import Path

import pytest

from src.domain.project_auth.cloud_projection import (
    BindingSnapshot,
    MembershipSnapshot,
    ProjectSnapshot,
    RoleSnapshot,
    build_projection,
    to_cloud_payload,
)

CLOUD_FIXTURE = (
    Path(__file__).resolve().parents[2]
    / "P2HSCloud" / "apps" / "pc-gateway" / "src" / "lib" / "fixtures" / "core-projection-v1.json"
)

ADMIN = uuid.UUID("00000000-0000-0000-0000-00000000000a")
STAFF = uuid.UUID("00000000-0000-0000-0000-00000000000b")
PROT = uuid.UUID("00000000-0000-0000-0000-00000000000c")
MEMBER_ID = uuid.UUID("00000000-0000-0000-0000-0000000000a1")


def sample_payload() -> dict:
    roles = {
        ADMIN: RoleSnapshot(ADMIN, "admin", "admin", False, frozenset(["member.role.grant_staff", "staff"])),
        STAFF: RoleSnapshot(STAFF, "staff", "staff", False, frozenset(["staff"])),
        PROT: RoleSnapshot(PROT, "super_admin", None, True, frozenset(["super_admin", "billing"])),
    }
    snapshot = ProjectSnapshot(
        roles=roles,
        protected_owner_permissions=frozenset(["super_admin", "billing"]),
        memberships=(),
    )
    member = MembershipSnapshot(
        membership_id=MEMBER_ID,
        email="alice@example.test",
        is_owner=False,
        cloud_app_user_id="usr_alice",
        authorization_version=7,
        bindings=frozenset({BindingSnapshot(ADMIN, "workspace"), BindingSnapshot(STAFF, "local")}),
        holds=frozenset(),
    )
    return to_cloud_payload("prj_fixture", build_projection(snapshot, member))


def test_core_output_matches_the_cloud_fixture_byte_for_byte_in_meaning():
    if not CLOUD_FIXTURE.exists():
        pytest.skip("sibling P2HSCloud checkout not present")
    expected = json.loads(CLOUD_FIXTURE.read_text(encoding="utf-8"))
    assert sample_payload() == expected


def test_the_schema_version_and_field_set_are_fixed():
    payload = sample_payload()
    assert payload["schema_version"] == 1
    assert set(payload) == {
        "schema_version", "project_id", "email", "cloud_app_user_id", "status", "is_owner",
        "project_roles", "project_permissions", "excluded_roles", "legacy_role",
        "authorization_version",
    }
