"""Optimization report formatter for validation and quick wins results."""

from datetime import datetime
from typing import Any

from ..workflows.quick_wins_workflow import QuickWinsResult
from ..workflows.validation_workflow import ValidationResult


class OptimizationReportFormatter:
    """Format optimization reports in various formats."""

    def format_validation_report(self, result: ValidationResult) -> str:
        """
        Generate validation optimization report.

        Args:
            result: ValidationResult from validation workflow

        Returns:
            Formatted markdown report
        """
        report = f"""# Validation Report

**Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**Existing Code Quality:** {result.existing_code_quality:.1f}/10
**Proposed Design Quality:** {result.proposed_design_quality:.1f}/10
**Decision:** {result.decision.upper().replace('_', ' ')}

---

## Executive Summary

{result.rationale}

---

## High-Value Optimizations (Implement Immediately) ⭐⭐⭐

{self._format_recommendations(result.optimization_recommendations, priority="high")}

---

## Medium-Value Optimizations (Consider) ⭐⭐

{self._format_recommendations(result.optimization_recommendations, priority="medium")}

---

## Low-Value Enhancements (Skip - YAGNI) ⭐

{self._format_recommendations(result.optimization_recommendations, priority="low")}

---

## Implementation Plan

**Phase 1:** High-value optimizations ({self._total_effort(result.optimization_recommendations, "high")} min)
**Phase 2:** Medium-value optimizations (optional)

**Total Impact:** {self._total_impact(result.optimization_recommendations, "high")}% improvement

---

## Next Steps

"""

        if result.decision == "keep_existing":
            report += """
1. Review and implement high-value optimizations
2. Update tests if needed
3. Document changes
4. Monitor performance improvements
"""
        else:
            report += """
1. Proceed with new implementation
2. Migrate existing functionality
3. Update tests
4. Phase out old code
"""

        return report

    def format_quick_wins_report(self, result: QuickWinsResult) -> str:
        """
        Generate quick wins optimization report.

        Args:
            result: QuickWinsResult from quick wins workflow

        Returns:
            Formatted markdown report
        """
        report = f"""# Quick Wins Report

**Date:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
**File:** {result.file_path}
**Focus Area:** {result.focus_area.title()}
**Quick Wins Found:** {len(result.quick_wins)}

---

## Summary

Found **{len(result.quick_wins)} high-ROI optimizations** that can deliver **{result.total_impact}% improvement** in approximately **{result.total_effort} minutes** of effort.

---

## Quick Wins (Sorted by Impact)

"""

        for i, win in enumerate(result.quick_wins, 1):
            report += f"""
### {i}. {win.name} ({win.category.title()})

**Impact:** {win.impact}% improvement
**Effort:** {win.effort} minutes
**ROI:** {win.impact / max(win.effort, 1):.1f}% per minute

{win.description}
"""

            if win.code_example:
                report += f"""
**Example:**

```python
{win.code_example.strip()}
```
"""

            report += "\n---\n"

        report += f"""

## Implementation Plan

1. **Quick Wins (Total: {result.total_effort} min)**
"""

        for win in result.quick_wins:
            report += f"   - [ ] {win.name} ({win.effort} min)\n"

        report += f"""
2. **Test Changes**
   - [ ] Add/update unit tests
   - [ ] Run test suite

3. **Measure Impact**
   - [ ] Benchmark before/after
   - [ ] Monitor in production

**Expected Total Impact:** {result.total_impact}% improvement

---

Generated by TappsCodingAgents Simple Mode ⚡
"""

        return report

    def _format_recommendations(
        self,
        recommendations: list[dict[str, Any]],
        priority: str
    ) -> str:
        """Format recommendations by priority."""
        filtered = [r for r in recommendations if r.get("priority") == priority]

        if not filtered:
            return "_No recommendations at this priority level_\n"

        result = []
        for i, rec in enumerate(filtered, 1):
            result.append(f"""
### {i}. {rec.get('name', 'Optimization')}

**Impact:** {rec.get('impact', 0)}% improvement
**Effort:** {rec.get('effort', 0)} minutes
**ROI:** {rec.get('impact', 0) / max(rec.get('effort', 1), 1):.1f}% per minute

{rec.get('description', 'No description')}
""")

        return "\n".join(result)

    def _total_effort(self, recommendations: list[dict[str, Any]], priority: str) -> int:
        """Calculate total effort for recommendations."""
        filtered = [r for r in recommendations if r.get("priority") == priority]
        return sum(r.get("effort", 0) for r in filtered)

    def _total_impact(self, recommendations: list[dict[str, Any]], priority: str) -> int:
        """Calculate average impact for recommendations."""
        filtered = [r for r in recommendations if r.get("priority") == priority]
        if not filtered:
            return 0
        return int(sum(r.get("impact", 0) for r in filtered) / len(filtered))

    def format_summary(self, validation_result: ValidationResult) -> str:
        """
        Generate concise summary for quick display.

        Args:
            validation_result: ValidationResult to summarize

        Returns:
            Concise summary string
        """
        high_value = len([
            r for r in validation_result.optimization_recommendations
            if r.get("priority") == "high"
        ])

        return f"""
📊 Validation Summary:
   Existing Quality: {validation_result.existing_code_quality:.1f}/10
   Proposed Quality: {validation_result.proposed_design_quality:.1f}/10
   Decision: {validation_result.decision.replace('_', ' ').title()}
   High-Value Optimizations: {high_value}
""".strip()
