from __future__ import annotations

import importlib

run_case_module = importlib.import_module("run_tools.run_case")
run_case_cli_module = importlib.import_module("run_tools.run_case_cli")


class _FakeMacroEnergy:
    def __init__(self) -> None:
        self.called = False
        self.case_path = None
        self.kwargs = None

    def run_case(self, case_path, **kwargs):
        self.called = True
        self.case_path = case_path
        self.kwargs = kwargs
        return (["system-a"], {"ok": True})


def test_run_case_passes_case_path_and_kwargs(monkeypatch):
    fake_macro = _FakeMacroEnergy()
    monkeypatch.setattr(run_case_module, "_macroenergy_module", lambda: fake_macro)

    systems, solution = run_case_module.run_case("/tmp/case", lazy_load=False)

    assert fake_macro.called is True
    assert fake_macro.case_path == "/tmp/case"
    assert fake_macro.kwargs == {"lazy_load": False}
    assert systems == ["system-a"]
    assert solution == {"ok": True}


def test_run_case_cli_builds_expected_kwargs(monkeypatch):
    captured = {}

    def fake_run_case(case_path, **kwargs):
        captured["case_path"] = case_path
        captured["kwargs"] = kwargs
        return (["system-a"], None)

    monkeypatch.setattr(run_case_cli_module, "run_case", fake_run_case)
    monkeypatch.setattr(run_case_cli_module, "_parse_log_level", lambda _: "INFO_LEVEL")
    monkeypatch.setattr(
        run_case_cli_module,
        "setup_macroenergy_jl",
        lambda **_: (_ for _ in ()).throw(AssertionError("setup should not run")),
    )
    monkeypatch.setattr(
        "sys.argv",
        [
            "macroenergy-run-case",
            "./case",
            "--no-lazy-load",
            "--no-log-to-console",
            "--log-level",
            "Info",
        ],
    )

    exit_code = run_case_cli_module.main()

    assert exit_code == 0
    assert captured["case_path"] == "./case"
    assert captured["kwargs"]["lazy_load"] is False
    assert captured["kwargs"]["log_to_console"] is False
    assert captured["kwargs"]["log_level"] == "INFO_LEVEL"
