from __future__ import annotations

import re


class DocsCanonicalDocIdResolver:
    _DOC_PATH_RE = re.compile(r"docs/(?:documentation/)?(?P<section>api|domain|logic|architecture)/(?P<name>[^/]+)\.md$", re.IGNORECASE)
    _TITLE_ENDPOINT_RE = re.compile(r"/([a-z0-9_{}-]+)", re.IGNORECASE)

    def candidates(self, row: dict) -> list[str]:
        metadata = dict(row.get("metadata") or {})
        values: list[str] = []
        for candidate in (
            metadata.get("document_id"),
            metadata.get("doc_id"),
            self.from_path(str(row.get("path") or "")),
            self.from_title(str(row.get("title") or ""), str(row.get("path") or "")),
        ):
            value = str(candidate or "").strip()
            if value and value not in values:
                values.append(value)
        return values

    def from_path(self, path: str) -> str | None:
        match = self._DOC_PATH_RE.search((path or "").strip())
        if match is None:
            return None
        section = match.group("section").lower()
        name = match.group("name").lower().replace("-", "_")
        if section == "api" and not name.endswith("_endpoint"):
            name = f"{name}_endpoint"
        if section == "domain" and name.endswith("_entity"):
            name = name[: -len("_entity")]
        return f"{section}.{name}"

    def from_title(self, title: str, path: str) -> str | None:
        normalized = (title or "").strip().lower()
        if "/health" in normalized:
            return "api.health_endpoint"
        if "/send" in normalized:
            return "api.send_message_endpoint"
        match = self._TITLE_ENDPOINT_RE.search(normalized)
        section = "api" if "/api/" in (path or "").lower() else ""
        if match and section:
            slug = match.group(1).replace("-", "_")
            return f"{section}.{slug}_endpoint"
        return None
