import pytest
from brynq import marketplace
import json
import uuid

@pytest.fixture(autouse=True)
def setup_teardown_marketplace():
    # Setup
    marketplace.VALID_CATEGORIES = (
        "code_review",
        "testing",
        "docs",
        "refactoring",
        "debugging",
        "architecture",
        "security_audit",
        "performance",
        "data_analysis",
        "devops",
        "general",
        "raw_compute",
    )
    yield
    # Teardown logic if needed

def test_list_service_invalid_category():
    with pytest.raises(ValueError, match="Invalid category"):
        marketplace.list_service("Test", "Desc", "invalid_cat")

def test_list_service_invalid_pricing_tier():
    with pytest.raises(ValueError, match="Invalid pricing_tier"):
        marketplace.list_service("Test", "Desc", "code_review", pricing_tier="invalid_tier")

def test_list_service_success(tmp_path, monkeypatch):
    # Mock out file operations
    mock_services = []
    
    def mock_write(service):
        mock_services.append(service)
        
    def mock_notify(channel, msg):
        pass
        
    monkeypatch.setattr(marketplace, "_write_service", mock_write)
    monkeypatch.setattr(marketplace, "_notify_channel", mock_notify)
    monkeypatch.setattr(marketplace, "SESSION_ID", "test-session")
    monkeypatch.setattr(marketplace, "SESSION_NAME", "test-agent")
    monkeypatch.setattr(marketplace, "PLATFORM", "pytest")

    result = marketplace.list_service(
        title="My Service",
        description="Does cool stuff",
        category="code_review",
        pricing_tier="free"
    )

    assert result["title"] == "My Service"
    assert result["category"] == "code_review"
    assert result["pricing_tier"] == "free"
    assert len(mock_services) == 1
    assert mock_services[0]["service_id"] == result["service_id"]

def test_book_service_not_found(monkeypatch):
    monkeypatch.setattr(marketplace, "_read_service", lambda x: None)
    res = marketplace.book_service("fake-id", "needs")
    assert "error" in res