"""Grammar-Aware Dynamics: Proactive U1-U6 enforcement in operator selection.

Bridges the grammar validation system (U1-U6) with the dynamic operator
selection layer.  Provides **incremental** grammar checking for step-by-step
dynamics, where operators are selected one at a time per node.

Physics basis
-------------
The nodal equation motivates operator contracts and calibrated grammar
policies. This layer filters candidates against available state/history;
it neither proves trajectory stability nor supplies an autonomous selection law.

Incremental rule applicability
------------------------------
- **U1a** (Initiation): Checked when finite scalar EPI is zero and history is empty.
- **U2**  (Debt): Tracked via a cumulative destabilizer/stabilizer debt
  counter, independent of bounded history retention.
- **U3**  (Resonant Coupling): Phase compatibility required for UM/RA candidates.
- **U4a** (Bifurcation triggers): OZ/ZHIR require handlers in recent context.
- **U4b** (Transformer context): ZHIR/THOL need a recent destabilizer (and
  prior IL for ZHIR).
- **U1b** (Closure) and **U5/U6** are whole-sequence or telemetry checks and
  cannot be fully enforced incrementally; they are advisory here.

References
----------
- AGENTS.md §Unified Grammar (U1-U6)
- UNIFIED_GRAMMAR_RULES.md — policies, hypotheses and limits
- grammar_core.py — batch validator (full sequences)
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Sequence

from ..config.operator_names import BIFURCATION_WINDOW, U2_DEBT_CAPACITY
from ..types import Glyph
from .grammar_debt import (
    PRIOR_COHERENCE_KEY,
    U2_DEBT_KEY,
    advance_debt,
    advance_prior_coherence,
    debt_from_history,
    node_debt,
    node_has_prior_coherence,
    require_replayable_history,
)
from .grammar_types import (
    BIFURCATION_HANDLERS,
    BIFURCATION_TRIGGERS,
    CLOSURES,
    COUPLING_RESONANCE,
    DESTABILIZERS,
    GENERATORS,
    GLYPH_TO_FUNCTION,
    STABILIZERS,
    TRANSFORMERS,
    glyph_function_name,
)

# ── glyph code ↔ canonical executable-identifier helpers ───────────────────

# Build fast lookup from glyph code string ("IL") → canonical name ("coherence")
_CODE_TO_NAME: dict[str, str] = {g.value: name for g, name in GLYPH_TO_FUNCTION.items()}
# Reverse: canonical name → glyph code string
_NAME_TO_CODE: dict[str, str] = {name: g.value for g, name in GLYPH_TO_FUNCTION.items()}

# Sets of *glyph codes* (uppercase) for fast membership tests
_DESTABILIZER_CODES = frozenset(
    _NAME_TO_CODE[n] for n in DESTABILIZERS if n in _NAME_TO_CODE
)
_STABILIZER_CODES = frozenset(
    _NAME_TO_CODE[n] for n in STABILIZERS if n in _NAME_TO_CODE
)
_COUPLING_CODES = frozenset(
    _NAME_TO_CODE[n] for n in COUPLING_RESONANCE if n in _NAME_TO_CODE
)
_GENERATOR_CODES = frozenset(_NAME_TO_CODE[n] for n in GENERATORS if n in _NAME_TO_CODE)
_BIFURCATION_TRIGGER_CODES = frozenset(
    _NAME_TO_CODE[n] for n in BIFURCATION_TRIGGERS if n in _NAME_TO_CODE
)
_HANDLER_CODES = frozenset(
    _NAME_TO_CODE[n] for n in BIFURCATION_HANDLERS if n in _NAME_TO_CODE
)
_TRANSFORMER_CODES = frozenset(
    _NAME_TO_CODE[n] for n in TRANSFORMERS if n in _NAME_TO_CODE
)
_CLOSURE_CODES = frozenset(_NAME_TO_CODE[n] for n in CLOSURES if n in _NAME_TO_CODE)

# Canonical fallback when all else fails — IL (Coherence) is always safe
_FALLBACK_CODE = "IL"

# How many recent glyphs to consider for incremental grammar context
_DEFAULT_WINDOW = 6

# ── data structures ───────────────────────────────────────────────────────


@dataclass(slots=True)
class GrammarViolation:
    """A single incremental grammar rule violation."""

    rule: str  # e.g. "U2", "U4b"
    message: str  # human-readable explanation
    severity: str  # "error" (must fix) or "warning" (advisory)


@dataclass(slots=True)
class CandidateResult:
    """Result of validating a single candidate glyph against recent history."""

    candidate: str
    allowed: bool
    violations: list[GrammarViolation] = field(default_factory=list)
    suggested_alternative: str | None = None


# ── core incremental checks ──────────────────────────────────────────────


def _to_code(glyph: Any) -> str:
    """Normalize a glyph to its uppercase code string (e.g. 'IL')."""
    name = glyph_function_name(glyph)
    if name in _NAME_TO_CODE:
        return _NAME_TO_CODE[name]
    s = str(glyph).strip()
    # Handle "Glyph.AL" format
    if "." in s:
        s = s.rsplit(".", 1)[-1]
    return s.upper()  # best effort; unknown candidates fail syntax validation


def _recent_codes(G: Any, node: Any, window: int = _DEFAULT_WINDOW) -> list[str]:
    """Extract the last *window* glyph codes from the node's history."""
    nd = G.nodes[node]
    raw = nd.get("glyph_history")
    require_replayable_history(raw)
    if not raw:
        return []
    items = list(raw)[-window:]
    return [_to_code(g) for g in items]


