"""Extension CommonForm decoding must use the manifest payload route, not its GUID as a file name."""

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_common_form_uses_extension_manifest_route(monkeypatch) -> None:
    form_guid = "e7517ee6-7e33-40ba-9442-48c78e0818e1"
    captured: dict[str, str] = {}

    monkeypatch.setattr(
        adapter,
        "extension_objects_find",
        lambda _payload: {
            "status": "ok",
            "objects": [{
                "kind": "CommonForm",
                "name": "ФормаОтчетаПродкорзина",
                "guid": form_guid,
                "route": {"table": "ConfigCAS", "file_name": "manifest-hash-key"},
            }],
        },
    )

    def fake_read(_base_id, table, file_name, **_kwargs):
        captured["table"] = table
        captured["file_name"] = file_name
        return None, None, {"status": "source_missing", "diagnostics": {"message": "fixture stop"}}

    monkeypatch.setattr(adapter, "read_storage_file_bytes", fake_read)

    result = adapter.metadata_form_decode(
        {
            "base_id": "upo_test",
            "kind": "CommonForm",
            "extension": "фс_Отчеты1",
            "name": "ФормаОтчетаПродкорзина",
            "guid": form_guid,
            "source_state": "active",
        }
    )

    assert result["status"] == "source_missing"
    assert captured == {"table": "ConfigCAS", "file_name": "manifest-hash-key"}


def test_static_form_structure_marks_unproven_tree_edges() -> None:
    structure = adapter.form_static_structure(
        {"items": [{"id": "1", "name": "Настройки", "type_name": "Группа", "path": "1.7", "depth": 2}]}
    )
    assert structure["status"] == "partial"
    assert structure["elements"][0]["parent"]["status"] == "unresolved"
    assert structure["elements"][0]["children"]["status"] == "unresolved"
