"""Component graph must expose only children confirmed by its source readers."""

from __future__ import annotations

import sys
from pathlib import Path


CONNECTOR = Path(__file__).resolve().parents[2] / "plugins" / "1c" / "connector"
if str(CONNECTOR) not in sys.path:
    sys.path.insert(0, str(CONNECTOR))

import adapter_1c_server as adapter  # noqa: E402


def test_components_aggregate_confirmed_children_without_inference(monkeypatch) -> None:
    object_card = {"ref": "Report.Sales", "kind": "Report", "name": "Sales", "guid": "a" * 36}
    monkeypatch.setattr(
        adapter,
        "metadata_object_modules",
        lambda _: {"status": "ok", "method": "metadata.object.modules", "object": object_card,
                   "modules": [{"role": "object_module", "name": "Модуль объекта", "path": "Report.Sales.МодульОбъекта"}]},
    )
    monkeypatch.setattr(
        adapter,
        "metadata_object_forms",
        lambda _: {"status": "ok", "method": "metadata.object.forms", "object": object_card,
                   "forms": [{"name": "Main", "guid": "b" * 36}]},
    )
    monkeypatch.setattr(
        adapter,
        "metadata_object_templates",
        lambda _: {"status": "ok", "method": "metadata.object.templates", "object": object_card,
                   "templates": [{"name": "ОсновнаяСхемаКомпоновкиДанных", "guid": "c" * 36, "kind": "DataCompositionSchema"}]},
    )

    result = adapter.metadata_object_components(
        {"base_id": "upo_test", "extension": "test2", "ref": "Report.Sales", "include_storage": False}
    )

    assert result["status"] == "ok"
    assert [item["component_kind"] for item in result["components"]] == ["metadata_object", "module", "form", "scd"]
    assert result["components"][2]["read_selector"]["method"] == "metadata.object.form.details"
    assert result["components"][3]["read_selector"]["method"] == "scd.inspect"
    assert result["components"][3]["read_selector"]["params"]["extension"] == "test2"
    assert result["unresolved"] == []


def test_components_marks_a_failed_area_instead_of_creating_a_child(monkeypatch) -> None:
    object_card = {"ref": "CommonForm.t_Форма", "kind": "CommonForm", "name": "t_Форма"}
    monkeypatch.setattr(adapter, "metadata_object_modules", lambda _: {"status": "ok", "object": object_card, "modules": []})
    monkeypatch.setattr(adapter, "metadata_object_forms", lambda _: {"status": "ok", "object": object_card, "forms": []})
    monkeypatch.setattr(adapter, "metadata_object_templates", lambda _: {"status": "unsupported", "error": "not_decoded", "templates": []})

    result = adapter.metadata_object_components({"base_id": "upo_test", "ref": "CommonForm.t_Форма"})

    assert [item["component_kind"] for item in result["components"]] == ["metadata_object"]
    assert result["unresolved"] == [{"area": "templates", "method": "metadata.object.templates", "status": "unsupported", "error": "not_decoded"}]
