from __future__ import annotations
import importlib
import importlib.util
from pathlib import Path
import pytest

ROOT = Path(__file__).parent
LAUNCHER = ROOT / "launch_v3.py"
PROFILE = Path("/home/cube/.hermes/profiles/dualcoachtest")
PACKAGE = Path("/home/cube/.hermes/profiles/dualcoachtest/.strict-runtime/dac4e812/venv/lib/python3.12/site-packages")
spec = importlib.util.spec_from_file_location("launch_v3", LAUNCHER)
assert spec is not None and spec.loader is not None
launch = importlib.util.module_from_spec(spec)
spec.loader.exec_module(launch)


def pure_profile_modules(package_root: Path) -> tuple[Path, Path]:
    registration = importlib.import_module(
        "gateway.platforms.telegram_customer_bootstrap_registration"
    )
    instance = object.__new__(registration.TelegramCustomerBootstrapRegistration)
    instance.package_root = package_root
    admin, coaching = instance._profile_modules()
    return Path(admin.__file__).resolve(), Path(coaching.__file__).resolve()


def test_transient_gateway_binds_installed_profile_package() -> None:
    # Match gateway startup: installed profile modules are already imported before /start.
    importlib.import_module("checkin_cli.customer_admin")
    importlib.import_module("checkin_cli.customer_coaching")

    with pytest.raises(Exception, match="loaded checkin_cli is not profile-local"):
        pure_profile_modules(PROFILE / "workspace/checkin_cli")

    admin, coaching = pure_profile_modules(PACKAGE)
    assert admin == PACKAGE / "checkin_cli/customer_admin.py"
    assert coaching == PACKAGE / "checkin_cli/customer_coaching.py"

    expected = f"--setenv=DUALCOACH_PROFILE_PACKAGE={PACKAGE}"
    assert expected in LAUNCHER.read_text()
