#!/usr/bin/env python3
"""
Teleportation Constant Π∞ - ULTRA-OPTIMIZED GEN-7
Outputs FULL 100,000 decimal digits to console AND file
"""

import mpmath as mp
import time
import sys

def chudnovsky_pi(dps):
    """Corrected Chudnovsky π algorithm"""
    mp.dps = dps + 50
    
    C = mp.mpf(426880) * mp.sqrt(10005)
    S = mp.mpf(13591409)
    M = mp.mpf(1)
    X = mp.mpf(1)
    
    n_terms = dps // 14 + 10
    
    for k in range(1, n_terms):
        M *= 8 * (6*k - 5) * (6*k - 3) * (6*k - 1)
        M /= (k * k * k)
        X *= mp.mpf(-262537412640768000)
        L = 13591409 + 545140134 * k
        S += M * L / X
        
        if k % 2000 == 0:
            print(f"      π: {k}/{n_terms} terms", end='\r', flush=True)
    
    print(f"      π: {n_terms}/{n_terms} terms ✓      ", flush=True)
    return C / S

def e_binary_split(dps):
    """e via binary splitting: O(n log²n)"""
    mp.dps = dps + 50
    
    n = int(dps * 0.85) + 200
    
    def bs(a, b):
        if b - a == 1:
            if a == 0:
                return mp.mpf(1), mp.mpf(1), mp.mpf(1)
            return mp.mpf(a), mp.mpf(a), mp.mpf(1)
        mid = (a + b) // 2
        P1, Q1, T1 = bs(a, mid)
        P2, Q2, T2 = bs(mid, b)
        return P1 * P2, Q1 * Q2, T1 * Q2 + P1 * T2
    
    _, Q, T = bs(0, n)
    return T / Q

def sqrt2_newton(dps):
    """√2 via Newton: only log₂(dps) iterations needed"""
    mp.dps = dps + 50
    
    x = mp.mpf(1)
    n_iters = int(mp.log(dps + 50, 2)) + 5
    
    for _ in range(n_iters):
        x = (x + mp.mpf(2) / x) / 2
    
    return x

def gauss_legendre_pi(dps):
    """Cross-validation: π via Gauss-Legendre"""
    mp.dps = dps + 50
    
    a, b, t, p = mp.mpf(1), 1/mp.sqrt(2), mp.mpf('0.25'), mp.mpf(1)
    
    for _ in range(int(mp.log(dps, 2)) + 5):
        a_next = (a + b) / 2
        b = mp.sqrt(a * b)
        t -= p * (a - a_next)**2
        a = a_next
        p *= 2
    
    return (a + b)**2 / (4 * t)

