"""Report generation for meta-workflow execution results.

Produces human-readable markdown reports from MetaWorkflowResult data,
including summary statistics, agent details, and cost breakdowns.

Created: 2026-02-19
Purpose: Extracted from workflow.py for focused module design
"""

import json

from attune.meta_workflows.models import MetaWorkflowResult, MetaWorkflowTemplate


def generate_report(result: MetaWorkflowResult, template: MetaWorkflowTemplate) -> str:
    """Generate human-readable report.

    Args:
        result: Execution result
        template: Template used for this execution

    Returns:
        Markdown-formatted report

    """
    lines = []

    lines.append("# Meta-Workflow Execution Report")
    lines.append("")
    lines.append(f"**Run ID**: {result.run_id}")
    lines.append(f"**Template**: {template.name}")
    lines.append(f"**Timestamp**: {result.timestamp}")
    status = "Yes" if result.success else "No"
    lines.append(f"**Success**: {status}")
    if result.error:
        lines.append(f"**Error**: {result.error}")
    lines.append("")

    lines.append("## Summary")
    lines.append("")
    lines.append(f"- **Agents Created**: {len(result.agents_created)}")
    lines.append(f"- **Agents Executed**: {len(result.agent_results)}")
    lines.append(f"- **Total Cost**: ${result.total_cost:.2f}")
    lines.append(f"- **Total Duration**: {result.total_duration:.1f}s")
    lines.append("")

    lines.append("## Form Responses")
    lines.append("")
    for key, value in result.form_responses.responses.items():
        lines.append(f"- **{key}**: {value}")
    lines.append("")

    lines.append("## Agents Created")
    lines.append("")
    for i, agent in enumerate(result.agents_created, 1):
        lines.append(f"### {i}. {agent.role}")
        lines.append("")
        lines.append(f"- **Agent ID**: {agent.agent_id}")
        lines.append(f"- **Base Template**: {agent.base_template}")
        lines.append(f"- **Tier Strategy**: {agent.tier_strategy.value}")
        lines.append(f"- **Tools**: {', '.join(agent.tools) if agent.tools else 'None'}")
        if agent.config:
            lines.append(f"- **Config**: {json.dumps(agent.config)}")
        if agent.success_criteria:
            lines.append("- **Success Criteria**:")
            for criterion in agent.success_criteria:
                lines.append(f"  - {criterion}")
        lines.append("")

    lines.append("## Execution Results")
    lines.append("")
    for i, agent_result in enumerate(result.agent_results, 1):
        lines.append(f"### {i}. {agent_result.role}")
        lines.append("")
        agent_status = "Success" if agent_result.success else "Failed"
        lines.append(f"- **Status**: {agent_status}")
        lines.append(f"- **Tier Used**: {agent_result.tier_used}")
        lines.append(f"- **Cost**: ${agent_result.cost:.2f}")
        lines.append(f"- **Duration**: {agent_result.duration:.1f}s")
        if agent_result.error:
            lines.append(f"- **Error**: {agent_result.error}")
        lines.append("")

    lines.append("## Cost Breakdown")
    lines.append("")

    # Group by tier
    tier_costs: dict[str, float] = {}
    for agent_result in result.agent_results:
        tier = agent_result.tier_used
        if tier not in tier_costs:
            tier_costs[tier] = 0.0
        tier_costs[tier] += agent_result.cost

    for tier, cost in sorted(tier_costs.items()):
        lines.append(f"- **{tier}**: ${cost:.2f}")

    lines.append("")
    lines.append("---")
    lines.append("")
    lines.append("*Generated by Attune AI Meta-Workflow System*")

    return "\n".join(lines)
