from __future__ import annotations

import json
from typing import Any, Callable, Dict, Optional


TRANSCRIPT_TOPICS_PROMPT_V1 = """You are given transcript nodes with stable node IDs.
Group nodes into major discussion topics.

Return ONLY valid JSON list:
[
  {
    "topic": "Regulatory Approval Timeline",
    "node_ids": ["N0001", "N0002"],
    "start_time": "00:35",
    "end_time": "03:10",
    "summary": "brief summary of this topic",
    "sentiment": "Positive | Neutral | Negative"
  }
]

Rules:
- `topic` is required (or `heading` alias).
- `node_ids` is required and must contain existing node IDs only.
- Each node ID must appear in exactly one topic (no duplicates, no omissions).
- `start_time` and `end_time` are optional; include them when clear.
- summary should be present.
- sentiment should be one of Positive/Neutral/Negative.
- Do not rewrite transcript text; node text will be mapped later by system.

Transcript nodes:
{content}
"""


def render_transcript_topics_prompt(
    content: str,
    template: Optional[str | Callable[[str, Dict[str, Any]], str]] = None,
    extra: Optional[Dict[str, Any]] = None,
) -> str:
    payload = extra or {}
    if callable(template):
        return template(content, payload)
    chosen = template or TRANSCRIPT_TOPICS_PROMPT_V1
    # Avoid str.format on JSON examples with braces in prompt body.
    out = chosen.replace("{content}", content)
    out = out.replace("{extra_json}", json.dumps(payload, ensure_ascii=False))
    return out
