"""Markdown renderers for g-gremlin memory."""

from __future__ import annotations

import json
from collections import Counter
from typing import Any, Mapping, Sequence

from .query import normalize_scalar, normalize_text_list


def render_index_markdown(payload: Mapping[str, Any]) -> str:
    entries = [entry for entry in payload.get("entries", []) if isinstance(entry, Mapping)]
    lines = [
        "# Gremlin Memory Index",
        "",
        f"- Updated: {payload.get('updated_at', '')}",
        f"- Retained entries: {len(entries)}",
        f"- Retention limit: {payload.get('retention_limit', 200)}",
        "",
    ]
    if not entries:
        lines.extend(["No memory entries captured yet.", ""])
        return "\n".join(lines)
    counts = Counter(str(entry.get("command_id") or "") for entry in entries)
    lines.extend(["## Commands", ""])
    for command_id, count in sorted(counts.items()):
        lines.append(f"- {command_id}: {count}")
    lines.extend(["", "## Recent Entries", ""])
    for entry in entries[:20]:
        lines.append(
            f"- {entry.get('created_at', '')} | {entry.get('command_id', '')} | "
            f"{entry.get('status', '')} | {entry.get('title', '')}"
        )
    lines.append("")
    return "\n".join(lines)


def render_entry_markdown(entry: Mapping[str, Any]) -> str:
    lines = [
        f"# {entry.get('title', '')}",
        "",
        f"- Entry ID: {entry.get('entry_id', '')}",
        f"- Command: {entry.get('command_id', '')}",
        f"- Status: {entry.get('status', '')}",
        f"- Created: {entry.get('created_at', '')}",
        "",
        str(entry.get("summary") or "").strip(),
        "",
    ]
    _append_artifact_section(lines, "Inputs", entry.get("inputs"))
    _append_artifact_section(lines, "Outputs", entry.get("outputs"))
    _append_artifact_section(lines, "Artifacts", entry.get("artifacts"))
    _append_text_section(lines, "Key Facts", entry.get("key_facts"))
    _append_text_section(lines, "Issues", entry.get("issues"))
    _append_text_section(lines, "Suggested Next Steps", entry.get("suggested_next_steps"))
    related = entry.get("related_entry_ids")
    if isinstance(related, Sequence) and related:
        lines.extend(["## Related Entries", ""])
        for related_id in related:
            lines.append(f"- {related_id}")
        lines.append("")
    ai_summary = str(entry.get("ai_summary") or "").strip()
    if ai_summary:
        lines.extend(["## AI Summary", "", ai_summary, ""])
    return "\n".join(lines)


def render_command_page_markdown(command_id: str, entries: Sequence[Mapping[str, Any]]) -> str:
    sorted_entries = sorted(entries, key=lambda row: str(row.get("created_at") or ""), reverse=True)
    issue_counter: Counter[str] = Counter()
    for entry in sorted_entries:
        for issue in normalize_text_list(entry.get("issues")):
            issue_counter[issue] += 1
    lines = [
        f"# Command Memory: {command_id}",
        "",
        f"- Retained entries: {len(sorted_entries)}",
        "",
        "## Recent Entries",
        "",
    ]
    for entry in sorted_entries[:10]:
        lines.append(
            f"- {entry.get('created_at', '')} | {entry.get('status', '')} | "
            f"{entry.get('title', '')} | {entry.get('page_path', '')}"
        )
    lines.append("")
    latest_success = next((entry for entry in sorted_entries if str(entry.get("status") or "") == "success"), None)
    if latest_success:
        lines.extend(["## Latest Successful Outputs", ""])
        for bucket in ("outputs", "artifacts"):
            value = latest_success.get(bucket)
            if not isinstance(value, Sequence):
                continue
            for item in value:
                if isinstance(item, Mapping) and item.get("path"):
                    lines.append(f"- {item.get('path')}")
        lines.append("")
    if issue_counter:
        lines.extend(["## Recurring Issues", ""])
        for issue, count in issue_counter.most_common(10):
            lines.append(f"- {count}x {issue}")
        lines.append("")
    return "\n".join(lines)


def _append_artifact_section(lines: list[str], title: str, value: Any) -> None:
    if not isinstance(value, Sequence) or not value:
        return
    lines.extend([f"## {title}", ""])
    for item in value:
        if not isinstance(item, Mapping):
            continue
        path_text = str(item.get("path") or "").strip()
        label = str(item.get("label") or "").strip()
        if path_text and label:
            line = f"- {label}: {path_text}"
        elif path_text:
            line = f"- {path_text}"
        else:
            line = f"- {json.dumps(normalize_scalar(item), ensure_ascii=True)}"
        if item.get("sha256"):
            line += f" (sha256={item.get('sha256')})"
        lines.append(line)
    lines.append("")


def _append_text_section(lines: list[str], title: str, value: Any) -> None:
    entries = normalize_text_list(value)
    if not entries:
        return
    lines.extend([f"## {title}", ""])
    for entry in entries:
        lines.append(f"- {entry}")
    lines.append("")
