"""
Cubesquare Deep Diagnostic Tool

Orchestrates multiple shells to provide a semantic physics report for a token.
"""
import json
import logging
from dataclasses import dataclass, asdict
from typing import Dict, Any, Optional

from .shells.circular import CircularShell
from .shells.predict import PredictShell
from .shells.ecosystem import EcosystemShell
from .memory import CSTMemory

@dataclass
class TokenPhysicsProfile:
    hex_id: str
    basin: int
    layer: int
    
    # Circular Physics
    stability: str  # "STABLE" or "VOLATILE"
    k11_level: int
    wave_strength: float
    particle_strength: float
    
    # Predictive Behavior
    ilogic_state: str  # "DIRECT", "SPIRAL", etc.
    routing_outcome: str  # "TERMINATES", "EXPANDS", "LOOPS"
    
    # Ecosystem Role
    connectivity_role: str  # "HUB", "LEAF", "BRIDGE"
    degree: int
    category: str

class DeepExplainer:
    def __init__(self):
        self.circular = CircularShell()
        self.predict = PredictShell()
        self.ecosystem = EcosystemShell()
        # We don't need full memory for just hex analysis, but it helps for path resolution
        self.memory = CSTMemory() 

    def analyze_token(self, identifier: str) -> Dict[str, Any]:
        """
        Run a full diagnostic on a token.
        
        Args:
            identifier: Path string or Hex ID
            
        Returns:
            Dict containing the full profile and a human-readable summary.
        """
        # 1. Resolve Identity
        if identifier.startswith("0x") or len(identifier) == 8:
            hex_id = identifier.replace("0x", "")
            # Try to get more info if it exists in memory
            try:
                token = self.memory.get(hex_id)
                basin = token.basin
                layer = token.layer
            except:
                # If not in memory, we can still analyze the hex mathematically
                basin = 0 # Placeholder if unknown
                layer = 0
        else:
            # It's a path
            token = self.memory.read(identifier)
            if not token:
                return {"error": f"Token not found for path: {identifier}"}
            hex_id = token.hex_id
            basin = token.basin
            layer = token.layer

        # 2. Physics Analysis (Circular)
        intrinsic = self.circular.intrinsic(hex_id)
        is_stable = intrinsic.get('is_stable', False)
        stability = "STABLE" if is_stable else "VOLATILE"
        
        # 3. Behavior Analysis (Predict)
        # We simulate the token as an 'agent state' to see its I-Logic property
        # This is a heuristic: we map the hex's intrinsic state to an I-Logic state
        # For this v1, we'll infer it from the stability and polarity
        polarity = intrinsic.get('polarity', 0)
        if polarity > 0:
            ilogic_state = "DIRECT"
        elif polarity < 0:
            ilogic_state = "INVERSE"
        elif intrinsic.get('wave_strength', 0) > intrinsic.get('particle_strength', 0):
            ilogic_state = "SPIRAL"
        else:
            ilogic_state = "ABSORBED"
            
        # 4. Ecosystem Analysis
        # Check if it's a known node in the ecosystem graph
        degree = self.ecosystem.get_token_degree(hex_id)
        if degree > 5:
            role = "HUB"
        elif degree > 1:
            role = "BRIDGE"
        else:
            role = "LEAF"
            
        cat = self.ecosystem.get_category_tokens(basin) # This is wrong usage, need category from basin
        # We can get category from basin number directly
        from .shells.ecosystem import SemanticCategory
        category_enum = SemanticCategory.from_basin(basin) if basin else "UNKNOWN"

        # Synthesize Narrative
        narrative = (
            f"Token {hex_id} is a {stability} entity in the {category_enum} category (Basin {basin}).\n"
            f"Physically, it acts as a {ilogic_state} force with K11 level {intrinsic.get('k11_level')}.\n"
            f"In the ecosystem, it functions as a {role} (Degree: {degree})."
        )

        return {
            "hex_id": hex_id,
            "profile": {
                "stability": stability,
                "role": role,
                "ilogic_state": ilogic_state,
                "category": str(category_enum),
                "k11": intrinsic.get('k11_level'),
            },
            "narrative": narrative,
            "raw_data": {
                "intrinsic": intrinsic,
                "ecosystem_degree": degree
            }
        }

def explain(identifier: str) -> str:
    """Helper for CLI."""
    explainer = DeepExplainer()
    result = explainer.analyze_token(identifier)
    
    if "error" in result:
        return f"Error: {result['error']}"
        
    return f"""
CUBESQUARE DEEP DIAGNOSTIC
==========================
{result['narrative']}

---
DETAILS
Stability: {result['profile']['stability']}
Context:   {result['profile']['category']}
Role:      {result['profile']['role']}
Logic:     {result['profile']['ilogic_state']}
K11 Res:   {result['profile']['k11']}
"""
