"""Generate MIGRATION-REPORT.md after a migration run."""
from __future__ import annotations
from datetime import datetime
from pathlib import Path


def generate_report(
    helix_root: str,
    source_dir: str,
    framework: str,
    written: list[dict],
    skipped: list[dict],
    conflicts: list[dict],
    todos: list[str],
) -> str:
    """Write MIGRATION-REPORT.md to helix_root and return the absolute path."""
    now = datetime.now().strftime("%Y-%m-%d %H:%M")

    lines = [
        "# Migration Report",
        "",
        f"**Generated:** {now}  ",
        f"**Source:**    `{source_dir}`  ",
        f"**Framework:** `{framework}`  ",
        f"**Helix root:** `{helix_root}`",
        "",
        "---",
        "",
        "## Summary",
        "",
        "| Metric | Count |",
        "|--------|-------|",
        f"| Files written          | {len(written)} |",
        f"| Files skipped          | {len(skipped)} |",
        f"| Conflicts resolved     | {len(conflicts)} |",
        f"| TODOs added            | {len(todos)} |",
        "",
    ]

    if written:
        lines += [
            "## Migrated Files",
            "",
            "| Source | Target | Role | Changes |",
            "|--------|--------|------|---------|",
        ]
        for f in written:
            src     = f.get("source", "—")
            tgt     = f.get("target", "—")
            role    = f.get("role", "—")
            chg     = f.get("change_count", 0)
            lines.append(f"| `{src}` | `{tgt}` | {role} | {chg} |")
        lines.append("")

    if todos:
        lines += ["## TODOs", ""]
        for t in todos:
            lines.append(f"- {t}")
        lines.append("")

    if skipped:
        lines += ["## Skipped Files", ""]
        for f in skipped:
            src    = f.get("source", "—")
            reason = f.get("reason", "unknown")
            lines.append(f"- `{src}` — {reason}")
        lines.append("")

    if conflicts:
        lines += ["## Conflicts Resolved", ""]
        for c in conflicts:
            path       = c.get("path", "—")
            resolution = c.get("resolution", "unknown")
            lines.append(f"- `{path}` — {resolution}")
        lines.append("")

    lines += [
        "---",
        "",
        "> Generated by `qa-migration` — STLC Agents migration tool.",
        "",
    ]

    report_path = Path(helix_root) / "MIGRATION-REPORT.md"
    report_path.write_text("\n".join(lines), encoding="utf-8")
    return str(report_path)