def _check_u1a(
    candidate: str,
    history: list[str],
    epi: float,
) -> GrammarViolation | None:
    """U1a: If EPI ≈ 0 and history is empty, first glyph must be a generator."""
    if history or epi != 0.0:
        return None  # not applicable
    if candidate not in _GENERATOR_CODES:
        return GrammarViolation(
            rule="U1a",
            message=(
                f"EPI=0 with empty history requires a generator "
                f"({sorted(_GENERATOR_CODES)}), got '{candidate}'."
            ),
            severity="error",
        )
    return None


def _check_u2(
    candidate: str,
    history: list[str],
    *,
    current_debt: int | None = None,
) -> GrammarViolation | None:
    """U2: Convergence — destabilizer debt must not grow unbounded.

    Neutral operations cannot erase debt. A stabilizer may reduce a legacy
    over-capacity state, but new destabilization above capacity is rejected.
    """
    before = debt_from_history(history) if current_debt is None else current_debt
    debt = advance_debt(before, candidate)
    if debt > U2_DEBT_CAPACITY and debt >= before:
        return GrammarViolation(
            rule="U2",
            message=(
                f"Convergence violation: uncompensated destabilizer debt "
                f"{before} -> {debt} exceeds capacity {U2_DEBT_CAPACITY}. "
                f"Add a stabilizer (IL/THOL) before more destabilizers."
            ),
            severity="error",
        )
    return None


def _check_u3(
    candidate: str,
    G: Any,
    node: Any,
) -> GrammarViolation | None:
    """U3: Coupling/resonance candidates require phase-compatible neighbours."""
    if candidate not in _COUPLING_CODES:
        return None
    from ._phase_gate import resolve_u3_phase_limits
    from .preconditions import OperatorPreconditionError, validate_phase_gate_u3

    # Symbolic/proactive selection validates configured limits but leaves an
    # isolate unassessed: it may acquire an edge before concrete execution.
    # Every concrete UM/RA path separately requires a compatible live edge.
    resolve_u3_phase_limits(G.graph, operator_code=candidate)
    if not tuple(G.neighbors(node)):
        return None

    # Non-isolated selection and execution share the same wrapped-distance
    # compatibility predicate.
    try:
        validate_phase_gate_u3(G, node, _CODE_TO_NAME[candidate])
    except OperatorPreconditionError as exc:
        return GrammarViolation(
            rule="U3",
            message=str(exc),
            severity="error",
        )
    return None


