from __future__ import annotations

import json
from pathlib import Path

from checkin_cli.nutrition_onboarding_projection import (
    apply_nutrition_onboarding_projection,
)


def test_customer_projection_replay_survives_other_customer_projection(
    tmp_path: Path,
) -> None:
    registry_path = tmp_path / "customers/registry.json"
    registry_path.parent.mkdir(parents=True, mode=0o700)
    registry_path.write_text(
        json.dumps({
            "version": 1,
            "owner": {"user_id": "1", "chat_id": "1", "topic_id": "0"},
            "customers": [
                {"customer_key": "customer_a", "enabled": False},
                {"customer_key": "customer_b", "enabled": False},
            ],
        }),
        encoding="utf-8",
    )
    registry_path.chmod(0o600)

    first = apply_nutrition_onboarding_projection(
        tmp_path,
        customer_key="customer_a",
        nutrition_profile={"goal": "a"},
        plan={"starts_on": "2026-09-01"},
        artifact_bundle_digest="a" * 64,
        readiness_receipt_digest="b" * 64,
    )
    _ = apply_nutrition_onboarding_projection(
        tmp_path,
        customer_key="customer_b",
        nutrition_profile={"goal": "b"},
        plan={"starts_on": "2026-09-02"},
        artifact_bundle_digest="c" * 64,
        readiness_receipt_digest="d" * 64,
    )
    replay = apply_nutrition_onboarding_projection(
        tmp_path,
        customer_key="customer_a",
        nutrition_profile={"goal": "a"},
        plan={"starts_on": "2026-09-01"},
        artifact_bundle_digest="a" * 64,
        readiness_receipt_digest="b" * 64,
    )

    assert replay == first
    projected = json.loads(registry_path.read_text(encoding="utf-8"))
    customers = {
        customer["customer_key"]: customer for customer in projected["customers"]
    }
    assert customers["customer_a"]["profile"] == {"goal": "a"}
    assert customers["customer_b"]["profile"] == {"goal": "b"}
