#!/usr/bin/env python3
"""
IT³ Visualization Engine: Scientific Plots for Skeptics
Module: it3_visualization.py

Generates deterministic, publication-ready visualizations that directly 
address the main criticisms of the IT³ Topological Periodic Matrix.

Authors: Victor Logvinovich & Jean-Claude Perez
License: MIT
"""

import matplotlib.pyplot as plt
import numpy as np
from it3_chemistry_engine import (
    get_floor_capacity, 
    get_block_sequence, 
    get_quantum_passport,
    get_superheavy_properties
)

# ==============================================================================
# GLOBAL STYLE SETTINGS
# ==============================================================================
# Set a clean, academic style for all plots
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['axes.axisbelow'] = True  # Ensure grid is behind plots


def _apply_scientific_spines(ax):
    """Removes top and right spines for a cleaner, scientific look."""
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_linewidth(1.2)
    ax.spines['bottom'].set_linewidth(1.2)


# ==============================================================================
# 1. FLOOR CAPACITY MIRROR SYMMETRY PLOT
# ==============================================================================
def plot_floor_capacity_symmetry(save_path: str = "IT3_Floor_Capacity_Symmetry.png"):
    """
    Visualizes the perfect 86+86 topological mirror symmetry.
    This is the most critical plot: it shows that the sequence 
    2,8,8,18,18,32 is perfectly mirrored as 32,18,18,8,8,2.
    """
    Sn_values = list(range(12))
    capacities = [get_floor_capacity(Sn) for Sn in Sn_values]
    
    # Use constrained layout to automatically handle margins perfectly
    fig, ax = plt.subplots(figsize=(14, 7), layout='constrained')
    
    # Classical Vacuum (Sn 0-5) - Professional Blue
    ax.bar(Sn_values[:6], capacities[:6], color='#2B7BBA', alpha=0.85, edgecolor='black', linewidth=0.5, label='Classical Vacuum (Sn=0-5)')
    
    # Relativistic Vacuum (Sn 6-11) - Professional Crimson
    ax.bar(Sn_values[6:], capacities[6:], color='#C23B32', alpha=0.85, edgecolor='black', linewidth=0.5, label='Relativistic Vacuum (Sn=6-11)')
    
    # Mirror line at Sn=5.5
    ax.axvline(x=5.5, color='#333333', linestyle='--', linewidth=2.5, label='Relativistic Equator')
    
    # Annotations
    for i, cap in enumerate(capacities):
        ax.text(i, cap + 0.5, str(cap), ha='center', va='bottom', fontsize=13, fontweight='bold')
    
    ax.set_xlabel('Topological Floor (Sn)', fontsize=14, fontweight='bold')
    ax.set_ylabel('Element Capacity C(Sn)', fontsize=14, fontweight='bold')
    ax.set_title('IT³ Topological Mirror Symmetry: 86 + 86 = 172', fontsize=18, fontweight='black', pad=15)
    
    ax.legend(fontsize=12, frameon=True, shadow=True)
    ax.set_xticks(Sn_values)
    ax.set_xticklabels([f'Sn={i}' for i in Sn_values])
    ax.grid(axis='y', linestyle=':', alpha=0.6)
    
    _apply_scientific_spines(ax)
    
    plt.savefig(save_path, dpi=300, facecolor='white')
    plt.close()
    
    print(f"✅ Floor capacity symmetry plot saved to: {save_path}")


# ==============================================================================
# 2. X-SHAPED CROSSOVER DIAGRAM (Property Inversion)
# ==============================================================================
def plot_property_inversion(save_path: str = "IT3_Property_Inversion_Crossover.png"):
    """
    Visualizes the "X-shaped crossover" of chemical properties across 
    the relativistic equator. Shows how classical trends are inverted.
    """
    pairs = [
        ("Pb (82)", "Fl (114)", "Metal", "Quasi-Gas", "Phase State"),
        ("Rn (86)", "Og (118)", "Inert Gas", "Solid", "Phase State"),
        ("Hg (80)", "Cn (112)", "Liquid", "Gas", "Metallic Bond"),
        ("Au (79)", "Rg (111)", "Inert", "Reactive (+3,+5)", "Oxidation"),
        ("Cs (55)", "Fr (87)", "Peak Reactivity", "Trend Break", "s-block Reactivity"),
    ]
    
    fig, axes = plt.subplots(1, len(pairs), figsize=(20, 6), layout='constrained')
    
    for idx, (elem1, elem2, prop1, prop2, category) in enumerate(pairs):
        ax = axes[idx]
        
        # Classical (top)
        ax.barh([1], [1], color='#2B7BBA', alpha=0.85, edgecolor='none')
        ax.text(0.5, 1, prop1, ha='center', va='center', fontsize=11, fontweight='bold', color='white')
        
        # Relativistic (bottom)
        ax.barh([0], [1], color='#C23B32', alpha=0.85, edgecolor='none')
        ax.text(0.5, 0, prop2, ha='center', va='center', fontsize=11, fontweight='bold', color='white')
        
        # X-shaped arrow showing inversion
        ax.annotate('', xy=(0.8, 0.2), xytext=(0.2, 0.8), 
                    arrowprops=dict(arrowstyle='->,head_width=0.5,head_length=0.6', color='#111111', lw=2.5))
        ax.annotate('', xy=(0.2, 0.2), xytext=(0.8, 0.8), 
                    arrowprops=dict(arrowstyle='->,head_width=0.5,head_length=0.6', color='#111111', lw=2.5))
        
        ax.set_xlim(0, 1)
        ax.set_ylim(-0.5, 1.5)
        ax.set_title(f'{category}\n{elem1} → {elem2}', fontsize=13, fontweight='bold')
        ax.axis('off')
    
    plt.suptitle('IT³ Topological Inversion: X-Shaped Crossover of Chemical Properties', 
                 fontsize=18, fontweight='black')
    
    plt.savefig(save_path, dpi=300, facecolor='white')
    plt.close()
    
    print(f"✅ Property inversion crossover plot saved to: {save_path}")


