#!/usr/bin/env python3
"""
reflex_core.py

Elevated from R&D (flowtorch_reflex_core.py).

Technical function:
- Rule-based pattern matching from compressed JSON models
- Deterministic symbolic inference without tensor operations

Notes:
- This is not "AI inference", it's rule-based pattern matching.
- Integrated as OPTIONAL lightweight reasoning engine.
"""

import json
import gzip
from pathlib import Path
from typing import List, Dict, Tuple, Optional


class ReflexEngine:
    """
    Lightweight rule-based inference engine.

    Loads compressed rule sets and performs simple pattern matching
    to generate responses without neural computation.
    """

    def __init__(self, rules: Optional[List[Dict]] = None, helixz_path: Optional[Path] = None):
        """
        Initialize reflex engine with either:
        - Direct rules list
        - Path to compressed .helixz file
        """
        if rules is not None:
            self.rules = rules
        elif helixz_path is not None:
            self.rules = self._load_helixz(helixz_path)
        else:
            self.rules = []

    def _load_helixz(self, path: Path) -> List[Dict]:
        """Load rules from gzipped JSON (.helixz format)"""
        with gzip.open(path, 'rt') as f:
            model = json.load(f)
        return model.get("rules", [])

    def plan_chain(self, prompt: str) -> List[Tuple[str, str]]:
        """
        Find all rules that match the prompt.

        Returns list of (response, trigger) tuples.
        """
        hits = []
        prompt_lower = prompt.lower()

        for rule in self.rules:
            trigger = rule.get("trigger", "").lower()
            if trigger and (prompt_lower in trigger or trigger in prompt_lower):
                response = rule.get("response", "")
                hits.append((response, trigger))

        return hits

    def infer(self, prompt: str) -> str:
        """
        Run inference: find matching rules and concatenate responses.
        """
        chain = self.plan_chain(prompt)

        if not chain:
            return "No chain found."

        # Concatenate all responses
        return " → ".join([resp for resp, _ in chain])

    def trace(self, prompt: str) -> Dict:
        """
        Run inference and return full trace for debugging.
        """
        chain = self.plan_chain(prompt)

        return {
            "prompt": prompt,
            "matches": len(chain),
            "chain": [
                {
                    "step": i + 1,
                    "trigger": trigger,
                    "response": response
                }
                for i, (response, trigger) in enumerate(chain)
            ],
            "output": " → ".join([resp for resp, _ in chain]) if chain else "No chain found."
        }
