from __future__ import annotations

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


SEMI_STRUCTURED_HEADINGS_PROMPT_V1 = """You are given raw pages from a semi-structured document.
Identify likely section headings and their page starts.

Return ONLY valid JSON list in this schema:
[
  {
    "structure": "optional numbering like 1 or 2.1",
    "title": "heading text from document",
    "physical_index": 1
  }
]

Rules:
- Keep titles concise and faithful to source wording.
- Prefer major sections over minor fragments.
- physical_index must be the source page number.

Document text:
{content}
"""


def render_semi_structured_headings_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 SEMI_STRUCTURED_HEADINGS_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
