"""
Circular Shell - Circular System Operations
Standalone version for cubesquare package.
"""

import json
from typing import Dict, Any
from ..circular import (
    CircularLoopDetector, CircularValidator,
    srl_distance, bounded_sqrt,
    get_k11_level, get_intrinsic_stability, is_intrinsically_stable,
    ILogicState
)


class CircularShell:
    """
    Circular Shell.

    Provides circular system operations:
    - Loop detection
    - SRL computation
    - K11 level queries
    - Intrinsic stability analysis
    """

    def __init__(self):
        """Initialize Circular shell."""
        self.detector = CircularLoopDetector()
        self.validator = CircularValidator()

    def status(self, as_json: bool = False) -> Dict[str, Any]:
        """Get Circular system status."""
        result = {
            'system': 'Circular Shell',
            'version': '1.0.0',
            'components': {
                'loop_detector': 'active',
                'srl_integration': 'active',
                'state_machine': 'active',
                'validator': 'active',
            },
            'k11_range': '[-11, +11]',
            'srl_formula': 't = sqrt(d)',
            'status': 'operational',
        }

        if as_json:
            return json.dumps(result, indent=2)
        return result

    def srl(self, distance: int, as_json: bool = False) -> Dict[str, Any]:
        """Compute SRL distance: t = sqrt(d)."""
        t = srl_distance(distance)

        result = {
            'distance': distance,
            'srl_time': t,
            'formula': 't = sqrt(d)',
            't_squared': t * t,
            'residual': distance - (t * t),
        }

        if as_json:
            return json.dumps(result, indent=2)
        return result

    def k11(self, x: int, y: int, z: int, as_json: bool = False) -> Dict[str, Any]:
        """Compute K11 level from coordinates."""
        k11 = get_k11_level(x, y, z)

        result = {
            'coords': (x, y, z),
            'k11_level': k11,
            'formula': '(x + y + z) % 23 - 11',
            'coord_sum': x + y + z,
        }

        if as_json:
            return json.dumps(result, indent=2)
        return result

    def intrinsic(self, hex_id: str, as_json: bool = False) -> Dict[str, Any]:
        """Get intrinsic stability of hex ID."""
        stability = get_intrinsic_stability(hex_id)

        # Convert ILogicState to string for JSON
        result = {
            'hex_id': stability['hex_id'],
            'coords': stability['coords'],
            'sphere_position': stability['sphere_position'],
            'k11_level': stability['k11_level'],
            'state': stability['state_name'],
            'wave_strength': stability['wave_strength'],
            'particle_strength': stability['particle_strength'],
            'polarity': stability['polarity'],
            'phi_norm': stability['phi_norm'],
            'is_stable': stability['is_stable'],
        }

        if as_json:
            return json.dumps(result, indent=2)
        return result

    def validate_srl(self, distance: int, as_json: bool = False) -> Dict[str, Any]:
        """Validate SRL distance."""
        validation = self.validator.validate_srl(distance)
        return validation.to_dict() if not as_json else json.dumps(validation.to_dict(), indent=2)

    def validate_all(self, as_json: bool = False) -> Dict[str, Any]:
        """Run all validation checks."""
        # Performance validation
        perf_results = self.validator.validate_performance()

        results = {
            'validation_count': len(perf_results),
            'passed': sum(1 for r in perf_results if r.passed),
            'results': [r.to_dict() for r in perf_results],
        }

        if as_json:
            return json.dumps(results, indent=2)
        return results

    def run(self, command: str, *args, as_json: bool = False) -> Any:
        """Run a Circular shell command."""
        commands = {
            'status': lambda: self.status(as_json),
            'srl': lambda: self.srl(int(args[0]), as_json) if args else {'error': 'Distance required'},
            'k11': lambda: self.k11(int(args[0]), int(args[1]), int(args[2]), as_json) if len(args) >= 3 else {'error': 'Three coordinates required (x y z)'},
            'intrinsic': lambda: self.intrinsic(args[0], as_json) if args else {'error': 'Hex ID required'},
            'validate': lambda: self.validate_all(as_json),
        }

        if command in commands:
            return commands[command]()
        else:
            return {'error': f'Unknown command: {command}', 'available': list(commands.keys())}
