# Copyright (C) 2026 GoodData Corporation

from __future__ import annotations

from dataclasses import dataclass, field

from .types import JsonDict, new_json_dict


@dataclass(slots=True)
class ValidationStepDetail:
    """A single step's structured detail, safe to serialize to JSON."""

    name: str
    command: str | None
    success: bool
    exit_code: int | None
    log_path: str | None
    error_excerpt: str | None
    duration_seconds: float | None = None
    extras: JsonDict = field(default_factory=new_json_dict)

    def to_dict(self) -> dict[str, object]:
        # NOTE: We intentionally flatten extras at the top-level to preserve
        # the existing response shape (older clients may expect these keys).
        payload: dict[str, object] = {
            "name": self.name,
            "command": self.command,
            "success": self.success,
            "exit_code": self.exit_code,
            "log_path": self.log_path,
            "error_excerpt": self.error_excerpt,
        }
        if self.duration_seconds is not None:
            payload["duration_seconds"] = self.duration_seconds
        for k, v in self.extras.items():
            payload[k] = v
        return payload


def _new_step_detail_list() -> list[ValidationStepDetail]:
    return []


@dataclass(slots=True)
class ValidationResult:
    """Top-level structured result for a validate_* tool."""

    tool: str
    success: bool
    text: str
    steps: list[ValidationStepDetail] = field(default_factory=_new_step_detail_list)
    meta: JsonDict = field(default_factory=new_json_dict)

    def to_dict(self) -> dict[str, object]:
        payload: dict[str, object] = {
            "tool": self.tool,
            "success": self.success,
            "steps": [s.to_dict() for s in self.steps],
            "text": self.text,
        }
        for k, v in self.meta.items():
            payload[k] = v
        return payload
