from __future__ import annotations

import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "plugins" / "1c"))

from parser.common_command import (  # noqa: E402
    common_command_group_guid,
    index_common_command_groups,
    parse_common_command_tree,
)
from parser.payload import serialize_brace_tree  # noqa: E402


def command_tree(group_guid: str) -> dict[str, Any]:
    atom = lambda value: {"type": "atom", "value": str(value)}
    sequence = lambda *items: {"type": "list", "items": list(items)}
    root = sequence()
    node = root
    path = (1, 1, 2, 7, 1)
    for index in path[:-1]:
        items = node.setdefault("items", [])
        while len(items) <= index:
            items.append(sequence())
        node = items[index]
    items = node.setdefault("items", [])
    while len(items) <= path[-1]:
        items.append(sequence())
    items[path[-1]] = atom(group_guid)
    return root


def payload(group_guid: str) -> bytes:
    return serialize_brace_tree(command_tree(group_guid)).encode("utf-8")


def test_common_command_group_guid_decodes_observed_relation() -> None:
    group_guid = "11111111-1111-1111-1111-111111111111"
    tree = parse_common_command_tree(payload(group_guid))

    assert common_command_group_guid(tree) == group_guid


def test_common_command_reverse_index_groups_rows_and_reports_gaps() -> None:
    group_guid = "11111111-1111-1111-1111-111111111111"
    first_guid = "22222222-2222-2222-2222-222222222222"
    broken_guid = "33333333-3333-3333-3333-333333333333"
    missing_guid = "44444444-4444-4444-4444-444444444444"
    commands = [
        {"guid": first_guid, "name": "Первая"},
        {"guid": broken_guid, "name": "Поврежденная"},
        {"guid": missing_guid, "name": "Без файла"},
    ]

    result = index_common_command_groups(
        commands,
        {
            first_guid.upper(): payload(group_guid),
            broken_guid: b"not a Config tree",
        },
    )

    assert result["groups"][group_guid] == [{"guid": first_guid, "name": "Первая"}]
    assert result["scanned"] == 3
    assert result["source_missing"] == 1
    assert result["undecodable"] == 1
    assert result["unassigned"] == 0
