from __future__ import annotations

import importlib.util
import subprocess
from pathlib import Path


REPO_ROOT = Path(__file__).resolve().parents[2]
MODULE_PATH = REPO_ROOT / "scripts" / "rho-agent-run.py"


def load_module():
    spec = importlib.util.spec_from_file_location("rho_agent_run", MODULE_PATH)
    assert spec is not None
    assert spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


agent_run = load_module()


def test_fixture_settings_accepts_record_mode(tmp_path: Path):
    config = {
        "fixture": {
            "mode": "record",
            "root": str(tmp_path / "fixtures"),
            "key": "agent2-generate-code",
            "outputs": ["/output/sum_prices.py"],
        }
    }
    fixture = agent_run.fixture_settings(config, tmp_path)
    assert fixture["mode"] == "record"
    assert fixture["key"] == "agent2-generate-code"
    assert fixture["outputs"] == ["/output/sum_prices.py"]


def test_record_and_replay_fixture_result_round_trip(tmp_path: Path):
    fixture = {
        "mode": "record",
        "root": str(tmp_path / "fixtures"),
        "key": "agent2-generate-code",
        "outputs": ["/output/sum_prices.py"],
    }
    host_output = tmp_path / "sandbox" / "sum_prices.py"
    host_output.parent.mkdir(parents=True, exist_ok=True)
    host_output.write_text("print('555.00')\n", encoding="utf-8")
    result = subprocess.CompletedProcess(
        args=["rho", "agent-run"],
        returncode=0,
        stdout="Done: /output/sum_prices.py\n",
        stderr="",
    )

    agent_run.record_fixture_result(
        fixture,
        result,
        output_resolver=lambda output: host_output,
    )

    host_output.unlink()
    replayed = agent_run.replay_fixture_result(
        fixture,
        output_resolver=lambda output: host_output,
    )
    assert replayed.returncode == 0
    assert "Done:" in replayed.stdout
    assert host_output.read_text(encoding="utf-8") == "print('555.00')\n"


def test_map_guest_path_to_host_prefers_specific_mount(tmp_path: Path):
    repo_root = tmp_path / "repo"
    repo_root.mkdir()
    output_root = tmp_path / "sandbox" / "workspace"
    mounts = [{"host": str(output_root), "guest": "/output", "mode": "rw"}]
    mapped = agent_run.map_guest_path_to_host("/output/sum_prices.py", repo_root, "/app", mounts)
    assert mapped == output_root / "sum_prices.py"
