"""
Test parsers
"""
import pytest
from pathlib import Path

from juicekeggers.utils.parsers import (
    parse_org_file, parse_kegg_file, parse_ko_file,
    parse_pathway_file, parse_compound_file
)


def test_parse_org_file(temp_dir):
    """Test parsing organism file."""
    org_data = """hsa\tHomo sapiens\tftp://example.com/hsa
mmu\tMus musculus\tftp://example.com/mmu
# Comment line
eco\tE. coli\t\t# Missing URL
"""
    
    org_file = temp_dir / "organisms.tsv"
    org_file.write_text(org_data)
    
    result = parse_org_file(org_file)
    
    assert len(result) == 3  # Includes eco with empty URL
    assert result[0]["org_code"] == "hsa"
    assert result[0]["name"] == "Homo sapiens"
    assert result[0]["url"] == "ftp://example.com/hsa"
    assert result[2]["url"] == ""  # Empty URL for eco


def test_parse_kegg_file(sample_keg_file):
    """Test parsing KEGG file."""
    result = parse_kegg_file(sample_keg_file)
    
    assert len(result) == 3  # 3 gene entries
    assert result[0]["gene_id"] == "abc001"
    assert result[0]["ko_id"] == "K00001"
    assert result[0]["pathway"] == "ko00010"
    assert "alcohol dehydrogenase" in result[0]["ko_description"]


def test_parse_ko_file(sample_keg_file):
    """Test parsing KO file."""
    result = parse_ko_file(sample_keg_file)
    
    assert "ko00010" in result
    assert "ko00020" in result
    assert len(result["ko00010"]) == 2
    assert len(result["ko00020"]) == 1
    
    # Check gene mappings
    ko00010_genes = [g["gene_id"] for g in result["ko00010"]]
    assert "abc001" in ko00010_genes
    assert "abc002" in ko00010_genes
    assert "K00001" in [g["ko_id"] for g in result["ko00010"]]


def test_parse_pathway_file(temp_dir):
    """Test parsing pathway file."""
    pathway_data = """###PATHWAY
ko00010
Glycolysis / Gluconeogenesis
###MODULE
M00001
Glycolysis (Embden-Meyerhof pathway)
"""
    
    pathway_file = temp_dir / "pathway.txt"
    pathway_file.write_text(pathway_data)
    
    result = parse_pathway_file(pathway_file)
    
    assert "PATHWAY" in result
    assert "MODULE" in result
    assert result["PATHWAY"][0] == "ko00010"
    assert "Glycolysis" in result["PATHWAY"][1]
    assert result["MODULE"][0] == "M00001"


def test_parse_compound_file(temp_dir):
    """Test parsing compound file."""
    compound_data = """ENTRY       C00001
NAME        H2O; Water
FORMULA     H2O
EXACT_MASS  18.0106
MOL_WEIGHT  18.0153

ENTRY       C00002
NAME        ATP; Adenosine 5'-triphosphate
FORMULA     C10H16N5O13P3

"""
    
    compound_file = temp_dir / "compound.txt"
    compound_file.write_text(compound_data)
    
    result = parse_compound_file(compound_file)
    
    assert len(result) == 2
    assert result[0]["entry"] == "C00001"
    assert result[0]["name"] == "H2O; Water"
    assert result[0]["formula"] == "H2O"
    assert result[0]["exact_mass"] == "18.0106"
    
    assert result[1]["entry"] == "C00002"
    assert "ATP" in result[1]["name"]
	