def _check_u4a(
    candidate: str,
    history: list[str],
    *,
    future_handler: bool = False,
) -> GrammarViolation | None:
    """U4a: Bifurcation triggers need handlers in nearby context."""
    if candidate not in _BIFURCATION_TRIGGER_CODES:
        return None
    # Check if there's a handler anywhere in recent history or candidate itself
    full = history + [candidate]
    has_handler = future_handler or any(g in _HANDLER_CODES for g in full)
    if not has_handler:
        return GrammarViolation(
            rule="U4a",
            message=(
                f"Bifurcation trigger '{candidate}' has no handler "
                f"({sorted(_HANDLER_CODES)}) in recent context."
            ),
            severity="error",
        )
    return None


def _check_u4b(
    candidate: str,
    history: list[str],
    *,
    has_prior_coherence: bool | None = None,
) -> GrammarViolation | None:
    """U4b: Transformers need recent destabilizer context.

    ZHIR also requires a prior IL (stable base).
    """
    if candidate not in _TRANSFORMER_CODES:
        return None
    # Look for a destabilizer within the emergent relaxation window: the
    # structure stays plastic until the |ΔNFR| perturbation relaxes into the
    # scalar-surrogate band (BIFURCATION_WINDOW = 3, an operator-position policy).
    w = BIFURCATION_WINDOW
    recent = history[-w:] if len(history) >= w else history
    has_destab = any(g in _DESTABILIZER_CODES for g in recent)
    if not has_destab:
        return GrammarViolation(
            rule="U4b",
            message=(
                f"Transformer '{candidate}' requires a recent destabilizer "
                f"(within ~{w} ops). Recent: {recent}."
            ),
            severity="error",
        )
    # ZHIR additionally requires prior IL
    if candidate == "ZHIR":
        has_il = "IL" in history if has_prior_coherence is None else has_prior_coherence
        if not has_il:
            return GrammarViolation(
                rule="U4b",
                message=(
                    "ZHIR (Mutation) requires prior IL (Coherence) "
                    "for a stable base before phase transformation."
                ),
                severity="error",
            )
    return None


# ── public API ────────────────────────────────────────────────────────────


def _check_violations(
    G: Any,
    node: Any,
    code: str,
    window: int = _DEFAULT_WINDOW,
    *,
    sequence_context: Any = None,
) -> tuple[bool, list[GrammarViolation]]:
    """Core validation logic without alternative suggestion (avoids recursion)."""
    if code not in _CODE_TO_NAME:
        return False, [
            GrammarViolation(
                rule="SYNTAX",
                message=f"Unknown canonical operator '{code}'.",
                severity="error",
            )
        ]
    history = _recent_codes(G, node, window)

    from ..alias import get_attr
    from ..constants.aliases import ALIAS_EPI
    from ..types import require_finite_real_scalar_epi

    # An absent coordinate retains the provisional-selection compatibility
    # default. Provided state must be finite and preserve its signed scalar
    # embedding; conversion failure must not imply initialized form.
    epi = require_finite_real_scalar_epi(
        get_attr(
            G.nodes[node],
            ALIAS_EPI,
            1.0,
            strict=True,
            conv=lambda value: value,
        ),
        f"node {node!r} EPI",
    )

    violations: list[GrammarViolation] = []
    future_handler = False
    if sequence_context is not None:
        from .grammar_execution import ValidatedSequenceStep

        if not isinstance(sequence_context, ValidatedSequenceStep):
            raise TypeError("sequence_context must be a validated sequence step")
        future_handler = sequence_context.has_future_handler(code)

    for v in (
        _check_u1a(code, history, epi),
        _check_u4a(code, history, future_handler=future_handler),
    ):
        if v is not None:
            violations.append(v)

    v4b = _check_u4b(
        code, history, has_prior_coherence=node_has_prior_coherence(G.nodes[node])
    )
    if v4b is not None:
        violations.append(v4b)

    v2 = _check_u2(code, history, current_debt=node_debt(G.nodes[node]))
    if v2 is not None:
        violations.append(v2)

    # U3 needs the graph
    v3 = _check_u3(code, G, node)
    if v3 is not None:
        violations.append(v3)

    errors = [v for v in violations if v.severity == "error"]
    allowed = len(errors) == 0
    return allowed, violations


