"""Output formatters for scan results."""

from __future__ import annotations

import json


def format_json(result: dict) -> str:
    """Format scan result as pretty-printed JSON."""
    return json.dumps(result, indent=2)


def format_markdown(result: dict) -> str:
    """Format scan result as a GitHub-style Markdown comment."""
    signal = result["signal"]
    score = signal["score"]
    verdict = signal["verdict"]
    queries = result.get("queries", [])

    verdict_labels = {
        "LOW": "🟢 LOW — Greenfield opportunity or underserved niche",
        "MODERATE": "🟡 MODERATE — Some existing solutions, differentiation needed",
        "HIGH": "🔴 HIGH — Crowded space, needs strong differentiator",
    }
    verdict_str = verdict_labels.get(verdict, verdict)

    lines = [
        "## 🔍 Prior Art Scan",
        "",
        f"**Reality Signal:** {score}/100 — {verdict_str}",
        f"**Queries:** {', '.join(f'`{q}`' for q in queries)}",
        "",
    ]

    # GitHub repos
    repos = next(
        (s["results"] for s in result.get("sources", []) if s["type"] == "github"),
        [],
    )
    lines.append("### GitHub Repositories")
    if repos:
        lines.append("")
        lines.append("| Repo | ⭐ | Language | Description |")
        lines.append("|------|-----|----------|-------------|")
        for r in repos[:8]:
            desc = (r.get("description") or "—").replace("|", "\\|")
            row = (
                f"| [{r['name']}]({r['url']}) | {r['stars']:,}"
                f" | {r['language']} | {desc} |"
            )
            lines.append(row)
    else:
        lines.append("No relevant repositories found.")
    lines.append("")

    # HN discussions
    hn_posts = next(
        (s["results"] for s in result.get("sources", []) if s["type"] == "hn"),
        [],
    )
    lines.append("### Hacker News Discussions")
    if hn_posts:
        lines.append("")
        for p in hn_posts:
            lines.append(
                f"- [{p['title']}]({p['url']}) — {p['points']} pts, "
                f"{p['comments']} comments ({p['date']})"
            )
    else:
        lines.append("No relevant discussions found.")
    lines.append("")

    lines.append("---")
    lines.append(
        "*Auto-generated by priorart. Data informs Founder and attack agents.*"
    )

    return "\n".join(lines)


def format_table(result: dict) -> str:
    """Format scan result as plain-text tables."""
    signal = result["signal"]
    score = signal["score"]
    verdict = signal["verdict"]
    queries = result.get("queries", [])

    lines = [
        "Prior Art Scan",
        "=" * 60,
        f"Reality Signal: {score}/100  ({verdict})",
        f"Queries: {', '.join(queries)}",
        "",
    ]

    # GitHub repos
    repos = next(
        (s["results"] for s in result.get("sources", []) if s["type"] == "github"),
        [],
    )
    lines.append("GitHub Repositories")
    lines.append("-" * 60)
    if repos:
        col_widths = {"name": 35, "stars": 8, "language": 12, "description": 40}
        header = (
            f"{'Repo':<{col_widths['name']}} "
            f"{'Stars':>{col_widths['stars']}} "
            f"{'Language':<{col_widths['language']}} "
            f"Description"
        )
        lines.append(header)
        lines.append("-" * 60)
        for r in repos[:8]:
            name = r["name"][: col_widths["name"]]
            desc = (r.get("description") or "—")[: col_widths["description"]]
            lang = (r.get("language") or "—")[: col_widths["language"]]
            lines.append(
                f"{name:<{col_widths['name']}} "
                f"{r['stars']:>{col_widths['stars']},} "
                f"{lang:<{col_widths['language']}} "
                f"{desc}"
            )
    else:
        lines.append("No relevant repositories found.")
    lines.append("")

    # HN discussions
    hn_posts = next(
        (s["results"] for s in result.get("sources", []) if s["type"] == "hn"),
        [],
    )
    lines.append("Hacker News Discussions")
    lines.append("-" * 60)
    if hn_posts:
        for p in hn_posts:
            title = p["title"][:55]
            lines.append(f"  {title}")
            lines.append(
                f"    {p['points']} pts, {p['comments']} comments  {p['date']}"
            )
            lines.append(f"    {p['url']}")
    else:
        lines.append("No relevant discussions found.")

    return "\n".join(lines)
