"""
版本API集成测试
PM-Agent v2.0 - T-002 API测试框架
"""
import pytest
import sys
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock

sys.path.insert(0, str(Path(__file__).parent.parent.parent))


class TestVersionAPI:
    """版本API测试类"""

    @pytest.fixture
    def client(self):
        """创建测试客户端"""
        from fastapi.testclient import TestClient
        from backend.api.routes import main
        return TestClient(main.app)

    @pytest.fixture
    def mock_version_service(self):
        """Mock VersionService"""
        with patch('backend.api.routes.version.get_version_service') as mock:
            service = MagicMock()
            service.list_versions.return_value = [
                {"version": "v1.0.0", "status": "released"},
                {"version": "v1.1.0", "status": "draft"}
            ]
            service.show_version.return_value = {
                "version": "v1.0.0",
                "status": "released",
                "registered_at": "2026-01-01T00:00:00Z"
            }
            mock.return_value = service
            yield service

    def test_get_versions(self, client, mock_version_service):
        """测试获取版本列表"""
        response = client.get("/api/versions")
        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        mock_version_service.list_versions.assert_called_once()

    def test_get_version_detail(self, client, mock_version_service):
        """测试获取版本详情"""
        response = client.get("/api/versions/v1.0.0")
        assert response.status_code == 200
        data = response.json()
        assert data["version"] == "v1.0.0"
        mock_version_service.show_version.assert_called_with("v1.0.0")

    def test_get_version_not_found(self, client, mock_version_service):
        """测试版本不存在"""
        mock_version_service.show_version.side_effect = Exception("Version not found")
        
        response = client.get("/api/versions/v999.0.0")
        assert response.status_code == 404

    def test_get_current_version(self, client, mock_version_service):
        """测试获取当前版本"""
        mock_version_service.get_current_version.return_value = "v1.1.0"
        
        response = client.get("/api/versions/current")
        assert response.status_code == 200
        data = response.json()
        assert "current_version" in data


class TestVersionAPIRoutes:
    """版本API路由测试"""

    def test_version_endpoint_exists(self):
        """测试版本端点存在"""
        from backend.api.routes import main
        routes = [route.path for route in main.app.routes]
        assert any("/versions" in route for route in routes)

    def test_conf_man_endpoint_exists(self):
        """测试ConfMan端点存在"""
        from backend.api.routes import main
        routes = [route.path for route in main.app.routes]
        assert any("/conf-man" in route for route in routes)
