"""Test workspace-filtered tag stats."""
import pytest
from fastapi.testclient import TestClient
from server import app

@pytest.fixture
def client():
    with TestClient(app) as c:
        yield c

def test_user_stats_workspace_filter(client):
    """Test that /users/{id}/stats respects workspace_id filter."""
    # For demo user (user_id=1), we need to be authenticated or use DISABLE_AUTH mode
    # The test client uses the app directly, bypassing auth checks in development

    # Get stats for all workspaces
    all_stats = client.get("/api/v1/users/1/stats")
    assert all_stats.status_code == 200
    all_data = all_stats.json()
    all_tags = all_data.get("tagCount", {})

    # Get stats for PERSONAL workspace only
    personal_stats = client.get("/api/v1/users/1/stats?workspace_id=PERSONAL")
    assert personal_stats.status_code == 200
    personal_data = personal_stats.json()
    personal_tags = personal_data.get("tagCount", {})

    # Get stats for AI_SALES_CRM workspace only
    ai_stats = client.get("/api/v1/users/1/stats?workspace_id=AI_SALES_CRM")
    assert ai_stats.status_code == 200
    ai_data = ai_stats.json()
    ai_tags = ai_data.get("tagCount", {})

    # Verify: all_tags should be sum of personal + ai (approximately, accounting for overlapping tags)
    # Check that personal_tags only contain tags that are in all_tags
    for tag in personal_tags:
        assert tag in all_tags, f"Tag {tag} from personal not in all_tags"

    for tag in ai_tags:
        assert tag in all_tags, f"Tag {tag} from AI not in all_tags"

    print(f"\nAll tags: {all_tags}")
    print(f"Personal tags: {personal_tags}")
    print(f"AI_SALES_CRM tags: {ai_tags}")
