# Copyright (C) 2026 GoodData Corporation

"""Test-output summarization helpers (pytest/gradle)."""

from __future__ import annotations

import re


def extract_test_summary(stdout: str, stderr: str) -> str | None:
    """Extract test execution summary from pytest/gradle output."""
    combined = stdout + "\n" + stderr

    # Pytest patterns
    for line in reversed(combined.split("\n")):
        if ("passed" in line.lower() or "failed" in line.lower()) and re.search(
            r"\d+\s+(passed|failed|skipped|error)", line, re.IGNORECASE
        ):
            return f"📊 Test Summary: {line.strip()}"

    # Gradle test patterns
    if "BUILD SUCCESSFUL" in combined:
        for line in combined.split("\n"):
            if "test" in line.lower() and any(word in line.lower() for word in ["passed", "failed", "total"]):
                return f"📊 Test Summary: {line.strip()}"
        return "📊 All tests passed"

    return None


def extract_failed_test_names(stdout: str, stderr: str, max_count: int = 10) -> list[str]:
    """
    Extract names of failed tests from pytest/gradle output.

    Returns list of failed test names (limited to max_count).
    """
    combined = stdout + "\n" + stderr
    failed: list[str] = []

    # Pytest pattern: "FAILED test_file.py::test_name - AssertionError"
    for line in combined.split("\n"):
        if "FAILED" in line:
            match = re.search(r"FAILED\s+(\S+)", line)
            if match:
                failed.append(match.group(1))

    # Gradle pattern: "Test testSomething FAILED"
    for line in combined.split("\n"):
        if "FAILED" in line and "Test" in line:
            match = re.search(r"Test\s+(\w+)\s+FAILED", line)
            if match:
                failed.append(match.group(1))

    return failed[:max_count]


def create_test_failure_summary(stdout: str, stderr: str, *, max_failed_tests: int = 10) -> str:
    """Create a short summary of test failures.

    Args:
        max_failed_tests: Max number of failed tests listed inline.
    """
    result: list[str] = []

    summary = extract_test_summary(stdout, stderr)
    if summary:
        result.append(summary)
        result.append("")

    max_count = max_failed_tests if max_failed_tests > 0 else 10
    failed_tests = extract_failed_test_names(stdout, stderr, max_count=max_count)
    if failed_tests:
        result.append("❌ Failed Tests:")
        for test in failed_tests:
            result.append(f"  - {test}")

        all_failures = extract_failed_test_names(stdout, stderr, max_count=1000)
        if len(all_failures) > len(failed_tests):
            result.append(f"  ... and {len(all_failures) - len(failed_tests)} more")
        result.append("")
        result.append("💡 Tip: Run the test command locally for detailed error messages")

    return "\n".join(result)
