"""Performance issue detection - pure functions for detecting common problems.

This module provides functions to detect various performance issues beyond N+1 queries.
"""

from dataclasses import dataclass
from typing import List

import sys
import os

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from core.metrics import PerformanceMetrics


@dataclass
class PerformanceIssues:
    """Container for detected performance issues."""

    has_slow_response: bool
    has_excessive_queries: bool
    has_high_memory: bool
    has_poor_cache_performance: bool
    issues_summary: List[str]  # Human-readable list of issues


def detect_issues(metrics: PerformanceMetrics) -> PerformanceIssues:
    """Detect common performance issues in metrics.

    Args:
        metrics: PerformanceMetrics to analyze

    Returns:
        PerformanceIssues with detected problems

    Example:
        >>> metrics = PerformanceMetrics(response_time_ms=600, query_count=25, ...)
        >>> issues = detect_issues(metrics)
        >>> for issue in issues.issues_summary:
        ...     print(f"⚠️ {issue}")
    """
    issues_summary = []

    # Check response time
    has_slow_response = metrics.response_time_ms > 500
    if has_slow_response:
        issues_summary.append(
            f"Slow response time: {metrics.response_time_ms:.1f}ms (threshold: 500ms)"
        )

    # Check query count
    has_excessive_queries = metrics.query_count > 20
    if has_excessive_queries:
        issues_summary.append(
            f"Excessive database queries: {metrics.query_count} (threshold: 20)"
        )

    # Check memory
    has_high_memory = metrics.memory_overhead_mb > 50
    if has_high_memory:
        issues_summary.append(
            f"High memory overhead: {metrics.memory_overhead_mb:.1f}MB (threshold: 50MB)"
        )

    # Check cache performance
    has_poor_cache_performance = (
        (metrics.cache_hits + metrics.cache_misses > 0) and metrics.cache_hit_ratio < 0.7
    )
    if has_poor_cache_performance:
        issues_summary.append(
            f"Poor cache hit ratio: {metrics.cache_hit_ratio:.1%} (threshold: 70%)"
        )

    return PerformanceIssues(
        has_slow_response=has_slow_response,
        has_excessive_queries=has_excessive_queries,
        has_high_memory=has_high_memory,
        has_poor_cache_performance=has_poor_cache_performance,
        issues_summary=issues_summary,
    )


# Backward compatibility alias
DjangoPerformanceIssues = PerformanceIssues
