"""Declared canonical graph cases, independent of approximate encodings."""

import copy
import importlib.util
from pathlib import Path

HERE = Path(__file__).resolve().parent
SPEC = importlib.util.spec_from_file_location(
    "shape_admission", HERE.parent / "vsa-1310/admit.py"
)
ADMISSION = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(ADMISSION)
MAX_EDGES = 128  # trellis-core/src/entity.rs:MAX_EDGES
KINDS = (
    "concept",
    "typed_domain",
    "struct_shape",
    "module_boundary",
    "convention",
    "decision_anchor",
    "anti_pattern",
)
FAMILIES = (
    "concepts",
    "typed_domains",
    "struct_shapes",
    "module_boundaries",
    "conventions",
    "decision_anchors",
    "anti_patterns",
)
RELATIONS = (
    "contains",
    "implements",
    "depends_on",
    "conforms_to",
    "governed_by",
    "exhibits",
    "mitigates",
)


def cases():
    declared = []
    for count in range(MAX_EDGES + 1):
        nodes = [{"key": "hub", "kind": "concept"}] + [
            {"key": f"leaf-{i}", "kind": "concept"} for i in range(count)
        ]
        edges = [
            {"source": "hub", "target": node["key"], "kind": "depends_on"}
            for node in nodes[1:]
        ]
        declared.append({"label": f"hub-{count}", "nodes": nodes, "edges": edges})
    nodes = [
        {"key": key, "kind": "concept"}
        for key in ["hub", "repeat", "near", "island", "terminal"]
    ]
    nodes += [{"key": f"mixed-{i}", "kind": kind} for i, kind in enumerate(KINDS)]
    edges = [
        {
            "source": root,
            "target": f"mixed-{i}",
            "kind": RELATIONS[i] if root != "near" or i != 0 else "implements",
        }
        for root in ["hub", "repeat", "near"]
        for i in range(len(KINDS))
    ]
    edges += [{"source": "island", "target": "terminal", "kind": "depends_on"}]
    bridge = {"source": "mixed-0", "target": "island", "kind": "depends_on"}
    for label in ["mixed", "edge-add", "edge-change", "edge-remove"]:
        selected = copy.deepcopy(edges)
        if label in ["edge-add", "edge-change"]:
            selected.append(
                {**bridge, "kind": "depends_on" if label == "edge-add" else "contains"}
            )
        declared.append({"label": label, "nodes": nodes, "edges": selected})
    return declared


def declaration(node, metadata):
    key, kind = node["key"], node["kind"]
    common = {"key": key, "metadata": copy.deepcopy(metadata)}
    reason = "Explicit controlled graph research; not a source observation."
    if kind == "concept":
        payload = {"name": key, "definition": reason}
    elif kind == "typed_domain":
        payload = {
            "name": key,
            "wrapped_type": "ResearchValue",
            "claimed_concepts": ["hub"],
            "value_semantics": [],
            "construction_patterns": [],
            "unanchored_reason": reason,
        }
    elif kind == "struct_shape":
        payload = {
            "name": key,
            "fields": [],
            "architectural_role": reason,
            "attributes": [],
            "unanchored_reason": reason,
        }
    elif kind == "module_boundary":
        payload = {
            "module_path": key,
            "public_exports": [],
            "architectural_role": reason,
            "allowed_dependencies": [],
            "adjacent_boundaries": [],
        }
    elif kind == "convention":
        payload = {
            "name": key,
            "pattern": reason,
            "scope": reason,
            "examples": [],
            "exceptions": [],
            "strength": "binding",
            "rationale": reason,
        }
    elif kind == "decision_anchor":
        payload = {
            "title": key,
            "decision": reason,
            "rationale": reason,
            "strength": "binding",
        }
    else:
        payload = {
            "name": key,
            "signature": reason,
            "rationale": reason,
            "replacements": ["mixed-1"],
            "disowned_concepts": ["hub"],
            "state": "binding",
        }
    return {**common, **payload}


def manifest(case, metadata):
    value = ADMISSION.empty_manifest()
    for node in case["nodes"]:
        value[FAMILIES[KINDS.index(node["kind"])]].append(declaration(node, metadata))
    edge_metadata = {
        key: metadata[key]
        for key in [
            "evidence",
            "authority",
            "resolution",
            "confidence",
            "validity",
            "freshness",
            "visibility",
            "data_class",
        ]
    }
    value["edges"] = [{**edge_metadata, **edge} for edge in case["edges"]]
    return value
