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))

import scripts.smoke_1c_write_preflight as smoke  # noqa: E402


def test_repository_lock_is_a_valid_preflight_classification() -> None:
    assert smoke.classified_preflight_status("needs_repository_lock") is True
    assert smoke.classified_preflight_status("unexpected") is False


def test_saved_module_target_prefers_bounded_stream(monkeypatch) -> None:
    whole_form = {
        "kind": "module",
        "module_ref": "ConfigCASSave:extension__form.0",
        "file_name": "extension__form.0",
        "module_path": "2",
    }
    bounded_stream = {
        "kind": "module",
        "module_ref": "ConfigSave:module.3#stream:4",
        "file_name": "module.3",
        "stream_index": 4,
    }

    def fake_rpc_call(
        _endpoint_url: str,
        method: str,
        _payload: dict[str, Any],
        _timeout: float,
        *,
        transport: str,
        session_id: str | None,
    ) -> dict[str, Any]:
        assert method == "metadata.saved_state.modules.search"
        assert transport == "rest"
        assert session_id is None
        return {
            "status": "ok",
            "modules": [
                {"streams": [{"write_plan_target": whole_form}]},
                {"streams": [{"write_plan_target": bounded_stream}]},
            ],
        }

    monkeypatch.setattr(smoke, "rpc_call", fake_rpc_call)

    result = smoke.first_saved_module_target(
        "http://adapter",
        "upo_test",
        30,
        transport="rest",
        session_id=None,
    )

    assert result == bounded_stream
