#!/usr/bin/env python
"""
测试新增 API 集成

验证新的认证、用户管理和审计日志接口是否正确集成
"""

import sys
import os
import pytest

# 将项目根目录添加到 sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))


@pytest.mark.parametrize(
    "module_name, desc",
    [
        ("app.core.encryption", "加密模块"),
        ("app.core.security", "安全模块"),
        ("app.core.audit", "审计模块"),
        ("app.domain.models.role", "角色模型"),
        ("app.domain.schemas.user", "用户Schema"),
        ("app.domain.schemas.audit", "审计Schema"),
        ("app.auth.permissions", "权限控制"),
        ("app.api.v1.endpoints.auth", "认证接口"),
        ("app.api.v1.endpoints.user_management", "用户管理接口"),
        ("app.api.v1.endpoints.audit", "审计日志接口"),
        ("app.infra.repositories.user_repository", "用户仓储"),
        ("app.infra.repositories.audit_repository", "审计仓储"),
        ("app.infra.audit.middleware", "审计中间件"),
    ],
)
def test_module_imports(module_name, desc):
    """检查关键模块是否可以导入"""
    try:
        __import__(module_name)
    except ImportError as e:
        pytest.fail(f"无法导入 {desc} ({module_name}): {e}")


def test_router_configuration():
    """检查路由配置"""
    try:
        from app.api.v1 import router

        # 检查 router 中是否包含新增的路由
        api_router = router.api_router
        routes = [r.path for r in api_router.routes if hasattr(r, "path")]

        # 验证基础路径是否存在
        assert any("/auth" in r for r in routes), "缺少认证相关路由 (/auth)"
        assert any("/users" in r for r in routes), "缺少用户管理路由 (/users)"
        assert any("/audit" in r for r in routes), "缺少审计日志路由 (/audit)"

    except Exception as e:
        pytest.fail(f"路由配置检查失败: {e}")


def test_main_app_initialization():
    """检查 main.py 配置"""
    try:
        from app.main import app

        assert app is not None
        assert app.title != ""

        # 检查中间件 (简单检查是否存在)
        middleware_names = [m.cls.__name__ for m in app.user_middleware]
        # 检查是否包含审计中间件或其他关键中间件（根据实际类名修改）
        assert "AuditMiddleware" in middleware_names, "缺少审计中间件"

        # 检查路由总数
        assert len(app.routes) > 0

    except Exception as e:
        pytest.fail(f"main.py 配置检查失败: {e}")
