# Copyright (C) 2026 GoodData Corporation

"""Gradle/Kotlin output parsing utilities."""

from __future__ import annotations

import re


def extract_gradle_errors(stdout: str, stderr: str, *, max_sections: int = 5) -> str | None:
    """
    Extract critical Gradle build errors from verbose output.

    Gradle output is very verbose, and the actual error is often buried.
    This extracts:
    - Compilation errors (e: file.kt:line:col: error message)
    - Task failures (FAILURE: Build failed with an exception)
    - Root causes (Caused by:)
    """
    combined = stdout + "\n" + stderr
    lines = combined.split("\n")

    critical_sections: list[str] = []
    i = 0

    while i < len(lines):
        line = lines[i]

        # Kotlin compilation error
        if line.startswith("e: ") and ".kt:" in line:
            section = [line]
            i += 1
            while i < len(lines) and (lines[i].startswith("  ") or lines[i].startswith("^")):
                section.append(lines[i])
                i += 1
            critical_sections.append("\n".join(section))
            continue

        # Java compilation error
        if ".java:" in line and "error:" in line:
            section = [line]
            i += 1
            while i < len(lines) and lines[i].startswith("  "):
                section.append(lines[i])
                i += 1
            critical_sections.append("\n".join(section))
            continue

        # Build failure section
        if "FAILURE: Build failed" in line or "BUILD FAILED" in line:
            section = [line]
            i += 1
            for _ in range(min(10, len(lines) - i)):
                section.append(lines[i])
                i += 1
            critical_sections.append("\n".join(section))
            continue

        # Caused by (root cause)
        if line.startswith("Caused by:"):
            section = [line]
            i += 1
            while i < len(lines) and (
                lines[i].startswith("  ") or lines[i].startswith("\t") or lines[i].startswith("at ")
            ):
                section.append(lines[i])
                i += 1
                if len(section) >= 10:
                    break
            critical_sections.append("\n".join(section))
            continue

        i += 1

    max_keep = max_sections if max_sections > 0 else 5
    if critical_sections:
        result = ["🔍 Critical Gradle Errors:", ""]
        for idx, section in enumerate(critical_sections[:max_keep], 1):
            result.append(f"[{idx}]")
            result.append(section)
            result.append("")

        if len(critical_sections) > max_keep:
            result.append(f"... and {len(critical_sections) - max_keep} more error sections (see full output)")

        return "\n".join(result)

    return None


def extract_detekt_summary(stdout: str, stderr: str) -> str | None:
    """Extract detekt analysis summary."""
    combined = stdout + "\n" + stderr

    issues_found: list[str] = []
    for line in combined.split("\n"):
        if "issues" in line.lower() or "violations" in line.lower():
            issues_found.append(line.strip())

    if issues_found:
        return "🔍 Detekt: " + "; ".join(issues_found[:3])

    if "BUILD SUCCESSFUL" in combined:
        return "🔍 Detekt: No issues found"

    return None


def extract_spotless_summary(stdout: str, stderr: str) -> str | None:
    """Extract spotless formatting summary."""
    combined = stdout + "\n" + stderr

    violation_count = 0
    for line in combined.split("\n"):
        if "needs formatting" in line.lower() or "formatting violations" in line.lower():
            numbers = re.findall(r"\d+", line)
            if numbers:
                violation_count = int(numbers[0])

    if violation_count > 0:
        return f"💅 Spotless: {violation_count} file(s) need formatting"

    if "BUILD SUCCESSFUL" in combined or "UP-TO-DATE" in combined:
        return "💅 Spotless: All files formatted correctly"

    return None
