from __future__ import annotations

import sys
from pathlib import Path

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

from resolve_1c_bsl_symbol import load_json, resolve_symbol  # noqa: E402


METADATA = ROOT / "plugins" / "1c" / "metadata" / "examples" / "metadata-v2.example.json"
MODULES = ROOT / "plugins" / "1c" / "metadata" / "examples" / "bsl-modules.example.json"


def resolve(expression: str, **kwargs: str) -> dict:
    return resolve_symbol(
        load_json(METADATA),
        load_json(MODULES),
        expression=expression,
        object_kind="catalog",
        object_name="Номенклатура",
        module_id="catalog.Номенклатура.object",
        routine_name="ПередЗаписью",
        **kwargs,
    )


def test_full_metadata_path_resolves_as_metadata() -> None:
    result = resolve("Справочник.Номенклатура.Артикул")

    assert result["status"] == "resolved"
    assert result["resolution_kind"] == "metadata_path"
    assert result["canonical_path"] == "Справочник.Номенклатура.Артикул"
    assert result["safe_as_metadata_path"] is True


def test_object_module_attribute_resolves_from_context() -> None:
    result = resolve("Наименование")

    assert result["status"] == "resolved"
    assert result["resolution_kind"] == "context_metadata_member"
    assert result["canonical_path"] == "Справочник.Номенклатура.Наименование"
    assert result["context_path"] == "Наименование"


def test_routine_parameter_wins_over_metadata_guess() -> None:
    result = resolve("Отказ.Код")

    assert result["status"] == "resolved"
    assert result["resolution_kind"] == "parameter"
    assert result["context_path"] == "Отказ.Код"
    assert result["safe_as_metadata_path"] is False


def test_short_object_name_is_candidate_not_metadata_path() -> None:
    result = resolve("Номенклатура.ЕдИзмерение.Код")

    assert result["status"] == "unresolved"
    assert result["safe_as_metadata_path"] is False
    assert result["candidates"][0]["canonical_path"] == "Справочник.Номенклатура"
    assert result["candidates"][0]["reason"] == "short_object_name_requires_kind"
