"""Resume prompt template engine — the killer feature."""

from __future__ import annotations

from pjctx.core.context import Context


def build_prompt(ctx: Context, fmt: str = "default") -> str:
    """Build a resume prompt from a context in the given format."""
    builders = {
        "default": _build_default,
        "xml": _build_xml,
        "compact": _build_compact,
    }
    builder = builders.get(fmt, _build_default)
    return builder(ctx)


def _build_default(ctx: Context) -> str:
    """Markdown briefing document with headers."""
    sections: list[str] = []
    sections.append("# Project Context Resume\n")

    if ctx.branch:
        sections.append(f"**Branch:** `{ctx.branch}`")
    if ctx.timestamp:
        sections.append(f"**Last saved:** {ctx.timestamp}")
    if ctx.message:
        sections.append(f"\n## Summary\n{ctx.message}")
    if ctx.task:
        sections.append(f"\n## Current Task\n{ctx.task}")
    if ctx.current_approach:
        sections.append(f"\n## Current Approach\n{ctx.current_approach}")
    if ctx.approaches_tried:
        items = "\n".join(f"- {a}" for a in ctx.approaches_tried)
        sections.append(f"\n## Approaches Tried\n{items}")
    if ctx.decisions:
        items = "\n".join(f"- {d}" for d in ctx.decisions)
        sections.append(f"\n## Key Decisions\n{items}")
    if ctx.files_changed:
        items = "\n".join(f"- `{f}`" for f in ctx.files_changed)
        sections.append(f"\n## Files Changed\n{items}")
    if ctx.git_diff_summary:
        sections.append(f"\n## Git Changes\n{ctx.git_diff_summary}")
    if ctx.next_steps:
        items = "\n".join(f"- {s}" for s in ctx.next_steps)
        sections.append(f"\n## Next Steps\n{items}")
    if ctx.handoff_to:
        note = ctx.handoff_note or ""
        sections.append(f"\n## Handoff\nTo: {ctx.handoff_to}\n{note}")
    if ctx.tags:
        sections.append(f"\n**Tags:** {', '.join(ctx.tags)}")

    sections.append(
        "\n---\n*Continue from this context. "
        "Review the above and pick up where we left off.*"
    )
    return "\n".join(sections)


def _build_xml(ctx: Context) -> str:
    """Structured XML format for tools that parse it."""
    lines: list[str] = ['<context>']

    def _tag(name: str, value: str) -> None:
        if value:
            lines.append(f"  <{name}>{_esc(value)}</{name}>")

    def _list_tag(name: str, items: list[str], item_name: str = "item") -> None:
        if items:
            lines.append(f"  <{name}>")
            for item in items:
                lines.append(f"    <{item_name}>{_esc(item)}</{item_name}>")
            lines.append(f"  </{name}>")

    _tag("branch", ctx.branch)
    _tag("timestamp", ctx.timestamp)
    _tag("message", ctx.message)
    _tag("task", ctx.task)
    _tag("current_approach", ctx.current_approach)
    _list_tag("approaches_tried", ctx.approaches_tried, "approach")
    _list_tag("decisions", ctx.decisions, "decision")
    _list_tag("files_changed", ctx.files_changed, "file")
    _tag("git_diff_summary", ctx.git_diff_summary)
    _list_tag("next_steps", ctx.next_steps, "step")
    if ctx.handoff_to:
        lines.append(f"  <handoff to=\"{_esc(ctx.handoff_to)}\">{_esc(ctx.handoff_note or '')}</handoff>")
    _list_tag("tags", ctx.tags, "tag")
    lines.append("  <directive>Continue from this context. Review the above and pick up where we left off.</directive>")
    lines.append("</context>")
    return "\n".join(lines)


def _build_compact(ctx: Context) -> str:
    """Dense single paragraph for token-limited contexts."""
    parts: list[str] = []
    if ctx.branch:
        parts.append(f"Branch: {ctx.branch}.")
    if ctx.message:
        parts.append(f"Summary: {ctx.message}.")
    if ctx.task:
        parts.append(f"Task: {ctx.task}.")
    if ctx.current_approach:
        parts.append(f"Approach: {ctx.current_approach}.")
    if ctx.approaches_tried:
        parts.append(f"Tried: {'; '.join(ctx.approaches_tried)}.")
    if ctx.decisions:
        parts.append(f"Decisions: {'; '.join(ctx.decisions)}.")
    if ctx.files_changed:
        parts.append(f"Files: {', '.join(ctx.files_changed)}.")
    if ctx.git_diff_summary:
        parts.append(f"Diff: {ctx.git_diff_summary}.")
    if ctx.next_steps:
        parts.append(f"Next: {'; '.join(ctx.next_steps)}.")
    if ctx.handoff_to:
        parts.append(f"Handoff to {ctx.handoff_to}: {ctx.handoff_note or ''}.")
    if ctx.tags:
        parts.append(f"Tags: {', '.join(ctx.tags)}.")
    parts.append("Continue from this context.")
    return " ".join(parts)


def _esc(text: str) -> str:
    """Escape XML special characters."""
    return (
        text.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
    )
