from __future__ import annotations

from pathlib import Path
from uuid import uuid4

import pytest
from fastapi.testclient import TestClient

from tests.orchestrator_dual_harness import OrchestratorDualHubHarness, make_enterprise


def test_recipe_ingredient_tree_roundtrip(client: TestClient):
    enterprise_id = make_enterprise(client)
    harness = OrchestratorDualHubHarness(client, enterprise_id)
    hub_a, hub_b = harness.pair_hubs()
    recipe_id = "recipe-tree-1"
    ing_id = "ing-tree-1"
    comp_id = "comp-tree-1"
    harness.push_from(
        hub_a,
        [
            harness.make_component_event(hub_a, comp_id, name="Barley", version=1, content_hash="c1"),
            {
                "event_id": str(uuid4()),
                "seq": 2,
                "domain": "global",
                "table": "recipe",
                "record_id": recipe_id,
                "action": "upsert",
                "version": 1,
                "content_hash": "r1",
                "payload": {
                    "id": recipe_id,
                    "name": "Mix A",
                    "heads_per_trip": 100,
                    "ingredients": [{"id": ing_id, "component_id": comp_id, "name": "Barley", "amount": 10}],
                    "version": 1,
                    "content_hash": "r1",
                },
                "emitted_at": "2026-07-15T12:00:00Z",
                "origin_site_id": hub_a.hub_site_id,
            },
            {
                "event_id": str(uuid4()),
                "seq": 3,
                "domain": "global",
                "table": "ingredient",
                "record_id": ing_id,
                "action": "upsert",
                "version": 1,
                "content_hash": "i1",
                "payload": {
                    "id": ing_id,
                    "recipe_id": recipe_id,
                    "component_id": comp_id,
                    "name": "Barley",
                    "amount": 10.0,
                    "version": 1,
                    "content_hash": "i1",
                },
                "emitted_at": "2026-07-15T12:00:01Z",
                "origin_site_id": hub_a.hub_site_id,
            },
        ],
    )
    harness.drain([hub_b])
    recipe = harness.get_catalog(hub_b, "recipe", recipe_id)
    assert recipe is not None
    assert recipe.get("name") == "Mix A"
    ing = harness.get_catalog(hub_b, "ingredient", ing_id)
    assert ing is not None
    assert ing.get("component_id") == comp_id
