# Copyright (C) 2026 GoodData Corporation

from __future__ import annotations

from pathlib import Path

from aida_mcp.output.log_utils import extract_error_payload
from aida_mcp.output.policy import MAX_ERROR_LINES

from .models import ValidationStepDetail
from .types import JsonDict


def build_step_detail_from_command_result(
    *,
    kind: str,
    name: str,
    command: str,
    exit_code: int,
    stdout: str,
    stderr: str,
    log_path: Path | None,
    duration_seconds: float | None = None,
    extras: JsonDict | None = None,
) -> ValidationStepDetail:
    """Create a ValidationStepDetail from a completed command execution."""

    success = exit_code == 0
    errors, error_count, errors_truncated = extract_error_payload(log_path, max_errors=MAX_ERROR_LINES)
    error_excerpt = "\n".join(errors) if errors else None
    return ValidationStepDetail(
        name=name,
        command=command,
        success=success,
        exit_code=exit_code,
        log_path=str(log_path) if log_path else None,
        error_excerpt=error_excerpt if not success else None,
        duration_seconds=duration_seconds,
        extras={
            **(extras or {}),
            "error_count": error_count,
            "errors_truncated": errors_truncated,
        },
    )
