"""
FastAPI 엔드포인트 테스트
"""
import pytest
from fastapi.testclient import TestClient
from pathlib import Path
import sys

# 프로젝트 루트 디렉토리를 Python 경로에 추가
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from src.api.main import app

client = TestClient(app)


def test_root():
    """루트 엔드포인트 테스트"""
    response = client.get("/")
    assert response.status_code == 200
    data = response.json()
    assert data["service"] == "Vector DB 통합 시스템"
    assert data["version"] == "1.0.0"


def test_search_terms_keyword():
    """용어 키워드 검색 테스트"""
    response = client.post(
        "/api/terms/search",
        json={
            "query": "API",
            "search_type": "keyword",
            "top_k": 5,
            "confidence_threshold": 0.7
        }
    )
    assert response.status_code == 200
    results = response.json()
    assert isinstance(results, list)

    if len(results) > 0:
        result = results[0]
        assert "term" in result
        assert "relevance_score" in result
        assert "match_type" in result


def test_search_terms_vector():
    """용어 벡터 검색 테스트"""
    response = client.post(
        "/api/terms/search",
        json={
            "query": "회의 일정 관리",
            "search_type": "vector",
            "top_k": 3,
            "confidence_threshold": 0.6
        }
    )
    assert response.status_code == 200
    results = response.json()
    assert isinstance(results, list)


def test_search_terms_hybrid():
    """용어 하이브리드 검색 테스트"""
    response = client.post(
        "/api/terms/search",
        json={
            "query": "마이크로서비스",
            "search_type": "hybrid",
            "top_k": 5,
            "confidence_threshold": 0.5
        }
    )
    assert response.status_code == 200
    results = response.json()
    assert isinstance(results, list)


def test_get_term_stats():
    """용어 통계 조회 테스트"""
    response = client.get("/api/terms/stats")
    assert response.status_code == 200
    stats = response.json()
    assert "total_terms" in stats
    assert "by_category" in stats
    assert "avg_confidence" in stats


def test_search_documents():
    """관련 문서 검색 테스트"""
    response = client.post(
        "/api/documents/search",
        json={
            "query": "프로젝트 계획",
            "top_k": 3,
            "relevance_threshold": 0.3,
            "semantic_ranking": True
        }
    )
    assert response.status_code == 200
    results = response.json()
    assert isinstance(results, list)

    if len(results) > 0:
        result = results[0]
        assert "document_id" in result
        assert "title" in result
        assert "content" in result
        assert "relevance_score" in result


def test_search_documents_with_filters():
    """필터링된 문서 검색 테스트"""
    response = client.post(
        "/api/documents/search",
        json={
            "query": "회의록",
            "top_k": 5,
            "relevance_threshold": 0.3,
            "document_type": "회의록",
            "semantic_ranking": True
        }
    )
    assert response.status_code == 200
    results = response.json()
    assert isinstance(results, list)


def test_get_document_stats():
    """문서 통계 조회 테스트"""
    response = client.get("/api/documents/stats")
    assert response.status_code == 200
    stats = response.json()
    assert "total_documents" in stats
    assert "by_type" in stats
    assert "total_chunks" in stats


def test_get_nonexistent_term():
    """존재하지 않는 용어 조회 테스트"""
    response = client.get("/api/terms/nonexistent-term-id")
    assert response.status_code == 404


def test_explain_term():
    """용어 설명 생성 테스트 (Claude AI)"""
    # 먼저 용어 검색
    search_response = client.post(
        "/api/terms/search",
        json={
            "query": "API",
            "search_type": "keyword",
            "top_k": 1
        }
    )

    if search_response.status_code == 200:
        results = search_response.json()
        if len(results) > 0:
            term_id = results[0]["term"]["term_id"]

            # 용어 설명 생성
            explain_response = client.post(
                f"/api/terms/{term_id}/explain",
                json={
                    "meeting_context": "백엔드 개발 회의에서 REST API 설계 논의"
                }
            )

            assert explain_response.status_code == 200
            explanation = explain_response.json()
            assert "term" in explanation
            assert "explanation" in explanation
            assert "generated_by" in explanation


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
