#!/usr/bin/env python3
"""
Helix8 Program Definitions
==========================

Semantic codon map for the 8-position Helix slice.

Each position in "ABCDEFGH" represents a specific operation:
  Position 0 (A): Context gathering
  Position 1 (B): Embedding
  Position 2 (C): Projection up
  Position 3 (D): Layer normalization
  Position 4 (E): Bias + ReLU (ANCHOR GATE - reasoning pivot)
  Position 5 (F): W1 matmul
  Position 6 (G): Softmax
  Position 7 (H): Emit logits

The Position 4 gate is where FibPi3D anchors bend computation.
Gate mutations (E→G, E→A, E→B) steer toward math/code/json reasoning.
"""

from typing import Dict, List, Tuple

# ============================================================================
# HELIX8 PIPELINE DEFINITION
# ============================================================================

HELIX8_POSITIONS: List[str] = [
    "CTX_GATHER",      # 0 - A: Gather context from anchor
    "EMBED",           # 1 - B: Embed input into latent space
    "PROJ_UP",         # 2 - C: Project up to hidden dimension
    "LAYER_NORM",      # 3 - D: Layer normalization
    "BIAS_RELU",       # 4 - E: Bias + ReLU (GATE POSITION)
    "W1_MATMUL",       # 5 - F: First weight matrix multiply
    "SOFTMAX",         # 6 - G: Softmax activation
    "EMIT_LOGITS",     # 7 - H: Emit output logits
]

# Letter → Semantic operation mapping
LETTER_TO_OP: Dict[str, str] = {
    "A": "CTX_GATHER",
    "B": "EMBED",
    "C": "PROJ_UP",
    "D": "LAYER_NORM",
    "E": "BIAS_RELU",
    "F": "W1_MATMUL",
    "G": "SOFTMAX",
    "H": "EMIT_LOGITS",
}

# Reverse mapping: operation → letter
OP_TO_LETTER: Dict[str, str] = {v: k for k, v in LETTER_TO_OP.items()}

# ============================================================================
# BASE PROGRAM
# ============================================================================

# The canonical Helix8 base program
BASE_PROGRAM: str = "ABCDEFGH"

# Gate position (where anchor bends computation)
GATE_POSITION: int = 4

# ============================================================================
# GATE SEMANTIC DESCRIPTIONS
# ============================================================================

GATE_SEMANTICS: Dict[str, Dict[str, str]] = {
    "math_bias": {
        "mutation": "E→G",
        "program": "ABCDGFGH",
        "effect": "Replace BIAS_RELU with SOFTMAX at position 4",
        "reasoning": "Softmax at gate position increases math/logic precision",
    },
    "code_bias": {
        "mutation": "E→A",
        "program": "ABCDAFGH",
        "effect": "Replace BIAS_RELU with CTX_GATHER at position 4",
        "reasoning": "Re-gathering context at gate favors code pattern matching",
    },
    "json_bias": {
        "mutation": "E→B",
        "program": "ABCDBFGH",
        "effect": "Replace BIAS_RELU with EMBED at position 4",
        "reasoning": "Re-embedding at gate increases structural output fidelity",
    },
    "balanced": {
        "mutation": "E→E",
        "program": "ABCDEFGH",
        "effect": "No mutation (baseline)",
        "reasoning": "Standard pipeline without bias",
    },
}

# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================


def program_to_ops(program: str) -> List[str]:
    """
    Convert letter program to semantic operation list.

    Args:
        program: Letter program (e.g., "ABCDEFGH")

    Returns:
        List of operation names

    Example:
        >>> program_to_ops("ABCDGFGH")
        ['CTX_GATHER', 'EMBED', 'PROJ_UP', 'LAYER_NORM', 'SOFTMAX', 'W1_MATMUL', 'SOFTMAX', 'EMIT_LOGITS']
    """
    return [LETTER_TO_OP.get(c, f"UNKNOWN_{c}") for c in program]


def ops_to_program(ops: List[str]) -> str:
    """
    Convert semantic operation list to letter program.

    Args:
        ops: List of operation names

    Returns:
        Letter program string
    """
    return "".join(OP_TO_LETTER.get(op, "?") for op in ops)


def describe_program(program: str) -> Dict[str, any]:
    """
    Generate human-readable description of a Helix8 program.

    Args:
        program: Letter program (e.g., "ABCDGFGH")

    Returns:
        Dict with program analysis
    """
    ops = program_to_ops(program)
    gate_letter = program[GATE_POSITION] if len(program) > GATE_POSITION else "?"
    gate_op = LETTER_TO_OP.get(gate_letter, "UNKNOWN")

    # Find which gate policy this matches
    gate_policy = "custom"
    for policy_name, policy_info in GATE_SEMANTICS.items():
        if policy_info["program"] == program:
            gate_policy = policy_name
            break

    return {
        "program": program,
        "operations": ops,
        "gate_position": GATE_POSITION,
        "gate_letter": gate_letter,
        "gate_operation": gate_op,
        "gate_policy": gate_policy,
        "pipeline": [
            f"[{i}] {LETTER_TO_OP.get(c, '?')} ({c})" + (" ← GATE" if i == GATE_POSITION else "")
            for i, c in enumerate(program)
        ],
    }


def validate_program(program: str) -> Tuple[bool, str]:
    """
    Validate a Helix8 program string.

    Args:
        program: Letter program to validate

    Returns:
        Tuple of (is_valid, error_message)
    """
    if not program:
        return False, "Empty program"

    if len(program) != 8:
        return False, f"Program must be 8 characters, got {len(program)}"

    invalid_chars = [c for c in program if c not in LETTER_TO_OP]
    if invalid_chars:
        return False, f"Invalid characters: {invalid_chars}"

    return True, "Valid Helix8 program"


# ============================================================================
# DEMO / CLI
# ============================================================================


def _demo():
    """Demonstrate Helix8 program semantics."""
    print("=" * 70)
    print("HELIX8 PROGRAM SEMANTICS")
    print("=" * 70)
    print()

    print("PIPELINE POSITIONS:")
    for i, (letter, op) in enumerate(zip(BASE_PROGRAM, HELIX8_POSITIONS)):
        marker = " ← GATE (reasoning pivot)" if i == GATE_POSITION else ""
        print(f"  [{i}] {letter} = {op}{marker}")
    print()

    print("GATE MUTATIONS:")
    for policy_name, info in GATE_SEMANTICS.items():
        print(f"\n  {policy_name}:")
        print(f"    Mutation: {info['mutation']}")
        print(f"    Program:  {info['program']}")
        print(f"    Effect:   {info['effect']}")
    print()

    print("EXAMPLE ANALYSIS:")
    for prog in ["ABCDEFGH", "ABCDGFGH", "ABCDAFGH", "ABCDBFGH"]:
        desc = describe_program(prog)
        print(f"\n  Program: {prog}")
        print(f"    Gate: position {desc['gate_position']} = {desc['gate_operation']}")
        print(f"    Policy: {desc['gate_policy']}")

    print()
    print("=" * 70)


if __name__ == "__main__":
    _demo()