def validate_candidate(
    G: Any,
    node: Any,
    candidate: str | Glyph,
    *,
    window: int = _DEFAULT_WINDOW,
    sequence_context: Any = None,
) -> CandidateResult:
    """Check whether *candidate* is grammar-valid given the node's recent history.

    Runs incremental checks for U1a, U2, U3, U4a, U4b.  Returns a
    :class:`CandidateResult` with ``allowed=True`` if no errors are found.
    A one-shot ``glyph_history`` iterator raises ``ValueError`` without being
    consumed; read-only checks require a replayable list, tuple or deque.
    An optional validated sequence step can supply a future U4a handler;
    it supplies no past history, stabilization credit, or phase permission.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node.
    node : NodeId
        Target node.
    candidate : str | Glyph
        Candidate glyph code (e.g. ``"OZ"``) or :class:`Glyph` enum.
    window : int, optional
        Recent U1/U4 history context (default 6). U2 debt does not expire.

    Returns
    -------
    CandidateResult
        Validation result with violations and suggested alternative.
    """
    code = _to_code(candidate)
    allowed, violations = _check_violations(
        G,
        node,
        code,
        window,
        sequence_context=sequence_context,
    )

    alt: str | None = None
    if not allowed:
        alt = suggest_alternative(G, node, code, window=window)

    return CandidateResult(
        candidate=code,
        allowed=allowed,
        violations=violations,
        suggested_alternative=alt,
    )


def filter_candidates(
    G: Any,
    node: Any,
    candidates: Sequence[str | Glyph],
    *,
    window: int = _DEFAULT_WINDOW,
) -> list[str]:
    """Return only grammar-valid candidates from the given list.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node.
    node : NodeId
        Target node.
    candidates : sequence of str | Glyph
        Candidate glyph codes to evaluate.
    window : int, optional
        Recent history context size.

    Returns
    -------
    list[str]
        Codes that pass incremental grammar checks (errors only; warnings pass).
    """
    result: list[str] = []
    for c in candidates:
        code = _to_code(c)
        allowed, _ = _check_violations(G, node, code, window)
        if allowed:
            result.append(code)
    return result


_PRIORITY_ORDER = ["IL", "THOL", "EN", "SHA", "RA", "NAV", "AL"]
"""Fallback priority: stabilizers first, then neutral, then generators."""


def suggest_alternative(
    G: Any,
    node: Any,
    rejected: str,
    *,
    window: int = _DEFAULT_WINDOW,
) -> str:
    """Suggest the best grammar-safe alternative when *rejected* is invalid.

    Iterates a priority-ordered list of safe candidates and returns the first
    that passes incremental grammar checks.  Falls back to ``IL`` (always safe).

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node.
    node : NodeId
        Target node.
    rejected : str
        The glyph code that was rejected.
    window : int, optional
        Recent history context size.

    Returns
    -------
    str
        A grammar-safe glyph code.
    """
    for alt in _PRIORITY_ORDER:
        if alt == rejected:
            continue
        allowed, _ = _check_violations(G, node, alt, window)
        if allowed:
            return alt
    return _FALLBACK_CODE


def enforce_grammar_on_glyph(
    G: Any,
    node: Any,
    candidate: str | Glyph,
    *,
    window: int = _DEFAULT_WINDOW,
    sequence_context: Any = None,
) -> str:
    """Apply live grammar with an explicit rejection policy.

    ``enforce_canonical_grammar()`` delegates here. The graph-owned setting
    ``GRAMMAR_REJECTION_MODE`` accepts exactly ``"fallback"`` (the compatibility
    default) or ``"raise"``. The latter rejects a blocked candidate without
    calculating an alternative. A validated ``sequence_context`` always raises
    on rejection, regardless of this setting, so its word is not rewritten.

    Both modes apply the same incremental U1a/U2/U3/U4 checks. Strict rejection
    neither derives those policies from the nodal equation nor supplies an
    autonomous selection law. Other selector policies are separate.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node.
    node : NodeId
        Target node.
    candidate : str | Glyph
        Proposed glyph.
    window : int, optional
        Recent history context size.

    Returns
    -------
    str
        The validated (or replaced) glyph code.
    """
    mode = G.graph.get("GRAMMAR_REJECTION_MODE", "fallback")
    if type(mode) is not str:
        raise TypeError("GRAMMAR_REJECTION_MODE must be 'fallback' or 'raise'")
    if mode not in {"fallback", "raise"}:
        raise ValueError("GRAMMAR_REJECTION_MODE must be 'fallback' or 'raise'")

    code = _to_code(candidate)
    allowed, violations = _check_violations(
        G,
        node,
        code,
        window,
        sequence_context=sequence_context,
    )
    if allowed:
        return code
    if mode == "raise" or sequence_context is not None:
        from .grammar_types import StructuralGrammarError

        raise StructuralGrammarError(
            rule=violations[0].rule,
            candidate=code,
            message="; ".join(violation.message for violation in violations),
        )
    return suggest_alternative(G, node, code, window=window)