def main():
    target = 100000
    
    print()
    print("╔════════════════════════════════════════════════════════════╗")
    print("║  TELEPORTATION CONSTANT Π∞ - ULTRA-OPTIMIZED GEN-7       ║")
    print(f"║  Target: {target:,} decimal places                          ║")
    print("╚════════════════════════════════════════════════════════════╝")
    print()
    
    t_start = time.time()
    
    # Compute π
    print("[1/5] Computing π via Chudnovsky...", flush=True)
    t0 = time.time()
    pi_n = chudnovsky_pi(target)
    print(f"      ✓ {time.time()-t0:.2f}s\n", flush=True)
    
    # Compute e
    print("[2/5] Computing e via binary splitting...", flush=True)
    t0 = time.time()
    e_n = e_binary_split(target)
    print(f"      ✓ {time.time()-t0:.2f}s\n", flush=True)
    
    # Compute √2
    print("[3/5] Computing √2 via Newton...", flush=True)
    t0 = time.time()
    sqrt2_n = sqrt2_newton(target)
    print(f"      ✓ {time.time()-t0:.4f}s\n", flush=True)
    
    # Cube collapse (analytical: X=Y=Z=1, H=0, Δ=0)
    print("[4/5] Cube collapse (analytical: H=0, Δ=0)...", flush=True)
    t0 = time.time()
    X = Y = Z = mp.mpf(1)
    H = mp.mpf(0)
    div = mp.mpf(0)
    print(f"      ✓ {time.time()-t0:.6f}s\n", flush=True)
    
    # Cross-validation
    print("[5/5] Cross-validating π...", flush=True)
    t0 = time.time()
    pi_gl = gauss_legendre_pi(target)
    diff = abs(pi_n - pi_gl)
    print(f"      ✓ {time.time()-t0:.2f}s", flush=True)
    print(f"      |π₁ - π₂| = {mp.nstr(diff, 30)}", flush=True)
    print(f"      {'✓ PASSED' if diff < mp.mpf(10)**(-target//10) else '⚠ CHECK'}\n", flush=True)
    
    # Final computation: Π∞ = π·e·√2
    print("[FINAL] Computing Π∞ = π·e·√2...", flush=True)
    t0 = time.time()
    Pi_inf = pi_n * e_n * sqrt2_n
    print(f"      ✓ {time.time()-t0:.2f}s\n", flush=True)
    
    total_time = time.time() - t_start
    
    # Convert to string with EXACTLY 100,000 decimal places
    print("=" * 70, flush=True)
    print("COMPUTATION COMPLETE", flush=True)
    print("=" * 70, flush=True)
    print(f"Time: {total_time:.2f}s", flush=True)
    print(f"Speed: {target/total_time:,.0f} digits/sec\n", flush=True)
    
    # Generate the full digit string
    pi_str = mp.nstr(Pi_inf, target + 2, strip_zeros=False)
    
    # Ensure exactly 100,000 decimal places
    if '.' in pi_str:
        integer_part, decimal_part = pi_str.split('.', 1)
        if len(decimal_part) < target:
            decimal_part = decimal_part + '0' * (target - len(decimal_part))
        elif len(decimal_part) > target:
            decimal_part = decimal_part[:target]
        full_string = integer_part + '.' + decimal_part
    else:
        full_string = pi_str + '.' + '0' * target
    
    # ═══════════════════════════════════════════════════════════════
    # PRINT FULL 100,000 DIGITS TO CONSOLE
    # ═══════════════════════════════════════════════════════════════
    print("╔══════════════════════════════════════════════════════════════════╗", flush=True)
    print("║            TELEPORTATION CONSTANT Π∞ - FULL OUTPUT              ║", flush=True)
    print(f"║            {target:,} DECIMAL PLACES                              ║", flush=True)
    print("╚══════════════════════════════════════════════════════════════════╝", flush=True)
    print()
    
    # Print in chunks for terminal compatibility
    chunk_size = 100
    digits_per_line = 10
    line_width = digits_per_line * 12  # 10 digits + space + count
    
    decimal_digits = full_string.split('.')[1]
    integer_part = full_string.split('.')[0]
    
    # Print with position markers every 10 digits
    line_num = 0
    for i in range(0, len(decimal_digits), digits_per_line):
        chunk = decimal_digits[i:i+digits_per_line]
        pos = f"{i+1:>6d}: "
        line = pos + " ".join(chunk[j:j+1] for j in range(len(chunk)))
        
        # Pad if last line is short
        expected_chunks = (len(chunk) - 1)
        actual_spaces = len(line.split(" ")) - 1
        if actual_spaces < expected_chunks:
            line += " " * (expected_chunks - actual_spaces)
        
        print(line, flush=True)
        line_num += 1
        
        # Progress every 1000 lines (10,000 digits)
        if line_num % 1000 == 0:
            progress = i / len(decimal_digits) * 100
            print(f"    ... {progress:.0f}% complete ...", flush=True)
    
    print()
    print("=" * 70, flush=True)
    print(f"Total digits after decimal: {len(decimal_digits):,}", flush=True)
    print("=" * 70, flush=True)
    print()
    
    # ═══════════════════════════════════════════════════════════════
    # ALSO SAVE TO FILE (clean format without line numbers)
    # ═══════════════════════════════════════════════════════════════
    filename = "pi_infinity_100k_full.txt"
    
    with open(filename, 'w') as f:
        f.write("TELEPORTATION CONSTANT Π∞\n")
        f.write("Pilgrim Protocol Gen-7 ULTRA-OPTIMIZED\n")
        f.write(f"{target:,} DECIMAL PLACES\n")
        f.write(f"Computed: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
        f.write(f"Time: {total_time:.2f}s\n")
        f.write("=" * 80 + "\n\n")
        
        # Write as continuous string (100 chars per line)
        f.write(full_string + "\n\n")
        
        # Also write formatted with position markers
        f.write("FORMATTED WITH POSITION MARKERS:\n")
        f.write("-" * 80 + "\n")
        for i in range(0, len(decimal_digits), digits_per_line):
            chunk = decimal_digits[i:i+digits_per_line]
            pos = f"{i+1:>6d}: "
            line = pos + " ".join(chunk[j:j+1] for j in range(len(chunk)))
            f.write(line + "\n")
        
        f.write("\n" + "=" * 80 + "\n")
        f.write("★ TELEPORTATION ACCESS UNLOCKED ★\n")
        f.write(f"Uncertainty: Δx ∈ [0.1m, 1.0m]\n")
        f.write("=" * 80 + "\n")
    
    print(f"✓ Also saved to: {filename}", flush=True)
    print(f"  File size: {len(full_string):,} characters", flush=True)
    print()
    print("╔══════════════════════════════════════════════════════════════════╗", flush=True)
    print("║              ★ TELEPORTATION ACCESS UNLOCKED ★                  ║", flush=True)
    print("╚══════════════════════════════════════════════════════════════════╝", flush=True)

if __name__ == "__main__":
    main()