from mpmath import mp, zeta, zetazero

# ============================================================================
# VERIFY CCT-FOUND "ZERO" USING MPMATH HIGH PRECISION
# ============================================================================

def verify_riemann_zero(t_candidate: float, dps: int = 50) -> dict:
    """
    Verify if t_candidate corresponds to a true Riemann zero.
    Uses mpmath with arbitrary precision.
    
    Args:
        t_candidate: imaginary part to test
        dps: decimal places of precision (default 50)
    
    Returns:
        Dictionary with verification results
    """
    with mp.workdps(dps):
        
        # Complex s on critical line
        s = mp.mpf('0.5') + 1j * mp.mpf(str(t_candidate))
        
        # Compute ζ(s) with high precision
        zeta_val = zeta(s)
        
        # Get magnitude and phase
        abs_zeta = abs(zeta_val)
        arg_zeta = mp.arg(zeta_val)
        
        result = {
            't_candidate': t_candidate,
            's': s,
            'zeta_value': zeta_val,
            '|ζ(s)|': abs_zeta,
            'arg(ζ(s))': arg_zeta,
            'is_zero': abs_zeta < 1e-10,
            'precision_used': dps
        }
        
        return result


def compare_with_known_zeros(t_candidate: float, n_nearest: int = 5) -> dict:
    """
    Compare t_candidate with the first n_nearest known Riemann zeros.
    """
    with mp.workdps(50):
        
        known_zeros = []
        for n in range(1, n_nearest + 1):
            zero_n = zetazero(n)
            known_zeros.append({
                'index': n,
                's': zero_n,
                't': mp.im(zero_n)
            })
        
        # Find closest known zero
        t_mp = mp.mpf(str(t_candidate))
        distances = [abs(z['t'] - t_mp) for z in known_zeros]
        
        closest_idx = distances.index(min(distances))
        closest_zero = known_zeros[closest_idx]
        distance = distances[closest_idx]
        
        return {
            'candidate': t_candidate,
            'closest_known': closest_zero,
            'distance': distance,
            'all_known_zeros': known_zeros,
            'is_known_zero': distance < 1e-6
        }


def plot_verification(t_candidate: float, known_t: float):
    """
    Visualize ζ(s) values near the candidate and known zero.
    """
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Grid near candidate
    t_range = np.linspace(t_candidate - 0.5, t_candidate + 0.5, 200)
    
    zeta_values = []
    with mp.workdps(30):
        for t_val in t_range:
            s = mp.mpf('0.5') + 1j * mp.mpf(str(t_val))
            zeta_values.append(float(abs(zeta(s))))
    
    # Plot
    fig, axes = plt.subplots(1, 2, figsize=(14, 5))
    
    # Left: ζ(s) magnitude near candidate
    ax1 = axes[0]
    ax1.plot(t_range, zeta_values, 'b-', linewidth=2)
    ax1.axhline(y=0, color='k', linestyle='-', alpha=0.3)
    ax1.axvline(x=t_candidate, color='r', linestyle='--', 
                label=f'CCT found: t={t_candidate:.6f}')
    ax1.scatter([t_candidate], [zeta_values[100]], c='red', s=100, zorder=5)
    ax1.set_xlabel('t (Im(s))')
    ax1.set_ylabel('|ζ(0.5 + it)|')
    ax1.set_title(f'ζ(s) Magnitude Near CCT Candidate t={t_candidate:.6f}')
    ax1.legend()
    ax1.set_yscale('log')
    
    # Right: ζ(s) magnitude near known first zero
    t_range2 = np.linspace(known_t - 0.5, known_t + 0.5, 200)
    zeta_values2 = []
    with mp.workdps(30):
        for t_val in t_range2:
            s = mp.mpf('0.5') + 1j * mp.mpf(str(t_val))
            zeta_values2.append(float(abs(zeta(s))))
    
    ax2 = axes[1]
    ax2.plot(t_range2, zeta_values2, 'g-', linewidth=2)
    ax2.axhline(y=0, color='k', linestyle='-', alpha=0.3)
    ax2.axvline(x=known_t, color='r', linestyle='--', 
                label=f'First zero: t={known_t:.6f}')
    ax2.scatter([known_t], [zeta_values2[100]], c='green', s=100, zorder=5)
    ax2.set_xlabel('t (Im(s))')
    ax2.set_ylabel('|ζ(0.5 + it)|')
    ax2.set_title(f'ζ(s) Magnitude Near First True Zero t={known_t:.6f}')
    ax2.legend()
    ax2.set_yscale('log')
    
    plt.tight_layout()
    plt.savefig('zeta_verification.png', dpi=150)
    plt.show()


# ============================================================================
# MAIN VERIFICATION
# ============================================================================

if __name__ == "__main__":
    
    print("="*80)
    print("CCT-FOUND ZERO VERIFICATION USING MPMATH")
    print("="*80)
    
    # CCT found value
    t_cct = 1.9368047241
    
    print(f"\n[1] Verifying CCT-found value: t = {t_cct}")
    print("-" * 60)
    
    result = verify_riemann_zero(t_cct, dps=50)
    
    print(f"  Candidate: s = {result['s']}")
    print(f"  ζ(s) = {result['zeta_value']}")
    print(f"  |ζ(s)| = {result['|ζ(s)|']}")
    print(f"  arg(ζ(s)) = {result['arg(ζ(s))']}")
    print(f"  Is Zero: {'✓ YES' if result['is_zero'] else '✗ NO'}")
    
    print(f"\n[2] Comparing with known Riemann zeros")
    print("-" * 60)
    
    comparison = compare_with_known_zeros(t_cct, n_nearest=10)
    
    print(f"  Closest known zero: #{comparison['closest_known']['index']}")
    print(f"    s = {comparison['closest_known']['s']}")
    print(f"    t = {comparison['closest_known']['t']}")
    print(f"  Distance from candidate: {comparison['distance']:.10f}")
    print(f"  Is known zero: {'✓ YES' if comparison['is_known_zero'] else '✗ NO'}")
    
    print(f"\n[3] First 10 known Riemann zeros:")
    print("-" * 60)
    for zero in comparison['all_known_zeros']:
        print(f"  #{zero['index']}: s = 0.5 + {float(zero['t']):.6f}i")
    
    print(f"\n[4] Analysis:")
    print("-" * 60)
    
    if result['is_zero']:
        print(f"  ✓ {t_cct} IS a Riemann zero!")
    else:
        print(f"  ✗ {t_cct} is NOT a Riemann zero")
        print(f"     |ζ(s)| = {result['|ζ(s)|']:.10f} (should be ~0)")
        print(f"     Difference from nearest zero: {comparison['distance']:.6f}")
        print(f"     This is a SPURIOUS ZERO from truncated proxy series.")
    
    print(f"\n[5] Visualizing comparison...")
    plot_verification(t_cct, float(comparison['closest_known']['t']))
    
    # Additional: Verify the TRUE first zero
    print(f"\n[6] Verification of TRUE first zero (14.134725) for comparison:")
    print("-" * 60)
    true_zero = verify_riemann_zero(14.134725, dps=50)
    print(f"  t = 14.134725")
    print(f"  ζ(s) = {true_zero['zeta_value']}")
    print(f"  |ζ(s)| = {true_zero['|ζ(s)|']}")
