#!/usr/bin/env python3
"""
Computation 46 -- Option C refined-bridge fine-tuning and fidelity check
=========================================================================
Computation 45 showed that the two-monomial superposition bridge
    f(z_0, z_1) = (z_0 z_1)^m + alpha (z_0 z_1)^{m+1}
can achieve essentially exact L_comm closure (gap < 0.01) at all
weight classes k with appropriate (m(k), alpha(k)).

This script:
  (a) Refines (m, alpha) per k via finer alpha grid search.
  (b) Checks the fidelity: sup |f| / 1 (target = 1 for chi_S unitary).
  (c) Records the closure for k = 1..8 with sub-percent precision.

If the refined bridge gives gap < 1e-3 at all k with bounded
sup |f|, Option C is a fully closed L_comm construction.
"""
import math
import numpy as np


def F_sup(m, alpha, n_theta=40, n_phi=24):
    best = 0.0
    for i in range(n_theta + 1):
        theta = (i / n_theta) * (np.pi / 2)
        r = np.cos(theta)
        s = np.sin(theta)
        for j in range(n_phi + 1):
            phi0 = (j / n_phi) * (2 * np.pi)
            for k in range(n_phi + 1):
                phi1 = (k / n_phi) * (2 * np.pi)
                z0 = r * np.exp(1j * phi0)
                z1 = s * np.exp(1j * phi1)
                val = abs((z0 * z1)**m + alpha * (z0 * z1)**(m + 1))
                if val > best:
                    best = val
    return best


def M_sup(m, alpha, n_theta=30, n_phi=20):
    """Sup over partial B^2 of pointwise op-norm of M = sigma_a (J_a F),
    for F = (z_0 z_1)^m + alpha (z_0 z_1)^{m+1}.
    """
    best = 0.0
    for i in range(n_theta + 1):
        theta = (i / n_theta) * (np.pi / 2)
        r = np.cos(theta)
        s = np.sin(theta)
        for j in range(n_phi + 1):
            phi0 = (j / n_phi) * (2 * np.pi)
            for k in range(n_phi + 1):
                phi1 = (k / n_phi) * (2 * np.pi)
                z0 = r * np.exp(1j * phi0)
                z1 = s * np.exp(1j * phi1)
                # J_+ F = z_0 d/dz_1 F
                #       = m z_0 z_1^{m-1} z_0^m + alpha (m+1) z_0 z_1^m z_0^{m+1}
                #       = m z_0^{m+1} z_1^{m-1} + alpha (m+1) z_0^{m+2} z_1^m
                # J_- F (swap z_0, z_1 in argument and roles)
                # J_z F = 0 (symmetric in (p, q) since p = q for both monomials)
                if m >= 1:
                    jp = m * z0**(m+1) * z1**(m-1) + alpha * (m+1) * z0**(m+2) * z1**m
                    jm = m * z0**(m-1) * z1**(m+1) + alpha * (m+1) * z0**m * z1**(m+2)
                else:
                    jp = alpha * (m+1) * z0**(m+2) * z1**m
                    jm = alpha * (m+1) * z0**m * z1**(m+2)
                jz_val = 0.0 + 0.0j
                naive = 0.5 * (abs(jp)**2 + abs(jm)**2) + abs(jz_val)**2
                X = 0.5 * (abs(jp)**2 - abs(jm)**2)
                Y_imag = (jz_val.conjugate() * jm).imag
                Y_sq = 4.0 * Y_imag**2
                op2 = naive + math.sqrt(X**2 + Y_sq)
                val = math.sqrt(op2)
                if val > best:
                    best = val
    return best


def find_best(k, m_range, alpha_grid):
    target = 2 * math.sqrt(k)
    best = None
    for m in m_range:
        for alpha in alpha_grid:
            sF = F_sup(m, alpha, n_theta=24, n_phi=14)
            if sF < 1e-9:
                continue
            sM = M_sup(m, alpha, n_theta=20, n_phi=12)
            r = sM / sF
            gap = abs(r - target)
            if best is None or gap < best[0]:
                best = (gap, m, alpha, r, sF, sM)
    return best


def refine_alpha(k, m, alpha_start, scale=0.05, iters=4):
    """Bisection-like refinement of alpha around alpha_start."""
    target = 2 * math.sqrt(k)
    current_alpha = alpha_start
    current_step = scale
    best_gap = float('inf')
    best_result = None
    for it in range(iters):
        candidates = [current_alpha + current_step * d for d in [-2, -1, -0.5, 0, 0.5, 1, 2]]
        results = []
        for a in candidates:
            sF = F_sup(m, a, n_theta=40, n_phi=24)
            if sF < 1e-9:
                continue
            sM = M_sup(m, a, n_theta=30, n_phi=20)
            r = sM / sF
            gap = abs(r - target)
            results.append((gap, a, r, sF, sM))
        results.sort()
        if results[0][0] < best_gap:
            best_gap = results[0][0]
            best_result = (results[0][0], m, results[0][1], results[0][2], results[0][3], results[0][4])
            current_alpha = results[0][1]
        current_step /= 2.0
    return best_result


def main():
    print("=" * 90)
    print("  Computation 46  --  Refined symmetric bridge: fine-tuning and fidelity")
    print("=" * 90)
    print()
    print(f"  {'k':>3}  {'2 sqrt(k)':>11}  {'m':>3}  {'alpha':>10}  {'ratio':>10}"
          f"  {'gap':>10}  {'sup |F|':>10}")

    results_table = []
    for k in range(1, 9):
        # Coarse search first -- include POSITIVE alphas and wider range
        if k == 1:
            m_range = [1]
            alpha_grid = [0.0]
        else:
            m_range = list(range(max(1, int(math.sqrt(k)) - 2), int(math.sqrt(k)) + 5))
            alpha_grid = [-5.0 + 0.1 * i for i in range(101)]  # [-5, 5] step 0.1
        coarse = find_best(k, m_range, alpha_grid)
        if coarse is None:
            continue
        _, m_best, alpha_coarse, _, _, _ = coarse
        # Refine
        refined = refine_alpha(k, m_best, alpha_coarse, scale=0.05, iters=6)
        if refined is None:
            continue
        gap, m, alpha, ratio, sF, sM = refined
        results_table.append((k, m, alpha, ratio, gap, sF))
        target = 2 * math.sqrt(k)
        print(f"  {k:>3}  {target:>11.4f}  {m:>3}  {alpha:>10.5f}"
              f"  {ratio:>10.5f}  {gap:>10.5f}  {sF:>10.5f}")
    print()

    print("=" * 90)
    print("  Verdict")
    print("=" * 90)
    print()
    max_gap = max(r[4] for r in results_table)
    print(f"  Max closure gap across k = 1..{results_table[-1][0]}: {max_gap:.5f}")
    if max_gap < 1e-3:
        print(f"  => EXACT closure (gap below grid resolution)")
        print(f"  => Option C: refined symmetric bridge achieves L_comm closure UNIFORMLY")
        print(f"     across weight classes -- no cutoff transition discontinuity.")
    elif max_gap < 1e-2:
        print(f"  => essentially exact closure (gap < 1%)")
    else:
        print(f"  => non-trivial residual gap; refine grid resolution")
    print()
    print(f"  sup |F| range across k: [{min(r[5] for r in results_table):.4f}, "
          f"{max(r[5] for r in results_table):.4f}]")
    print(f"  Fidelity scale: bounded; bridge_final = T_f / sup |f| gives unit op-norm bridge.")


if __name__ == "__main__":
    main()
