from __future__ import annotations

import importlib.util
from pathlib import Path
import sys


def _load_case_module():
    scripts_dir = Path(__file__).resolve().parents[2] / "scripts"
    if str(scripts_dir) not in sys.path:
        sys.path.insert(0, str(scripts_dir))
    file_path = scripts_dir / "auto_test_domains" / "project_case.py"
    spec = importlib.util.spec_from_file_location("project_case_for_test", file_path)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load module from {file_path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def test_project_case_round_3_focuses_on_stable_readback_fields(monkeypatch, tmp_path: Path) -> None:
    module = _load_case_module()
    captured_rounds: dict[str, dict] = {}

    def _fake_run_pipeline_round(**kwargs):
        captured_rounds[kwargs["round_name"]] = kwargs
        return {"name": kwargs["round_name"], "passed": True, "issues": []}

    def _fake_build_domain_report(**kwargs):
        return kwargs

    monkeypatch.setattr(module, "run_pipeline_round", _fake_run_pipeline_round)
    monkeypatch.setattr(module, "build_domain_report", _fake_build_domain_report)

    module.run_case(config={"project_root": str(tmp_path)}, report_root=tmp_path)

    round_3 = captured_rounds["round_3_investment_update"]
    expected_fields = round_3["expected_bound_fields"]["remote"]["project"][module.LOCAL_PROJECT_ID]
    changed_fields = round_3["expected_changes"]["project"][module.LOCAL_PROJECT_ID]

    assert set(changed_fields) == {
        "investment_decision_capacity",
        "investment_decision_date",
        "complete_investment",
        "dynamic_investment",
    }
    assert set(expected_fields.keys()) == {
        "investment_decision_capacity",
        "investment_decision_date",
        "complete_investment",
        "dynamic_investment",
    }
    assert "PUT /project/settlement_investment" in round_3["coverage"]["api"]
