"""Logical consistency checks run before graph state is published."""
from __future__ import annotations

from typing import Any

from ..build.document_content import utf8_size


class GraphValidationError(RuntimeError):
    pass


def validate_graph_state(
    store: Any,
    keyword_index: Any,
    symbol_index: Any,
    file_index: Any,
) -> None:
    """Reject snapshots with dangling graph or index references."""
    try:
        nodes = store.get_all_nodes()
    except (AttributeError, NotImplementedError):
        node_types = (
            "repository", "module", "class", "function", "symbol", "file",
            "document", "section", "document_chunk", "concept", "test", "commit", "pr",
            "convention", "code_chunk", "diff", "manifest",
        )
        nodes = [
            node
            for node_type in node_types
            for node in store.get_nodes_by_type(node_type)
        ]
    by_id = {
        str(node["id"]): node
        for node in nodes
        if node.get("id")
    }
    errors: list[str] = []

    edges = store.get_all_edges()
    edge_keys = {(edge.source, edge.target, edge.type) for edge in edges}
    for edge in edges:
        if not edge.source:
            continue  # None/empty source — stale reference, skip
        if edge.source not in by_id:
            errors.append(f"edge {edge.id} has missing source {edge.source}")
        if not edge.target:
            continue  # None/empty target — stale reference, skip
        if edge.target not in by_id:
            errors.append(f"edge {edge.id} has missing target {edge.target}")

    files = file_index.snapshot()
    ownership: dict[str, str] = {}
    for path, info in files.items():
        root_id = info.get("file_id")
        if not root_id or root_id not in by_id:
            errors.append(f"file index {path} has missing root {root_id}")
            continue
        root_path = str(by_id[root_id].get("path", "")).replace("\\", "/")
        if root_path and root_path != str(path).replace("\\", "/"):
            errors.append(f"file index path {path} disagrees with node path {root_path}")
        for owned_id in info.get("nodes", []):
            if not owned_id:
                continue
            if owned_id not in by_id:
                errors.append(f"file index {path} owns missing node {owned_id}")
            else:
                ownership[str(owned_id)] = str(path).replace("\\", "/")

    for node_type in ("file", "document", "manifest"):
        for node in store.get_nodes_by_type(node_type):
            path = node.get("path")
            node_id = node.get("id")
            info = file_index.get(path) if path else None
            if not info or info.get("file_id") != node_id:
                errors.append(f"{node_type} {node_id} has no matching file ownership")

    keyword_documents = set(getattr(keyword_index, "documents", {}))
    keyword_lengths = set(getattr(keyword_index, "doc_len", {}))
    keyword_reverse = getattr(keyword_index, "_doc_tokens", {})
    keyword_reverse_ids = set(keyword_reverse)
    keyword_postings = getattr(keyword_index, "postings", {})
    keyword_posting_ids = {
        str(doc_id)
        for posting in keyword_postings.values()
        for doc_id in posting
    }
    keyword_ids = (
        keyword_documents
        | keyword_lengths
        | keyword_reverse_ids
        | keyword_posting_ids
    )
    for doc_id in keyword_ids:
        if doc_id not in by_id:
            errors.append(f"keyword index references missing node {doc_id}")
    if keyword_documents != keyword_lengths:
        errors.append("keyword documents and doc_len registries disagree")
    if keyword_documents != keyword_reverse_ids:
        errors.append("keyword documents and reverse-token registries disagree")
    if not keyword_posting_ids <= keyword_documents:
        errors.append("keyword postings contain unregistered document IDs")
    for token, posting in keyword_postings.items():
        for doc_id, frequency in posting.items():
            if token not in keyword_reverse.get(doc_id, set()):
                errors.append(
                    f"keyword posting {token!r} lacks reverse entry for {doc_id}"
                )
            if isinstance(frequency, bool) or not isinstance(frequency, int) or frequency <= 0:
                errors.append(
                    f"keyword posting {token!r} has invalid frequency for {doc_id}"
                )
    for doc_id, tokens in keyword_reverse.items():
        for token in tokens:
            if doc_id not in keyword_postings.get(token, {}):
                errors.append(
                    f"keyword reverse entry {doc_id} lacks posting for {token!r}"
                )
    for symbol_name, node_ids in symbol_index.snapshot().items():
        for node_id in node_ids:
            if node_id not in by_id:
                errors.append(
                    f"symbol index {symbol_name} references missing node {node_id}"
                )

    for module in store.get_nodes_by_type("module"):
        module_id = module.get("id")
        parent_id = module.get("parent")
        if parent_id:
            if parent_id not in by_id:
                errors.append(f"module {module_id} has missing parent {parent_id}")
            elif (parent_id, module_id, "CONTAIN") not in edge_keys:
                errors.append(
                    f"module {module_id} lacks parent CONTAIN edge from {parent_id}"
                )

    # Projection-integrity checks: after a mini projection, surviving nodes
    # must not reference removed functions/classes.
    for cls in store.get_nodes_by_type("class"):
        cls_id = cls.get("id")
        for method_id in cls.get("methods") or []:
            if method_id not in by_id:
                errors.append(
                    f"class {cls_id} references missing method {method_id}"
                )
    for fn in store.get_nodes_by_type("function"):
        fn_id = fn.get("id")
        class_id = fn.get("class_id")
        if class_id and class_id not in by_id:
            # Cross-file impl blocks (impl Trait for Bar in a different file
            # than where Bar is defined) produce a class_id that doesn't match
            # any ClassNode in this file.  This is legitimate Rust — clear the
            # stale reference rather than failing validation.
            store.update_node(fn_id, {"class_id": None})

    documents = {
        str(document.get("id")): document
        for document in store.get_nodes_by_type("document")
        if document.get("id")
    }
    sections = {
        str(section.get("id")): section
        for section in store.get_nodes_by_type("section")
        if section.get("id")
    }
    for doc_id, document in documents.items():
        content = document.get("content")
        complete = document.get("content_complete") is True
        content_state = document.get("content_state")
        try:
            declared_bytes = int(document.get("content_bytes") or 0)
        except (TypeError, ValueError):
            declared_bytes = -1
            errors.append(f"document {doc_id} has invalid content_bytes")
        if complete and not isinstance(content, str):
            errors.append(f"document {doc_id} is complete without string content")
            continue
        if not complete and content is not None:
            errors.append(f"document {doc_id} has content but is not complete")
            continue
        if complete and content_state not in (None, "full"):
            errors.append(
                f"document {doc_id} is complete with state {content_state!r}"
            )
        if not complete:
            if declared_bytes != 0:
                errors.append(
                    f"document {doc_id} is incomplete with nonzero content_bytes"
                )
            if content_state == "full":
                errors.append(f"document {doc_id} is incomplete with full state")
            if content_state not in (
                None, "not_selected", "omitted_oversize", "omitted_binary",
            ):
                errors.append(
                    f"document {doc_id} has unknown content state {content_state!r}"
                )
        if complete:
            expected_bytes = utf8_size(content)
            if declared_bytes != expected_bytes:
                errors.append(
                    f"document {doc_id} content_bytes {declared_bytes} "
                    f"does not match {expected_bytes}"
                )

    for chunk in store.get_nodes_by_type("document_chunk"):
        chunk_id = str(chunk.get("id") or "")
        doc_id = str(chunk.get("doc_id") or "")
        document = documents.get(doc_id)
        if document is None:
            errors.append(f"document chunk {chunk_id} has missing parent {doc_id}")
            continue
        content = document.get("content")
        if document.get("content_complete") is not True or not isinstance(content, str):
            errors.append(f"document chunk {chunk_id} parent {doc_id} is not complete")
            continue
        raw_ranges = (
            chunk.get("char_start"), chunk.get("char_end"),
            chunk.get("line_start"), chunk.get("line_end"),
        )
        if any(isinstance(value, bool) for value in raw_ranges):
            errors.append(f"document chunk {chunk_id} has invalid ranges")
            continue
        try:
            char_start = int(chunk.get("char_start"))
            char_end = int(chunk.get("char_end"))
            line_start = int(chunk.get("line_start"))
            line_end = int(chunk.get("line_end"))
        except (TypeError, ValueError):
            errors.append(f"document chunk {chunk_id} has invalid ranges")
            continue
        if not 0 <= char_start < char_end <= len(content):
            errors.append(
                f"document chunk {chunk_id} has out-of-bounds character range"
            )
        if line_start < 1 or line_end < line_start:
            errors.append(f"document chunk {chunk_id} has invalid line range")
        try:
            document_line_count = int(document.get("line_count") or 0)
        except (TypeError, ValueError):
            document_line_count = 0
        if document_line_count and line_end > document_line_count:
            errors.append(
                f"document chunk {chunk_id} line range exceeds its parent"
            )
        section_id = chunk.get("section_id")
        if section_id is not None:
            section = sections.get(str(section_id))
            if section is None:
                errors.append(
                    f"document chunk {chunk_id} has missing section {section_id}"
                )
            elif section.get("doc_id") != doc_id:
                errors.append(
                    f"document chunk {chunk_id} section belongs to another document"
                )
        document_path = str(document.get("path") or "").replace("\\", "/")
        if ownership.get(chunk_id) != document_path:
            errors.append(
                f"document chunk {chunk_id} has no matching file ownership"
            )

    if errors:
        preview = "; ".join(errors[:10])
        if len(errors) > 10:
            preview += f"; ... ({len(errors) - 10} more)"
        raise GraphValidationError(preview)