import importlib
import importlib.util
import sys
import os
import types
from pathlib import Path

import pytest
from fastapi import FastAPI

# 自动添加项目根目录到路径（处理项目结构）
PROJECT_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT_ROOT))


def run_this_test(test_file):
    """自定义函数：运行单个测试文件（类似pytest）"""
    # 提取测试文件名（无扩展名）
    test_name = os.path.splitext(os.path.basename(test_file))[0]
    # 使用pytest运行（自动处理导入）
    pytest.main([test_file, "-v"])


def build_test_app(router, prefix: str = "") -> FastAPI:
    app = FastAPI()
    app.include_router(router, prefix=prefix)
    return app


def load_module_from_path(module_name: str, relative_path: str):
    module_path = PROJECT_ROOT / relative_path
    spec = importlib.util.spec_from_file_location(module_name, module_path)
    module = importlib.util.module_from_spec(spec)
    assert spec and spec.loader
    spec.loader.exec_module(module)
    return module


def install_stub(monkeypatch, name: str, attrs: dict | None = None, package: bool = False):
    module = types.ModuleType(name)
    if package:
        module.__path__ = []
    if attrs:
        for key, value in attrs.items():
            setattr(module, key, value)

    monkeypatch.setitem(sys.modules, name, module)

    parent_name, _, child_name = name.rpartition(".")
    if parent_name:
        parent = sys.modules.get(parent_name)
        if parent is None:
            try:
                parent = importlib.import_module(parent_name)
            except Exception:
                parent = types.ModuleType(parent_name)
                parent.__path__ = []
                monkeypatch.setitem(sys.modules, parent_name, parent)
        setattr(parent, child_name, module)

    return module
