from __future__ import annotations

from app.modules.rag.indexing.docs.models import RelationEdge


class DocsRelationExtractor:
    def extract(self, frontmatter: dict, *, source_id: str) -> list[RelationEdge]:
        edges: list[RelationEdge] = []
        parent = str(frontmatter.get("parent") or "").strip()
        if parent:
            edges.append(RelationEdge(source_id=source_id, relation_type="parent", target_id=parent, anchor="frontmatter.parent"))
        for child in frontmatter.get("children") or []:
            target = str(child or "").strip()
            if target:
                edges.append(RelationEdge(source_id=source_id, relation_type="child", target_id=target, anchor="frontmatter.children"))
        for item in frontmatter.get("links") or []:
            if not isinstance(item, dict):
                continue
            relation_type = str(item.get("type") or "").strip()
            target = str(item.get("target") or "").strip()
            if relation_type and target:
                edges.append(RelationEdge(source_id=source_id, relation_type=relation_type, target_id=target, anchor="frontmatter.links"))
        return edges
