"""Unified Interface - Generated by phi4, fixed to work with actual APIs.

The system designed this from the inside. This file combines:
- PhiShell for LLM reasoning (phi4)
- SphereMind for context tracking
- Swarm for agent dispatch
- flip() for coordinates
- EventBus for visualization events

Run: python -m cubesquare.unified
"""
import sys
from cubesquare.shells.phi import PhiShell, LayerLLMProcessor
from cubesquare.mcp.sphere_mind import SphereMind, NLMessage
from cubesquare import Swarm
from cubesquare.shells.flip import flip
from cubesquare.visual.events import get_event_bus, EventType, Event
from cubesquare.i_logic.states import ILogicState


class UnifiedInterface:
    """Unified natural language interface to Cubesquare.

    Designed by phi4 from inside the system.
    """

    def __init__(self, name: str = "unified"):
        self.phi_shell = PhiShell()
        self.processor = LayerLLMProcessor()
        self.sphere_mind = SphereMind(name=name)
        self.swarm = Swarm()
        self.event_bus = get_event_bus()

        print(f"Unified Interface initialized")
        print(f"  Sphere: {self.sphere_mind.sphere_id}")
        print(f"  LLM: phi4-mini {'(ready)' if self.processor.model_available else '(fallback)'}")
        print(f"  Agents: {self.swarm.agent_count}")
        print()

    def process(self, user_input: str) -> dict:
        """Process natural language input through the full system."""

        # 1. Flip input to get coordinates
        record = flip(user_input, 'text')

        # 2. Use phi4 to understand the input semantically
        understanding = self.processor.process_layer(user_input, 2)  # L2 Semantic

        # 3. Track context in SphereMind
        nl_message = NLMessage(content=user_input)
        self.sphere_mind.context.add_context(nl_message)

        # 4. Process through SphereMind dialogue
        dialogue_result = self.sphere_mind.dialogue(user_input)

        # 5. Route to swarm for agent dispatch
        dispatch_result = self.swarm.dispatch(user_input)

        # 6. Emit visualization events
        self.event_bus.emit(Event(
            type=EventType.FLIP,
            source_id=self.sphere_mind.sphere_id,
            data={
                'content': user_input[:50],
                'hex_id': record.hex_id,
                'basin': record.basin,
                'layer': record.layer,
            }
        ))

        self.event_bus.emit(Event(
            type=EventType.DISPATCH,
            source_id=self.sphere_mind.sphere_id,
            target_id=dispatch_result.agent.name,
            data={
                'task': user_input[:50],
                'agent': dispatch_result.agent.name,
                'outcome': dispatch_result.outcome_name,
            }
        ))

        # 7. Build response
        result = {
            'input': user_input,
            'coordinates': {
                'hex_id': record.hex_id,
                'basin': record.basin,
                'layer': record.layer,
                'i_state': record.i_state_name,
            },
            'understanding': {
                'semantic': understanding.llm_output[:200],
                'i_logic': understanding.i_logic_state,
                'method': understanding.processing_method,
            },
            'thinking': {
                'state': dialogue_result['thinking']['state'],
                'response': dialogue_result['thinking']['response'],
            },
            'dispatch': {
                'agent': dispatch_result.agent.name,
                'layer': dispatch_result.agent.layer,
                'outcome': dispatch_result.outcome_name,
                'resolved': dispatch_result.resolved,
            },
            'sphere': {
                'bounce': dialogue_result['sphere']['bounce'],
                'coupling': dialogue_result['sphere']['coupling'],
            }
        }

        return result

    def run(self) -> None:
        """Interactive REPL loop."""
        print("=" * 60)
        print("  CUBESQUARE UNIFIED INTERFACE")
        print("  Speak naturally. The system understands.")
        print("=" * 60)
        print()
        print("Commands: 'exit' to quit, 'reflect' to see state")
        print()

        while True:
            try:
                user_input = input("you > ").strip()

                if not user_input:
                    continue

                if user_input.lower() == "exit":
                    print("Saving state...")
                    self.sphere_mind.save()
                    break

                if user_input.lower() == "reflect":
                    print()
                    print(self.sphere_mind.reflect())
                    print()
                    continue

                # Process through the full system
                result = self.process(user_input)

                # Display result
                print()
                print(f"  [{result['coordinates']['hex_id']}] "
                      f"B{result['coordinates']['basin']}/L{result['coordinates']['layer']} "
                      f"({result['coordinates']['i_state']})")
                print()
                print(f"  Understanding: {result['understanding']['semantic'][:100]}...")
                print(f"  Method: {result['understanding']['method']}")
                print()
                print(f"  Agent: {result['dispatch']['agent']} (L{result['dispatch']['layer']})")
                print(f"  Outcome: {result['dispatch']['outcome']} "
                      f"({'resolved' if result['dispatch']['resolved'] else 'pending'})")
                print()
                print(f"  Thinking: {result['thinking']['state']}")
                print(f"  > {result['thinking']['response'][:80]}...")
                print()

            except (EOFError, KeyboardInterrupt):
                print("\nExiting...")
                self.sphere_mind.save()
                break


def main():
    """Entry point."""
    name = "unified"
    if len(sys.argv) > 1:
        name = sys.argv[1]

    interface = UnifiedInterface(name=name)
    interface.run()


if __name__ == "__main__":
    main()
