"""
Shared constants for CDNA layout verification.

WO-CDNA-LAYOUT-FIX-01: Centralize thresholds to prevent drift between tools.

Layout correctness is separate from fidelity:
- layout_ok: "Are we multiplying the right matrix with the right orientation?"
- fidelity_ok: "How close are values after quantization?"
"""

# Layout verification threshold
# A cosine >= this value with margin over second-best mode indicates correct layout
# This should be high enough to distinguish correct from wrong, but low enough
# to accommodate VQ quantization loss (~256 bins typically gives 0.999+ for correct layout)
LAYOUT_COSINE_THRESHOLD = 0.999

# Minimum margin between best and second-best mode to declare layout unambiguous
# If best_cosine - second_best_cosine < LAYOUT_MARGIN, layout is ambiguous
# 0.01 is plenty: correct mode ~0.9999, wrong mode ~0.0001 or negative
LAYOUT_MARGIN = 0.01

# Fidelity threshold for "good enough" quantization
# This is separate from layout - a tensor can have correct layout but poor fidelity
FIDELITY_COSINE_THRESHOLD = 0.98

# Fidelity threshold for "excellent" quantization (near-lossless)
FIDELITY_COSINE_EXCELLENT = 0.9999


def check_layout_ok(best_cosine: float, second_best_cosine: float = 0.0) -> bool:
    """
    Determine if layout is correct based on cosine values.

    Args:
        best_cosine: Cosine of best-matching operation mode
        second_best_cosine: Cosine of second-best mode (0 if only one mode tested)

    Returns:
        True if layout is unambiguously correct
    """
    # Must exceed minimum threshold
    if best_cosine < LAYOUT_COSINE_THRESHOLD:
        return False

    # Must have clear margin over second-best (if there is one)
    if second_best_cosine > 0 and (best_cosine - second_best_cosine) < LAYOUT_MARGIN:
        return False

    return True


def check_fidelity_ok(cosine: float) -> bool:
    """Check if fidelity meets minimum acceptable threshold."""
    return cosine >= FIDELITY_COSINE_THRESHOLD


def check_fidelity_excellent(cosine: float) -> bool:
    """Check if fidelity is near-lossless."""
    return cosine >= FIDELITY_COSINE_EXCELLENT