# ==============================================================================
# 3. 3D TOPOLOGICAL MATRIX VISUALIZATION
# ==============================================================================
def plot_3d_topological_matrix(save_path: str = "IT3_3D_Matrix.png"):
    """
    3D visualization of all 172 elements distributed across topological floors.
    Shows the structural integrity of the IT³ framework.
    """
    fig = plt.figure(figsize=(16, 12), layout='constrained')
    ax = fig.add_subplot(111, projection='3d')
    
    # High-contrast color map for blocks
    block_colors = {
        's': '#F4B400',  # Warm Gold
        'p': '#8E44AD',  # Deep Purple
        'd': '#DB4437',  # Crimson Red
        'f': '#0F9D58',  # Vibrant Cyan/Green
    }
    
    # Generate all elements
    all_elements = [get_quantum_passport(Z) for Z in range(1, 173)]
    
    # Plot each element as a 3D point
    for elem in all_elements:
        Z = elem['Z']
        Sn = elem['Sn']
        block = elem['Lambda']
        mu = elem['mu']
        
        block_idx = {'s': 0, 'p': 1, 'd': 2, 'f': 3}.get(block, 0)
        
        color = block_colors.get(block, 'gray')
        ax.scatter(block_idx, mu, Sn, c=color, s=70, alpha=0.9, edgecolors='white', linewidth=0.5, depthshade=True)
    
    ax.set_xlabel('Block (s, p, d, f)', fontsize=12, fontweight='bold', labelpad=15)
    ax.set_ylabel('Spatial Node (μ)', fontsize=12, fontweight='bold', labelpad=15)
    ax.set_zlabel('Topological Floor (Sn)', fontsize=12, fontweight='bold', labelpad=15)
    ax.set_title('IT³ 3D Topological Matrix: All 172 Elements', fontsize=18, fontweight='black', pad=20)
    
    ax.set_xticks([0, 1, 2, 3])
    ax.set_xticklabels(['s', 'p', 'd', 'f'])
    ax.set_yticks(range(2, 15, 2))
    ax.set_zticks(range(12))
    
    # Adjust viewing angle for a better isometric perspective
    ax.view_init(elev=20, azim=-55)
    
    plt.savefig(save_path, dpi=300, facecolor='white')
    plt.close()
    
    print(f"✅ 3D topological matrix plot saved to: {save_path}")


# ==============================================================================
# 4. DENSITY PREDICTION COMPARISON
# ==============================================================================
def plot_density_comparison(save_path: str = "IT3_Density_Prediction.png"):
    """
    Compares IT³ density prediction for Z=120 (246 g/cm³) with 
    classical Dirac-Fock estimates (~40 g/cm³).
    """
    elements = ['Os (76)', 'Ir (77)', 'Pt (78)', 'Au (79)', 'Ubn (120)']
    densities_classical = [22.6, 22.56, 21.45, 19.3, 40]  # Classical estimates
    densities_it3 = [22.6, 22.56, 21.45, 19.3, 246.048]  # IT³ predictions
    
    x = np.arange(len(elements))
    width = 0.35
    
    fig, ax = plt.subplots(figsize=(12, 7), layout='constrained')
    
    bars1 = ax.bar(x - width/2, densities_classical, width, label='Classical (Dirac-Fock)', color='#2B7BBA', alpha=0.85, edgecolor='black', linewidth=0.5)
    bars2 = ax.bar(x + width/2, densities_it3, width, label='IT³ Prediction', color='#C23B32', alpha=0.85, edgecolor='black', linewidth=0.5)
    
    ax.set_ylabel('Density (g/cm³)', fontsize=14, fontweight='bold')
    ax.set_title('Density Prediction: Classical vs IT³ Framework', fontsize=18, fontweight='black', pad=15)
    ax.set_xticks(x)
    ax.set_xticklabels(elements, fontsize=12, fontweight='bold')
    
    ax.legend(fontsize=12, frameon=True, shadow=True, loc='upper left')
    ax.grid(axis='y', linestyle=':', alpha=0.6)
    _apply_scientific_spines(ax)
    
    # Add value labels on bars
    for bar in bars1:
        height = bar.get_height()
        ax.text(bar.get_x() + bar.get_width()/2., height + 3, f'{height:.1f}', ha='center', va='bottom', fontsize=10)
    
    for bar in bars2:
        height = bar.get_height()
        font_weight = 'black' if height > 100 else 'normal'
        color = '#C23B32' if height > 100 else 'black'
        ax.text(bar.get_x() + bar.get_width()/2., height + 3, f'{height:.1f}', ha='center', va='bottom', fontsize=10, fontweight=font_weight, color=color)
    
    # Set y-limit slightly higher to accommodate labels
    ax.set_ylim(0, 270)
    
    plt.savefig(save_path, dpi=300, facecolor='white')
    plt.close()
    
    print(f"✅ Density comparison plot saved to: {save_path}")


# ==============================================================================
# MAIN EXECUTION
# ==============================================================================
if __name__ == "__main__":
    print("Generating IT³ Scientific Visualizations...")
    print("=" * 60)
    
    plot_floor_capacity_symmetry()
    plot_property_inversion()
    plot_3d_topological_matrix()
    plot_density_comparison()
    
    print("=" * 60)
    print("✅ ALL VISUALIZATIONS GENERATED SUCCESSFULLY.")
    print("These high-resolution plots are ready for inclusion in your LaTeX article.")