"""Workflow result container with audit chain."""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.types import Result, Status, StepOutcome


class WorkflowResult(Result):
    """Extended result with helper methods for step aggregation.

    Wraps ``Result`` with convenience methods to derive overall status
    from individual step outcomes and produce summaries.
    """

    @classmethod
    def from_steps(
        cls,
        workflow: str,
        steps: List[StepOutcome],
        metadata: Optional[Dict[str, Any]] = None,
    ) -> "WorkflowResult":
        """Build a result from a list of step outcomes.

        Status logic:
            - All SUCCESS -> SUCCESS
            - Any FAILED -> FAILED
            - Mix of SUCCESS + SKIPPED/NOT_IMPLEMENTED -> PARTIAL
        """
        status = _aggregate_status(steps)
        summary = _build_summary(workflow, steps, status)
        return cls(
            workflow=workflow,
            status=status,
            steps=steps,
            summary=summary,
            metadata=metadata or {},
        )

    @property
    def failed_steps(self) -> List[StepOutcome]:
        return [s for s in self.steps if s.status == Status.FAILED]

    @property
    def successful_steps(self) -> List[StepOutcome]:
        return [s for s in self.steps if s.status == Status.SUCCESS]

    @property
    def is_success(self) -> bool:
        return self.status == Status.SUCCESS


def _aggregate_status(steps: List[StepOutcome]) -> Status:
    if not steps:
        return Status.SUCCESS
    statuses = {s.status for s in steps}
    if Status.FAILED in statuses:
        return Status.FAILED
    if statuses == {Status.SUCCESS}:
        return Status.SUCCESS
    return Status.PARTIAL


def _build_summary(
    workflow: str, steps: List[StepOutcome], status: Status
) -> str:
    total = len(steps)
    ok = sum(1 for s in steps if s.status == Status.SUCCESS)
    failed = sum(1 for s in steps if s.status == Status.FAILED)
    stub = sum(1 for s in steps if s.status == Status.NOT_IMPLEMENTED)
    parts = [f"{workflow}: {status.value} ({ok}/{total} steps passed)"]
    if failed:
        parts.append(f"{failed} failed")
    if stub:
        parts.append(f"{stub} not yet implemented")
    return ", ".join(parts)
