'''
Copyright (C) 2024-2026 Mo Zhou <lumin@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
'''
import pytest
import subprocess
from unittest.mock import patch, MagicMock
from debgpt.tool import Tool, ManPageReader

def test_tool_base_class():
    tool = Tool()
    with pytest.raises(NotImplementedError):
        tool()

def test_man_page_reader_success():
    reader = ManPageReader()
    
    # Mock subprocess.run for success
    mock_run = MagicMock()
    mock_run.returncode = 0
    mock_run.stdout = "l\x08ls\x08s - list directory contents"
    
    with patch("subprocess.run", return_value=mock_run) as mock_subprocess:
        result = reader("ls")
        
        # Verify subprocess was called correctly
        mock_subprocess.assert_called_once()
        args, kwargs = mock_subprocess.call_args
        assert args[0] == ["man", "ls"]
        assert "env" in kwargs
        assert kwargs["env"].get("PAGER") == "cat"
        
        # Verify backspaces were stripped
        assert result == "ls - list directory contents"

def test_man_page_reader_failure():
    reader = ManPageReader()
    
    # Mock subprocess.run for failure
    mock_run = MagicMock()
    mock_run.returncode = 1
    mock_run.stderr = "No manual entry for invalid_command\n"
    
    with patch("subprocess.run", return_value=mock_run):
        result = reader("invalid_command")
        assert "Error reading man page for invalid_command: No manual entry for invalid_command" in result

def test_man_page_reader_exception():
    reader = ManPageReader()
    
    # Mock subprocess.run to raise exception
    with patch("subprocess.run", side_effect=Exception("Unexpected error")):
        result = reader("ls")
        assert "Error: Unexpected error" in result

def test_man_page_reader_integration():
    # A real integration test to make sure it actually reads something
    reader = ManPageReader()
    result = reader("ls")
    # `ls` man page should have 'NAME' section and 'ls' in it
    assert "NAME" in result
    assert "ls" in result
    assert "Error" not in result
