"""ReportGenerator — comprehensive evolution report generation."""
import logging
from datetime import datetime, timezone
from typing import Any

from rosclaw.auto.core.artifact import EvolutionReport, ChampionCard

logger = logging.getLogger("rosclaw.auto.reports")


class ReportGenerator:
    """Generate human-readable evolution reports in Markdown/HTML."""

    def __init__(self, engine: Any):
        self._engine = engine

    def generate_markdown(self, task_id: str) -> str:
        """Generate a full Markdown evolution report."""
        report = self._engine.generate_report(task_id)
        task = self._engine.get_task(task_id)
        task_name = task.name if task else task_id

        lines = [
            f"# Evolution Report: {task_name}",
            f"",
            f"**Report ID:** `{report.id}`  ",
            f"**Task ID:** `{task_id}`  ",
            f"**Generated:** {report.created_at}",
            f"",
            "## 📊 Summary",
            f"",
            f"| Metric | Value |",
            f"|--------|-------|",
            f"| Proposals Created | {report.proposals_created} |",
            f"| Experiments Run | {report.experiments_run} |",
            f"| Champions Promoted | {report.champions_promoted} |",
            f"| DeadEnds Registered | {report.deadends_registered} |",
            f"",
        ]

        # Champions section
        champs = self._engine.list_champions(task_id)
        if champs:
            lines.extend([
                "## 🏆 Champions",
                f"",
                f"| Skill | Level | Metrics | Parent |",
                f"|-------|-------|---------|--------|",
            ])
            for c in champs:
                metrics_str = ", ".join(f"{k}={v}" for k, v in c.metrics.items())
                lines.append(f"| `{c.skill_id}` | {c.level} | {metrics_str} | {c.parent_skill_id or '-'} |")
            lines.append("")

        # DeadEnds section
        des = self._engine.list_deadends(task_id)
        if des:
            lines.extend([
                "## 🚫 DeadEnds",
                f"",
                f"| Direction | Reason | Evidence |",
                f"|-----------|--------|----------|",
            ])
            for d in des:
                ev = "; ".join(d.evidence[:3]) if d.evidence else "-"
                lines.append(f"| {d.direction} | {d.rejection_reason} | {ev} |")
            lines.append("")

        # Lineage tree
        if champs:
            lines.extend([
                "## 🌳 Skill Lineage",
                f"",
                "```",
            ])
            # Find root skill
            root = champs[0].parent_skill_id or champs[0].skill_id
            tree = self._engine.render_lineage_tree(root)
            lines.append(tree)
            lines.extend([
                "```",
                "",
            ])

        # Experiments timeline
        from rosclaw.auto.core.experiment import ExperimentSpec
        exps = [ExperimentSpec.from_dict(e) for e in self._engine.store.iterate("experiments")]
        exps = [e for e in exps if e.task == task_name or e.task == task_id]
        if exps:
            lines.extend([
                "## 🧪 Experiment Timeline",
                f"",
                f"| Experiment | Baseline | Candidate | Status |",
                f"|------------|----------|-----------|--------|",
            ])
            for e in exps:
                lines.append(f"| `{e.id}` | {e.baseline_skill_id} | {e.candidate_skill_id} | {e.status} |")
            lines.append("")

        # Evaluation deltas
        from rosclaw.auto.core.evaluation import EvaluationResult
        evals = [EvaluationResult.from_dict(e) for e in self._engine.store.iterate("evaluations")]
        if evals:
            lines.extend([
                "## 📈 Evaluation Deltas",
                f"",
                f"| Eval | Decision | Delta |",
                f"|------|----------|-------|",
            ])
            for ev in evals:
                delta_str = ", ".join(f"{k}={v:.3f}" if isinstance(v, float) else f"{k}={v}"
                                      for k, v in ev.delta.items() if isinstance(v, (int, float)))
                lines.append(f"| `{ev.id}` | {ev.decision} | {delta_str} |")
            lines.append("")

        lines.extend([
            "---",
            f"*Generated by rosclaw-auto v1.0*",
        ])
        return "\n".join(lines)

    def generate_champion_card_markdown(self, task_id: str, level: str | None = None) -> str:
        """Generate a champion card as Markdown."""
        champ = self._engine.get_champion(task_id, level)
        if not champ:
            return f"# No champion found for task={task_id} level={level}"

        card = ChampionCard(
            skill_id=champ.skill_id,
            previous_champion=champ.parent_skill_id,
            promotion_date=champ.created_at,
            improvement=champ.metrics,
            validated_on=[champ.level],
            known_limitations=[],
            rollback_to=champ.parent_skill_id,
        )
        return card.to_markdown()