def validate_sequence_incremental(
    G: Any,
    node: Any,
    sequence: Sequence[str | Glyph],
    *,
    window: int = _DEFAULT_WINDOW,
) -> list[CandidateResult]:
    """Validate a full operator sequence step-by-step against a node's live history.

    Unlike :func:`grammar_core.validate_sequence` (which checks the sequence
    in isolation), this function considers the **actual glyph history** stored
    on the node, simulating how the sequence would be applied incrementally.

    It appends each accepted glyph to a *shadow* history copy so that later
    steps in the sequence see the effect of earlier ones.
    A one-shot ``glyph_history`` iterator raises ``ValueError`` before any
    history is consumed or graph state is temporarily replaced.

    Parameters
    ----------
    G : TNFRGraph
        Graph containing the node.
    node : NodeId
        Target node.
    sequence : sequence of str | Glyph
        Ordered glyphs to validate.
    window : int, optional
        Recent history context size.

    Returns
    -------
    list[CandidateResult]
        One result per step. Only accepted glyphs enter the shadow history.
        Phase checks use the current graph state; this function does not
        simulate operator effects or certify later phase compatibility.
    """
    nd = G.nodes[node]
    raw = nd.get("glyph_history")
    require_replayable_history(raw)
    shadow: list[str] = [_to_code(g) for g in (list(raw) if raw else [])]
    shadow_debt = node_debt(nd)
    shadow_prior_coherence = node_has_prior_coherence(nd)

    results: list[CandidateResult] = []
    for step in sequence:
        code = _to_code(step)
        # Temporarily set shadow history on the node for the check
        had_history = "glyph_history" in nd
        original_history = nd.get("glyph_history")
        had_debt = U2_DEBT_KEY in nd
        original_debt = nd.get(U2_DEBT_KEY)
        had_prior_coherence = PRIOR_COHERENCE_KEY in nd
        original_prior_coherence = nd.get(PRIOR_COHERENCE_KEY)
        nd["glyph_history"] = shadow[-window:] if shadow else []
        nd[U2_DEBT_KEY] = shadow_debt
        nd[PRIOR_COHERENCE_KEY] = shadow_prior_coherence
        try:
            cr = validate_candidate(G, node, code, window=window)
        finally:
            # Restore original history
            if had_history:
                nd["glyph_history"] = original_history
            else:
                nd.pop("glyph_history", None)
            if had_debt:
                nd[U2_DEBT_KEY] = original_debt
            else:
                nd.pop(U2_DEBT_KEY, None)
            if had_prior_coherence:
                nd[PRIOR_COHERENCE_KEY] = original_prior_coherence
            else:
                nd.pop(PRIOR_COHERENCE_KEY, None)
        results.append(cr)
        # Accepted glyphs extend the shadow for subsequent steps
        if cr.allowed:
            shadow.append(code)
            shadow_debt = advance_debt(shadow_debt, code)
            shadow_prior_coherence = advance_prior_coherence(
                shadow_prior_coherence, code
            )

    return results


__all__ = [
    "GrammarViolation",
    "CandidateResult",
    "validate_candidate",
    "filter_candidates",
    "suggest_alternative",
    "enforce_grammar_on_glyph",
    "validate_sequence_incremental",
]
