from __future__ import annotations

import re

import yaml

from app.core.agent.processes.v2.workflows.doc_update_from_feature_v2.subprocesses.common.template_models import (
    SectionDraft,
    TemplateSpec,
)


class TemplateDocumentComposer:
    def compose(self, template: TemplateSpec, frontmatter: str, sections: list[SectionDraft], fallback_title: str) -> str:
        title = self._extract_title(frontmatter) or fallback_title
        section_map = {(item.level, item.title): item.content.strip() for item in sections}
        lines = [frontmatter.strip(), "", f"{'#' * template.title_level} {title}", ""]
        for section in template.sections:
            lines.append(f"{'#' * section.level} {section.title}")
            content = section_map.get((section.level, section.title), "")
            if content:
                lines.extend(["", content, ""])
                continue
            lines.append("")
        return "\n".join(lines).strip() + "\n"

    def _extract_title(self, frontmatter: str) -> str:
        value = frontmatter.strip()
        match = re.match(r"^---\n(.*?)\n---$", value, re.DOTALL)
        if not match:
            return ""
        payload = yaml.safe_load(match.group(1)) or {}
        return str(payload.get("title") or "").strip() if isinstance(payload, dict) else ""
