"""Step output store for Avatar plan execution (Phase C)."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any

GENERATED_TEXT_FIELDS = (
    "exact_text",
    "generated_content",
    "generated_text",
    "content",
    "summary",
    "text",
    "body",
    "draft",
    "markdown",
)


@dataclass
class PlanStepContext:
    """Maps step_id → execution evidence for depends_on / content_from_step resolution."""

    _outputs: dict[str, dict[str, Any]] = field(default_factory=dict)

    def store(self, step_id: str, evidence: dict[str, Any]) -> None:
        key = str(step_id or "").strip()
        if not key:
            return
        self._outputs[key] = dict(evidence)

    def get_evidence(self, step_id: str) -> dict[str, Any]:
        return dict(self._outputs.get(str(step_id or "").strip()) or {})

    def get_text(self, step_id: str) -> str:
        evidence = self.get_evidence(step_id)
        for field_name in GENERATED_TEXT_FIELDS:
            value = evidence.get(field_name)
            if isinstance(value, str) and value.strip():
                return value.strip()
        return ""

    def resolve_payload(self, payload: dict[str, Any], *, command_type: str = "") -> dict[str, Any]:
        resolved = dict(payload)
        had_text_from_step = bool(resolved.get("text_from_step"))
        had_content_from_step = bool(resolved.get("content_from_step"))
        source_step = str(
            resolved.pop("content_from_step", "")
            or resolved.pop("text_from_step", "")
            or ""
        ).strip()
        if not source_step:
            return resolved

        text = self.get_text(source_step)
        if not text:
            return resolved

        resolved["generated_text"] = text
        resolved["content"] = text
        ctype = str(command_type or resolved.get("command_type_hint") or "").strip().lower()
        if had_text_from_step or ctype == "keyboard_type_text" or "text" in payload:
            resolved["text"] = text
        if "summary" in payload or ctype == "summarize_content":
            resolved.setdefault("summary", text)
        elif ctype == "generate_content":
            resolved.setdefault("research_context", text)
        elif had_content_from_step and ctype in {"write_file_in_workspace", "open_document_edit"}:
            pass
        return resolved
