"""Renderer helpers to avoid duplicate titles between contract and UI templates."""

from __future__ import annotations

import re


def _normalize_title(value: str) -> str:
    text = str(value or "").strip().lower()
    text = re.sub(r"[^\w\sа-яё0-9]", " ", text, flags=re.IGNORECASE)
    return re.sub(r"\s+", " ", text).strip()


def strip_duplicate_renderer_title(
    rendered: str,
    *,
    contract_title: str = "",
    body_md: str = "",
) -> tuple[str, bool]:
    """Remove a leading title from rendered output when it duplicates contract/body title."""
    output = str(rendered or "")
    title = str(contract_title or "").strip()
    if not title:
        body = str(body_md or "").strip()
        header_match = re.match(r"^(?:#{1,6}\s+|\*\*)(.+?)(?:\*\*)?\s*$", body.splitlines()[0] if body else "")
        if header_match:
            title = str(header_match.group(1) or "").strip()

    if not title or not output.strip():
        return output, False

    title_key = _normalize_title(title)
    lines = output.splitlines()
    if not lines:
        return output, False

    first = lines[0].strip()
    first_key = _normalize_title(re.sub(r"^(?:#{1,6}\s+|\*\*|\*\s+)", "", first).strip(" *"))
    if not first_key:
        return output, False

    if first_key == title_key or first_key.startswith(title_key) or title_key.startswith(first_key):
        remaining = "\n".join(lines[1:]).lstrip("\n")
        return remaining, True
    return output, False
