"""
Text reporter for attribution results.

Formats Attribution objects as human-readable tree-format output.
"""

from __future__ import annotations

from llmhq_releaseops.attribution.models import Attribution, Influence


class TextReporter:
    """Formats attribution results as human-readable text."""

    def report(self, attribution: Attribution) -> str:
        lines = [
            "Attribution Analysis",
            "=" * 40,
            f"  Trace:   {attribution.trace_id}",
            f"  Bundle:  {attribution.bundle_id}@{attribution.bundle_version}",
            f"  Action:  {attribution.action}",
            f"  Type:    {attribution.action_type}",
            "",
        ]

        if attribution.primary_influence:
            primary = attribution.primary_influence
            lines.append(f"Primary Influence ({primary.confidence_label} confidence):")
            lines.extend(self._format_influence(primary, prefix="  "))
            lines.append("")

        supporting = [
            i for i in attribution.influences[1:]
            if i.confidence >= 0.3
        ]
        if supporting:
            lines.append("Supporting Influences:")
            for influence in supporting:
                lines.extend(self._format_influence(influence, prefix="  "))
                lines.append("")

        lines.append(f"Overall: {attribution.overall_assessment}")
        return "\n".join(lines)

    def _format_influence(self, influence: Influence, prefix: str = "") -> list:
        lines = [
            f"{prefix}{influence.artifact_type}: {influence.artifact_ref}",
        ]
        if influence.location:
            lines.append(f"{prefix}  Location: {influence.location}")
        if influence.content_snippet:
            lines.append(f"{prefix}  Content: \"{influence.content_snippet}\"")
        lines.append(f"{prefix}  Confidence: {influence.confidence:.2f} ({influence.confidence_label})")
        if influence.confidence_reason:
            lines.append(f"{prefix}  Confidence reason: {influence.confidence_reason}")
        lines.append(f"{prefix}  Reasoning: {influence.reasoning}")
        return lines
