from __future__ import annotations

import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
CONNECTOR = ROOT / "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_additional_attributes_find_reports_empty_source_not_silent_empty(monkeypatch) -> None:
    monkeypatch.setattr(adapter, "require_base_id", lambda _payload, _method: "upo_test")
    monkeypatch.setattr(
        adapter,
        "data_read",
        lambda _payload, method: {
            "status": "ok",
            "object": {"ref": "ChartOfCharacteristicTypes.ДополнительныеРеквизитыИСведения"},
            "rows": [],
            "counts": {"rows": 0},
            "route_diagnostics": {"status": "empty_source", "source_count": 0},
        },
    )

    result = adapter.additional_attributes_find({"base_id": "upo_test", "query": "Ответственное направление"})

    assert result["status"] == "empty_source"
    assert result["properties"] == []
    assert result["diagnostics"]["route"]["source_count"] == 0


def test_additional_attributes_storage_refuses_to_guess_storage_route() -> None:
    result = adapter.additional_attributes_storage_resolve(
        {
            "base_id": "upo_test",
            "property_ref": "0123456789ABCDEF0123456789ABCDEF",
            "owner_ref": "Catalog.СтруктурныеЕдиницы",
        }
    )

    assert result["status"] == "unresolved"
    assert result["storage"] is None
    assert "will not infer" in result["diagnostics"]["message"]


def test_additional_attributes_storage_confirms_metadata_evidenced_route(monkeypatch) -> None:
    monkeypatch.setattr(adapter, "list_objects", lambda *_args, **_kwargs: {"objects": [{"ref": "InformationRegister.ДополнительныеСведения"}]})
    monkeypatch.setattr(
        adapter,
        "metadata_object_attributes",
        lambda _payload: {
            "status": "ok",
            "dimensions": [
                {"name": "Объект", "type": {"kind": "reference"}},
                {"name": "Свойство", "type": {"resolved": {"kind": "ChartOfCharacteristicTypes", "name": "ДополнительныеРеквизитыИСведения"}}},
            ],
            "resources": [{"name": "Значение", "type": {"kind": "composite"}}],
        },
    )

    result = adapter.additional_attributes_storage_resolve(
        {
            "base_id": "upo_test",
            "property_ref": "0123456789ABCDEF0123456789ABCDEF",
            "owner_ref": "Catalog.СтруктурныеЕдиницы",
        }
    )

    assert result["status"] == "confirmed"
    assert result["storage"]["source_ref"] == "InformationRegister.ДополнительныеСведения"
    assert result["storage"]["fields"] == {"object": "Объект", "property": "Свойство", "value": "Значение"}
    assert result["scd_join"]["parameters"]["Свойство"] == "0123456789ABCDEF0123456789ABCDEF"


def test_additional_attributes_storage_requires_public_inputs() -> None:
    result = adapter.additional_attributes_storage_resolve({"base_id": "upo_test", "owner_ref": "Catalog.СтруктурныеЕдиницы"})

    assert result["status"] == "invalid_argument"
    assert result["argument"] == "property_ref"


def test_chart_semantics_exposes_only_evidenced_chart_level_value_types(monkeypatch) -> None:
    monkeypatch.setattr(adapter, "config_tree_item_at_path", lambda _tree, path: {"path": path})
    monkeypatch.setattr(adapter, "public_pattern_value_type", lambda *_args, **_kwargs: {"kind": "union", "count": 2})

    result = adapter.chart_of_characteristic_types_sql_details("upo_test", {"type": "list"}, table="Config", timeout_seconds=30)

    assert result["allowed_value_types"] == {"kind": "union", "count": 2}
    assert result["evidence"]["config_path"] == "1.18"


def test_chart_data_list_accepts_description_contains_filter(monkeypatch) -> None:
    monkeypatch.setattr(
        adapter,
        "data_object_schema",
        lambda _payload: {
            "status": "ok",
            "base_id": "upo_test",
            "table": {"name": "_Chrc1"},
            "object": {"kind": "ChartOfCharacteristicTypes"},
            "fields": [
                {"name": "ref", "physical_name": "_IDRRef", "type": {}},
                {"name": "description", "physical_name": "_Description", "type": {}},
                {"name": "marked_for_deletion", "physical_name": "_Marked", "type": {}},
            ],
        },
    )
    captured: dict[str, object] = {}

    def fake_sql(_base_id, sql, params, **_kwargs):
        captured["sql"] = sql
        captured["params"] = params
        return [], None

    monkeypatch.setattr(adapter, "data_sql_rows", fake_sql)
    result = adapter.data_read(
        {
            "base_id": "upo_test",
            "ref": "ChartOfCharacteristicTypes.Тест",
            "fields": ["ref", "description"],
            "filters": {"description": {"operator": "contains", "value": "Ответственное направление"}},
        }
    )

    assert result["status"] == "ok"
    assert "[_Description] LIKE %s" in str(captured["sql"])
    assert "%Ответственное направление%" in captured["params"]


def test_password_test_mode_accepts_explicit_global_unauthenticated_profile(monkeypatch) -> None:
    monkeypatch.delenv("ONEC_INFOBASE_USER_ADMIN_ALLOW_UNAUTHENTICATED", raising=False)
    monkeypatch.setenv("ONEC_ADAPTER_ALLOW_UNAUTHENTICATED_ADMIN", "true")

    assert adapter.infobase_user_password_unauthenticated_test_mode() is True
