"""Adversarial registry attachment tests for default reminder bootstrap."""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from gateway.config import PlatformConfig
from gateway.platforms.nutrition_weekly_operations_config import JsonValue
from gateway.platforms.nutrition_weekly_reminder_bootstrap import (
    WeeklyReminderStartupAuthorityIncident,
)
from gateway.platforms.telegram import TelegramAdapter
from tests.gateway._nutrition_weekly_reminder_support import (
    FakeTelegramHost,
    reminder_owner_fixture,
)


def platform_config(root: Path, extra: dict[str, JsonValue]) -> PlatformConfig:
    configured = dict(extra)
    raw = configured["nutrition_coaching"]
    assert isinstance(raw, dict)
    nutrition: dict[str, JsonValue] = dict(raw)
    nutrition.update(
        enabled=True,
        profile_root=str(root),
        registry_path="registry.json",
        weekly_operations_authority_path="weekly-authority",
    )
    configured["nutrition_coaching"] = nutrition
    return PlatformConfig(enabled=True, token="fixture", extra=configured)


def alternate_registry(path: Path, payload: bytes) -> Path:
    alternate = path.with_name("alternate-registry.json")
    _ = alternate.write_bytes(payload)
    alternate.chmod(0o600)
    return alternate


@pytest.mark.parametrize(
    "attack",
    (
        "symlink_identical",
        "inode_identical",
        "route_replacement",
        "hardlink_replacement",
        "fifo",
        "directory",
        "mode",
        "link_count",
    ),
)
def test_default_bootstrap_rejects_unsealed_registry_attachment(
    tmp_path: Path, attack: str
) -> None:
    fixture = reminder_owner_fixture(tmp_path)
    registry = fixture.registry_path
    payload = registry.read_bytes()
    config = platform_config(tmp_path, fixture.extra)
    if attack == "symlink_identical":
        alternate = alternate_registry(registry, payload)
        registry.unlink()
        registry.symlink_to(alternate.name)
    elif attack == "inode_identical":
        alternate = alternate_registry(registry, payload)
        os.replace(alternate, registry)
    elif attack == "route_replacement":
        redirected = payload.replace(
            b'"chat_id": "customer-chat"', b'"chat_id": "redirected"'
        )
        assert redirected != payload
        alternate = alternate_registry(registry, redirected)
        os.replace(alternate, registry)
    elif attack == "hardlink_replacement":
        alternate = alternate_registry(registry, payload)
        registry.unlink()
        os.link(alternate, registry)
    elif attack == "fifo":
        registry.unlink()
        os.mkfifo(registry, mode=0o600)
    elif attack == "directory":
        registry.unlink()
        registry.mkdir(mode=0o700)
    elif attack == "mode":
        registry.chmod(0o640)
    else:
        os.link(registry, registry.with_name("registry-alias.json"))
    provider = FakeTelegramHost()
    try:
        with pytest.raises(WeeklyReminderStartupAuthorityIncident):
            _ = TelegramAdapter(config)
        assert provider.calls == 0
    finally:
        fixture.owner.close()
