import pytest
from unittest.mock import patch, MagicMock
import subprocess
from slicer_utils import slice_model

def test_slice_model_success():
    # Mock output from PrusaSlicer --info
    mock_stdout = """
    volume = 12345.678
    size_x = 50.0
    size_y = 50.0
    size_z = 10.0
    """
    
    with patch("subprocess.run") as mock_run, \
         patch("shutil.which", return_value="/usr/bin/prusa-slicer"):
        
        mock_run.return_value = MagicMock(stdout=mock_stdout, check=True)
        
        result = slice_model("dummy.stl")
        
        assert result is not None
        assert result["success"] is True
        assert result["filament_g"] == round((12345.678 / 1000.0) * 1.25, 2)
        # 12345.678 / 10 = 1234 seconds = 20m 34s -> 20m
        assert result["print_time_str"] == "20m"

def test_slice_model_no_slicer():
    with patch("shutil.which", return_value=None):
        result = slice_model("dummy.stl")
        assert result is None

def test_slice_model_parsing_error():
    mock_stdout = "no volume here"
    
    with patch("subprocess.run") as mock_run, \
         patch("shutil.which", return_value="/usr/bin/prusa-slicer"):
        
        mock_run.return_value = MagicMock(stdout=mock_stdout, check=True)
        
        result = slice_model("dummy.stl")
        assert result is None

def test_slice_model_process_error():
    with patch("subprocess.run", side_effect=subprocess.CalledProcessError(1, "cmd")):
        result = slice_model("dummy.stl")
        assert result is None
