"""
Test KEGG utilities
"""
import pytest
from unittest.mock import Mock, patch
from pathlib import Path

from juicekeggers.utils.kegg import (
    kegg_api_get, kegg_list, kegg_find,
    parse_kegg_response, download_kegg_file
)


def test_parse_kegg_response():
    """Test parsing KEGG API response."""
    response = """ENTRY       K00001
NAME        alcohol dehydrogenase
PATHWAY     ko00010  Glycolysis / Gluconeogenesis
DBLINKS     RN: R00299
"""
    
    parsed = parse_kegg_response(response, "ko")
    
    assert parsed["ENTRY"] == "K00001"
    assert "alcohol dehydrogenase" in parsed["NAME"]
    assert "ko00010" in parsed["PATHWAY"]


@patch('juicekeggers.utils.kegg.urllib.request.urlopen')
def test_kegg_api_get_http_fallback(mock_urlopen):
    """Test KEGG API get with HTTP fallback."""
    # Mock response
    mock_response = Mock()
    mock_response.read.return_value = b"ENTRY\tK00001\nNAME\tTest"
    mock_urlopen.return_value.__enter__.return_value = mock_response
    
    result = kegg_api_get("K00001", "ko", max_retries=1)
    
    assert "ENTRY" in result
    assert "K00001" in result
    mock_urlopen.assert_called()


@patch('juicekeggers.utils.kegg.BIOPYTHON_AVAILABLE', False)
@patch('juicekeggers.utils.kegg.urllib.request.urlopen')
def test_kegg_api_get_without_biopython(mock_urlopen):
    """Test KEGG API get without BioPython."""
    mock_response = Mock()
    mock_response.read.return_value = b"mock data"
    mock_urlopen.return_value.__enter__.return_value = mock_response
    
    result = kegg_api_get("test", max_retries=1)
    
    assert result == "mock data"
    mock_urlopen.assert_called()


def test_kegg_list_parsing():
    """Test KEGG list parsing."""
    mock_response = """hsa:1234\tHuman gene 1
hsa:5678\tHuman gene 2
"""
    
    with patch('juicekeggers.utils.kegg.kegg_api_get') as mock_get:
        mock_get.return_value = mock_response
        
        result = kegg_list("hsa")
        
        assert len(result) == 2
        assert result[0][0] == "hsa:1234"
        assert result[0][1] == "Human gene 1"
        assert result[1][0] == "hsa:5678"


def test_kegg_find_parsing():
    """Test KEGG find parsing."""
    mock_response = """ko:K00001\talcohol dehydrogenase
ko:K00002\taldehyde dehydrogenase
"""
    
    with patch('juicekeggers.utils.kegg.kegg_api_get') as mock_get:
        mock_get.return_value = mock_response
        
        result = kegg_find("ko", "alcohol")
        
        assert len(result) == 2
        assert "alcohol dehydrogenase" in result[0][1]


@patch('juicekeggers.utils.kegg.urllib.request.urlopen')
def test_download_kegg_file(mock_urlopen, temp_dir):
    """Test downloading KEGG file."""
    mock_response = Mock()
    mock_response.read.return_value = b"KEGG file content"
    mock_urlopen.return_value.__enter__.return_value = mock_response
    
    output_path = download_kegg_file("ko00001", temp_dir, "keg")
    
    assert output_path.exists()
    assert output_path.name == "ko00001.keg"
    assert output_path.read_text() == "KEGG file content"
    
    # Test skipping existing file
    mock_urlopen.reset_mock()
    output_path2 = download_kegg_file("ko00001", temp_dir, "keg")
    mock_urlopen.assert_not_called()  # Should skip download
    assert output_path2 == output_path
	