"""Todo2 no-follow customer-registry identity issuance tests."""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from gateway.platforms.nutrition_weekly_operations_config import (
    WeeklyOperationsAuthorityError,
)
import gateway.platforms.nutrition_weekly_operations_registry_identity as registry_boundary
from tests.gateway._weekly_operations_authority_support import (
    registry_identity_from_file,
)


def test_identity_is_issued_from_exact_private_no_follow_inode(tmp_path: Path) -> None:
    registry = tmp_path / "registry.json"
    _ = registry.write_bytes(b'{"version":1}\n')
    registry.chmod(0o600)

    first = registry_identity_from_file(tmp_path, "registry.json")
    second = registry_identity_from_file(tmp_path, "registry.json")

    info = registry.stat()
    assert (first.device, first.inode) == (info.st_dev, info.st_ino)
    assert first == second
    assert first.binding_digest == registry_boundary.registry_identity_binding_digest(first)


@pytest.mark.parametrize("attack", ("symlink", "hardlink", "mode", "fifo"))
def test_identity_issuance_rejects_unsafe_registry_name(
    tmp_path: Path, attack: str
) -> None:
    registry = tmp_path / "registry.json"
    alternate = tmp_path / "alternate.json"
    _ = alternate.write_bytes(b"{}")
    alternate.chmod(0o600)
    if attack == "symlink":
        registry.symlink_to(alternate.name)
    elif attack == "hardlink":
        os.link(alternate, registry)
    elif attack == "mode":
        _ = registry.write_bytes(b"{}")
        registry.chmod(0o640)
    else:
        os.mkfifo(registry, mode=0o600)

    with pytest.raises((OSError, WeeklyOperationsAuthorityError)):
        _ = registry_identity_from_file(tmp_path, "registry.json")


def test_gateway_registry_boundary_exposes_no_runtime_issuer() -> None:
    names = dir(registry_boundary)
    assert not any(
        token in name.lower()
        for name in names
        for token in ("issue", "mint", "create", "refresh")
    )
