from __future__ import annotations

import importlib.util
from pathlib import Path
import sys

import yaml


def _load_base_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 = Path(__file__).resolve().parents[2] / "scripts" / "auto_test_domains" / "base.py"
    spec = importlib.util.spec_from_file_location("auto_test_domain_base_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_build_temp_run_profile_uses_explicit_project_prebind(tmp_path: Path) -> None:
    module = _load_base_module()

    source_profile = tmp_path / "source.yaml"
    source_profile.write_text(
        yaml.safe_dump(
            {
                "local_datasource": {"handler_configs": {"project": {"data_id_filter": ["old-local"]}}},
                "remote_datasource": {"handler_configs": {"project": {"data_id_filter": ["old-remote"]}}},
                "strategies": {"project": {"config": {}}},
            },
            allow_unicode=True,
            sort_keys=False,
        ),
        encoding="utf-8",
    )

    config = {
        "pipeline": {
            "run_profile": str(source_profile),
            "command": ["python", "run.py", "--config_path", "placeholder.yaml"],
        }
    }

    profile_path, command = module.build_temp_run_profile_for_project_auto_bind(
        config=config,
        report_root=tmp_path,
        profile_name="demo",
        local_project_id="local-project",
        remote_project_id="remote-project",
    )

    profile = yaml.safe_load(Path(profile_path).read_text(encoding="utf-8"))
    project_config = profile["strategies"]["project"]["config"]

    assert profile["local_datasource"]["handler_configs"]["project"]["data_id_filter"] == ["local-project"]
    assert profile["remote_datasource"]["handler_configs"]["project"]["data_id_filter"] == ["remote-project"]
    assert project_config["auto_bind"] is False
    assert project_config["auto_bind_fields"] == []
    assert project_config["pre_bind_data_id"] == [
        {"local_data_id": "local-project", "remote_data_id": "remote-project"}
    ]
    assert command[-1] == profile_path
