"""profile.md 分节解析与 merge — enrich 用。"""

from __future__ import annotations

import re

from niannian.virtual_persona.profile_schema import REQUIRED_PROFILE_SECTIONS

_SECTION_RE = re.compile(r"^## (.+)$", re.MULTILINE)


def parse_profile_sections(profile_md: str) -> dict[str, str]:
    text = str(profile_md or "")
    title = ""
    for line in text.splitlines():
        if line.startswith("# ") and not line.startswith("## "):
            title = line[2:].strip()
            break
    sections: dict[str, str] = {name: "" for name in REQUIRED_PROFILE_SECTIONS}
    matches = list(_SECTION_RE.finditer(text))
    for idx, match in enumerate(matches):
        name = match.group(1).strip()
        if name not in sections:
            continue
        start = match.end()
        end = matches[idx + 1].start() if idx + 1 < len(matches) else len(text)
        sections[name] = text[start:end].strip()
    return {"__title__": title, **sections}


def section_is_empty(content: str) -> bool:
    body = str(content or "").strip()
    if not body:
        return True
    return body in {"-", "—", "（待填）", "待填"}


def merge_profile_sections(
    profile_md: str,
    updates: dict[str, str],
    *,
    only_empty: bool = True,
) -> str:
    parsed = parse_profile_sections(profile_md)
    title = parsed.pop("__title__", "") or "角色"
    for name in REQUIRED_PROFILE_SECTIONS:
        new_val = updates.get(name)
        if new_val is None:
            continue
        new_val = str(new_val).strip()
        if not new_val:
            continue
        if only_empty and not section_is_empty(parsed.get(name, "")):
            continue
        parsed[name] = new_val
    lines = [f"# {title}", ""]
    for name in REQUIRED_PROFILE_SECTIONS:
        lines.append(f"## {name}")
        body = parsed.get(name, "").strip()
        lines.append(body)
        lines.append("")
    return "\n".join(lines).rstrip() + "\n"
