from __future__ import annotations
import re
from typing import Any
from collections.abc import Callable

from ..graph.models import Edge
from .relation_resolver import replace_edge_types


DESCRIBE_EDGE_TYPES = frozenset({"DESCRIBE"})

# Identifier/qualified-name tokens with Unicode identifier support.  Matching
# tokens rather than substrings prevents short symbols such as ``id`` and
# ``run`` from linking ordinary words such as ``valid`` and ``runtime``.
_SYMBOL_TOKEN_RE = re.compile(
    r"(?<![\w$])~?(?:[^\W\d]|[$])[\w$]*"
    r"(?:(?:::|\.)~?(?:[^\W\d]|[$])[\w$]*)*(?![\w$])",
    re.UNICODE,
)


def _is_han(character: str) -> bool:
    codepoint = ord(character)
    return (
        0x3400 <= codepoint <= 0x4DBF
        or 0x4E00 <= codepoint <= 0x9FFF
        or 0xF900 <= codepoint <= 0xFAFF
        or 0x20000 <= codepoint <= 0x2FA1F
    )


def _symbols_in_text(
    text: str,
    symbols_by_name: dict[str, tuple[str, ...]],
    han_symbols_by_first: dict[str, tuple[tuple[str, tuple[str, ...]], ...]],
) -> set[str]:
    """Resolve every exact identifier token in ``text`` in one scan."""
    matches: set[str] = set()
    for token_match in _SYMBOL_TOKEN_RE.finditer(text):
        token = token_match.group(0)
        spellings = {token}
        if "::" in token or "." in token:
            spellings.update(token.replace("::", ".").split("."))
        for spelling in spellings:
            matches.update(symbols_by_name.get(spelling, ()))
    # Han prose normally has no whitespace boundaries.  Indexing candidates by
    # their first character keeps this linear for ordinary text while allowing
    # identifiers such as ``图谱`` to match inside ``介绍图谱功能``.
    for index, character in enumerate(text):
        for symbol_name, symbol_ids in han_symbols_by_first.get(character, ()):
            if text.startswith(symbol_name, index):
                matches.update(symbol_ids)
    return matches


class LinkEngine:
    def __init__(self, store: Any):
        self.store = store

    def build_explicit_links(self) -> list[Edge]:
        edges = []
        documents = sorted(
            self.store.get_nodes_by_type("document"),
            key=lambda node: str(node.get("id", "")),
        )
        symbol_ids: dict[str, set[str]] = {}
        for node_type in ("function", "class"):
            for node in self.store.get_nodes_by_type(node_type):
                if node.get("name") and node.get("id"):
                    symbol_ids.setdefault(str(node["name"]), set()).add(
                        str(node["id"]),
                    )
        symbols_by_name = {
            name: tuple(sorted(ids))
            for name, ids in symbol_ids.items()
        }
        han_symbols: dict[str, list[tuple[str, tuple[str, ...]]]] = {}
        for name, ids in symbols_by_name.items():
            if name and all(_is_han(character) for character in name):
                han_symbols.setdefault(name[0], []).append((name, ids))
        han_symbols_by_first = {
            first: tuple(sorted(entries, key=lambda entry: entry[0]))
            for first, entries in han_symbols.items()
        }

        sections_by_doc: dict[str, list[dict[str, Any]]] = {}
        for section in self.store.get_nodes_by_type("section"):
            doc_id = section.get("doc_id")
            if doc_id:
                sections_by_doc.setdefault(str(doc_id), []).append(section)
        for sections in sections_by_doc.values():
            sections.sort(key=lambda node: str(node.get("id", "")))

        edge_ids: set[str] = set()

        for doc in documents:
            doc_id = str(doc.get("id", ""))
            if not doc_id:
                continue
            sections = sections_by_doc.get(doc_id, [])
            doc_targets = _symbols_in_text(
                str(doc.get("title", "")),
                symbols_by_name,
                han_symbols_by_first,
            )

            for sec in sections:
                sec_id = str(sec.get("id", ""))
                if not sec_id:
                    continue
                sec_text = f"{sec.get('title', '')} {sec.get('content', '')}"
                section_targets = _symbols_in_text(
                    sec_text, symbols_by_name, han_symbols_by_first,
                )
                doc_targets.update(section_targets)
                for symbol_id in sorted(section_targets):
                    eid = f"{sec_id}->{symbol_id}:DESCRIBE"
                    if eid in edge_ids:
                        continue
                    edges.append(Edge(
                        id=eid,
                        type="DESCRIBE",
                        source=sec_id,
                        target=symbol_id,
                        properties={"method": "section"},
                    ))
                    edge_ids.add(eid)

            for symbol_id in sorted(doc_targets):
                eid = f"{doc_id}->{symbol_id}:DESCRIBE"
                if eid in edge_ids:
                    continue
                edges.append(Edge(
                    id=eid,
                    type="DESCRIBE",
                    source=doc_id,
                    target=symbol_id,
                    properties={"method": "explicit"},
                ))
                edge_ids.add(eid)

        return edges

    def build_historical_links(self) -> list[Edge]:
        return []

    def build_all_links(self) -> list[Edge]:
        """Calculate DESCRIBE edges without mutating the store."""
        edges = []
        edges.extend(self.build_explicit_links())
        edges.extend(self.build_historical_links())
        return edges

    def calculate_all_links(self) -> list[Edge]:
        """Explicit name for the pure calculation phase."""
        return self.build_all_links()

    def replace_all_links(
        self,
        delete_edges_by_type: Callable[[set[str]], None] | None = None,
    ) -> list[Edge]:
        """Atomically-shaped replace API used by full and incremental builds.

        Replacements are fully calculated before any old DESCRIBE edge is
        removed.  Transaction/locking policy remains the caller's concern.
        """
        return replace_edge_types(
            self.store,
            DESCRIBE_EDGE_TYPES,
            self.calculate_all_links(),
            delete_edges_by_type,
        )