"""
Test workspace creation functionality for TDD infrastructure.

This test validates issue #11: Setup TDD workspace infrastructure
- Tests workspace creation from issue numbers
- Validates workspace structure and files
- Ensures proper error handling
"""

import pytest
import tempfile
import shutil
from pathlib import Path
from unittest.mock import Mock, patch

from tddai import WorkspaceManager, IssueFetcher, WorkspaceStatus, WorkspaceError, IssueError
from tddai.config import TddaiConfig


class TestWorkspaceCreation:
    """Test suite for workspace creation functionality."""

    @pytest.fixture
    def temp_workspace(self):
        """Create a temporary workspace for testing."""
        temp_dir = Path(tempfile.mkdtemp())
        config = TddaiConfig(workspace_dir=temp_dir / ".markitect_workspace")
        yield config
        shutil.rmtree(temp_dir)

    @pytest.fixture
    def mock_issue_data(self):
        """Mock issue data for testing."""
        return {
            'number': 11,
            'title': 'Setup TDD workspace infrastructure',
            'body': 'Create workspace management system for TDD workflow',
            'state': 'open',
            'created_at': '2025-01-01T00:00:00Z',
            'html_url': 'http://example.com/issues/11',
            'assignee': None,
            'labels': []
        }

    def test_workspace_manager_initialization(self, temp_workspace):
        """Test that WorkspaceManager can be initialized."""
        manager = WorkspaceManager(temp_workspace)
        assert manager.config == temp_workspace

    def test_workspace_status_clean_initially(self, temp_workspace):
        """Test that workspace status is clean when no workspace exists."""
        manager = WorkspaceManager(temp_workspace)
        status = manager.get_status()
        assert status == WorkspaceStatus.CLEAN

    def test_workspace_creation_from_issue_data(self, temp_workspace, mock_issue_data):
        """Test that workspace can be created from issue data."""
        manager = WorkspaceManager(temp_workspace)

        workspace = manager.create_workspace(mock_issue_data)

        assert workspace.issue_number == 11
        assert workspace.issue_title == 'Setup TDD workspace infrastructure'
        assert workspace.workspace_dir == temp_workspace.workspace_dir

        # Verify workspace status changes to active
        status = manager.get_status()
        assert status == WorkspaceStatus.ACTIVE

    def test_workspace_directory_structure_created(self, temp_workspace, mock_issue_data):
        """Test that workspace creates proper directory structure."""
        manager = WorkspaceManager(temp_workspace)
        workspace = manager.create_workspace(mock_issue_data)

        assert workspace.workspace_dir.exists()
        assert workspace.issue_dir.exists()
        assert workspace.tests_dir.exists()

    def test_workspace_metadata_files_created(self, temp_workspace, mock_issue_data):
        """Test that workspace creates required metadata files."""
        manager = WorkspaceManager(temp_workspace)
        workspace = manager.create_workspace(mock_issue_data)

        assert workspace.requirements_file.exists()
        assert workspace.test_plan_file.exists()
        assert temp_workspace.current_issue_path.exists()

    def test_current_issue_metadata_content(self, temp_workspace, mock_issue_data):
        """Test that current issue metadata is properly stored."""
        manager = WorkspaceManager(temp_workspace)
        manager.create_workspace(mock_issue_data)

        current_workspace = manager.get_current_workspace()
        assert current_workspace.issue_number == 11
        assert current_workspace.issue_title == 'Setup TDD workspace infrastructure'
        assert current_workspace.issue_state == 'open'

    def test_workspace_prevents_multiple_active_issues(self, temp_workspace, mock_issue_data):
        """Test that only one workspace can be active at a time."""
        manager = WorkspaceManager(temp_workspace)
        manager.create_workspace(mock_issue_data)

        # Try to create another workspace
        second_issue_data = mock_issue_data.copy()
        second_issue_data['number'] = 12
        second_issue_data['title'] = 'Different issue'

        with pytest.raises(WorkspaceError, match="Workspace already active"):
            manager.create_workspace(second_issue_data)

    @patch('gitea.http_client.subprocess.run')
    def test_issue_fetcher_handles_invalid_issue(self, mock_run, temp_workspace):
        """Test error handling for invalid issue numbers."""
        # Mock curl response for non-existent issue (404 error)
        from subprocess import CalledProcessError
        mock_run.side_effect = CalledProcessError(22, 'curl')  # HTTP 404 error

        fetcher = IssueFetcher(temp_workspace)

        with pytest.raises(IssueError, match="API error fetching issue.*HTTP request failed"):
            fetcher.fetch_issue(999)

    def test_workspace_cleanup(self, temp_workspace, mock_issue_data):
        """Test that workspace can be cleaned up properly."""
        manager = WorkspaceManager(temp_workspace)
        manager.create_workspace(mock_issue_data)

        # Verify workspace exists
        assert manager.get_status() == WorkspaceStatus.ACTIVE

        # Clean up
        manager.cleanup_workspace()

        # Verify workspace is clean
        assert manager.get_status() == WorkspaceStatus.CLEAN
        assert not temp_workspace.workspace_dir.exists()

    def test_workspace_finish_moves_tests(self, temp_workspace, mock_issue_data):
        """Test that finishing workspace moves tests to main directory."""
        manager = WorkspaceManager(temp_workspace)
        workspace = manager.create_workspace(mock_issue_data)

        # Create a test file in workspace
        test_file = workspace.tests_dir / "test_example.py"
        test_file.write_text("# Test content")

        # Finish workspace
        finished_workspace = manager.finish_workspace()

        assert finished_workspace.issue_number == 11
        assert manager.get_status() == WorkspaceStatus.CLEAN

        # Verify test was moved
        main_test_file = temp_workspace.tests_dir / "test_example.py"
        assert main_test_file.exists()
        assert main_test_file.read_text() == "# Test content"