"""
Feedback history for V5 orchestrator.

Walks the refined_from chain backwards to collect feedback.txt files
from iteration directories. Used to provide context to Claude prompts.
"""

from pathlib import Path
from typing import Optional

from .iteration import read_metadata


def get_feedback_history_for_claude(
    take_path: Path,
    stage: str,
    from_iteration: Optional[str] = None,
) -> str:
    """
    Walk refined_from chain backwards collecting feedback.txt files.

    Args:
        take_path: Path to take directory
        stage: Stage name (e.g. "07-grids")
        from_iteration: Starting iteration to walk back from.
            If None, returns empty.

    Returns:
        Formatted feedback history for Claude prompt context.
    """
    if not from_iteration:
        return ""

    stage_dir = take_path / stage
    feedback_chain = []
    current_iter = from_iteration
    visited = set()

    while current_iter and current_iter not in visited:
        visited.add(current_iter)
        iter_dir = stage_dir / current_iter

        if not iter_dir.exists():
            break

        # Read feedback for this iteration
        feedback_file = iter_dir / "feedback.txt"
        if feedback_file.exists():
            feedback_text = feedback_file.read_text().strip()
            if feedback_text:
                feedback_chain.append({
                    "iteration": current_iter,
                    "feedback": feedback_text,
                })

        # Walk to parent via refined_from
        meta = read_metadata(iter_dir)
        current_iter = meta.get("refined_from")

    if not feedback_chain:
        return ""

    # Format: oldest to newest
    lines = ["Previous feedback for this stage:", ""]
    for i, item in enumerate(reversed(feedback_chain), 1):
        lines.append(f"{i}. Iteration {item['iteration']}")
        lines.append(f'   User said: "{item["feedback"]}"')
        lines.append("")

    lines.append("Please incorporate this feedback into your generation.")
    return "\n".join(lines)
