from __future__ import annotations

import ast
import os
import subprocess
import sys
from pathlib import Path

import pytest


ROOT = Path(__file__).resolve().parents[1]


def _imported_modules(path: Path) -> set[str]:
    tree = ast.parse(path.read_text(encoding="utf-8"))
    modules: set[str] = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            modules.update(alias.name for alias in node.names)
        if isinstance(node, ast.ImportFrom) and node.module is not None:
            modules.add(node.module)
    return modules


def _pythonpath() -> str:
    src = str(ROOT / "src")
    existing = os.environ.get("PYTHONPATH")
    if existing:
        return f"{src}{os.pathsep}{existing}"
    return src


def test_bonds_api_does_not_import_analytics() -> None:
    modules = _imported_modules(ROOT / "src" / "fuggers_py" / "bonds" / "_api.py")
    assert not any(module.startswith("fuggers_py.analytics") for module in modules)


def test_pricing_specs_use_bonds_types_for_asset_swap_type() -> None:
    modules = _imported_modules(ROOT / "src" / "fuggers_py" / "data" / "pricing_specs.py")
    assert "fuggers_py.bonds.types" in modules
    assert "fuggers_py.analytics.spreads.asw" not in modules


def test_bonds_root_import_does_not_load_analytics() -> None:
    env = dict(os.environ)
    env["PYTHONPATH"] = _pythonpath()
    completed = subprocess.run(
        [
            sys.executable,
            "-c",
            (
                "import json, sys; "
                "import fuggers_py.bonds; "
                "print(json.dumps(sorted(name for name in sys.modules if name.startswith('fuggers_py.analytics'))))"
            ),
        ],
        cwd=ROOT,
        env=env,
        check=True,
        capture_output=True,
        text=True,
    )

    assert completed.stdout.strip() == "[]"


@pytest.mark.parametrize("module_name", ["fuggers_py.rates", "fuggers_py.funding", "fuggers_py.credit"])
def test_new_domain_roots_do_not_load_analytics(module_name: str) -> None:
    env = dict(os.environ)
    env["PYTHONPATH"] = _pythonpath()
    completed = subprocess.run(
        [
            sys.executable,
            "-c",
            (
                "import importlib, json, sys; "
                f"importlib.import_module('{module_name}'); "
                "print(json.dumps(sorted(name for name in sys.modules if name.startswith('fuggers_py.analytics'))))"
            ),
        ],
        cwd=ROOT,
        env=env,
        check=True,
        capture_output=True,
        text=True,
    )

    assert completed.stdout.strip() == "[]"
