import pytest
from datetime import datetime, timedelta
from unittest.mock import MagicMock
from src.services.health_service import HealthService
from src.models.llm import ValidationRecord

# [DEF:test_health_service:Module]
# @TIER: STANDARD
# @PURPOSE: Unit tests for HealthService aggregation logic.

@pytest.mark.asyncio
async def test_get_health_summary_aggregation():
    """
    @TEST_SCENARIO: Verify that HealthService correctly aggregates the latest record per dashboard.
    """
    # Setup: Mock DB session
    db = MagicMock()
    
    now = datetime.utcnow()
    
    # Dashboard 1: Old FAIL, New PASS
    rec1_old = ValidationRecord(
        dashboard_id="dash_1",
        environment_id="env_1",
        status="FAIL",
        timestamp=now - timedelta(hours=1),
        summary="Old failure",
        issues=[]
    )
    rec1_new = ValidationRecord(
        dashboard_id="dash_1",
        environment_id="env_1",
        status="PASS",
        timestamp=now,
        summary="New pass",
        issues=[]
    )
    
    # Dashboard 2: Single WARN
    rec2 = ValidationRecord(
        dashboard_id="dash_2",
        environment_id="env_1",
        status="WARN",
        timestamp=now,
        summary="Warning",
        issues=[]
    )
    
    # Mock the query chain
    # subquery = self.db.query(...).filter(...).group_by(...).subquery()
    # query = self.db.query(ValidationRecord).join(subquery, ...).all()
    
    mock_query = db.query.return_value
    mock_query.filter.return_value = mock_query
    mock_query.group_by.return_value = mock_query
    mock_query.subquery.return_value = MagicMock()
    
    db.query.return_value.join.return_value.all.return_value = [rec1_new, rec2]
    
    service = HealthService(db)
    summary = await service.get_health_summary(environment_id="env_1")
    
    assert summary.pass_count == 1
    assert summary.warn_count == 1
    assert summary.fail_count == 0
    assert len(summary.items) == 2
    
    # Verify dash_1 has the latest status (PASS)
    dash_1_item = next(item for item in summary.items if item.dashboard_id == "dash_1")
    assert dash_1_item.status == "PASS"
    assert dash_1_item.summary == "New pass"

@pytest.mark.asyncio
async def test_get_health_summary_empty():
    """
    @TEST_SCENARIO: Verify behavior with no records.
    """
    db = MagicMock()
    db.query.return_value.join.return_value.all.return_value = []
    
    service = HealthService(db)
    summary = await service.get_health_summary(environment_id="env_none")
    
    assert summary.pass_count == 0
    assert len(summary.items) == 0

# [/DEF:test_health_service:Module]