from QNS.components import *
from QNS.channels import *
from QNS.StateEvaluation import *
import numpy as np

# --- Detector parameters:
DETECTOR_PARAMETERS = dict(
    dead_time=40e-9,
    jitter=55e-12,
    mean_response_time=2e-9,
    coupling_eff=0.95,
    dark_count_rate=100,
    det_eff=0.90
)

# --- Channel parameters:
FIBER_CHANNEL_PARAMETERS = dict(
    length=1,
    alpha=0.2,
    n_core=1.5
)

# --- CHSH analyzer settings (optimal Bell angles, degrees) ---
ALICE_SETTING_1 = 0.0     # commonly labeled "a"
ALICE_SETTING_2 = 45.0    # commonly labeled "a'"
BOB_SETTING_1   = 22.5    # commonly labeled "b"
BOB_SETTING_2   = 67.5    # commonly labeled "b'"

RUNTIME_SECONDS = 0.05

measurement_configurations = [
    ("correlation_alice1_bob1", ALICE_SETTING_1, BOB_SETTING_1),
    ("correlation_alice1_bob2", ALICE_SETTING_1, BOB_SETTING_2),
    ("correlation_alice2_bob1", ALICE_SETTING_2, BOB_SETTING_1),
    ("correlation_alice2_bob2", ALICE_SETTING_2, BOB_SETTING_2),
]

correlation_results = {}

for config_label, alice_angle_deg, bob_angle_deg in measurement_configurations:

    # Half-wave plate rotates polarization by 2x its angle, so divide requested
    # analyzer angle by 2 to get the physical HWP setting
    alice_hwp_angle = (alice_angle_deg / 2.0) % 360
    bob_hwp_angle = (-bob_angle_deg / 2.0) % 360

    tl = Timeline()
    state_manager = StateManager("StateManager")

    entangled_source = EntangledPhotonSource("EntangledSource", tl.env, state_manager)

    alice_half_waveplate = HalfWavePlate(
        "AliceHalfWavePlate", tl.env, state_manager, angle=alice_hwp_angle
    )
    alice_polarizing_splitter = PolarisingBeamSplitter(
        "AlicePolarizingBeamSplitter", tl.env, state_manager
    )
    alice_detector_horizontal = Detector(
        "AliceDetectorHorizontal", tl.env, state_manager, **DETECTOR_PARAMETERS
    )
    alice_detector_vertical = Detector(
        "AliceDetectorVertical", tl.env, state_manager, **DETECTOR_PARAMETERS
    )

    bob_half_waveplate = HalfWavePlate(
        "BobHalfWavePlate", tl.env, state_manager, angle=bob_hwp_angle
    )
    bob_polarizing_splitter = PolarisingBeamSplitter(
        "BobPolarizingBeamSplitter", tl.env, state_manager
    )
    bob_detector_horizontal = Detector(
        "BobDetectorHorizontal", tl.env, state_manager, **DETECTOR_PARAMETERS
    )
    bob_detector_vertical = Detector(
        "BobDetectorVertical", tl.env, state_manager, **DETECTOR_PARAMETERS
    )

    channel_links = [
        (entangled_source, 0, alice_half_waveplate, 0),
        (entangled_source, 1, bob_half_waveplate, 0),
        (alice_half_waveplate, 0, alice_polarizing_splitter, 0),
        (bob_half_waveplate, 0, bob_polarizing_splitter, 0),
        (alice_polarizing_splitter, 0, alice_detector_horizontal, 0),
        (alice_polarizing_splitter, 1, alice_detector_vertical, 0),
        (bob_polarizing_splitter, 0, bob_detector_horizontal, 0),
        (bob_polarizing_splitter, 1, bob_detector_vertical, 0),
    ]

    for link_index, (source_node, source_port, dest_node, dest_port) in enumerate(channel_links):
        channel_parameters = dict(FIBER_CHANNEL_PARAMETERS)
        if source_node is not entangled_source:
            channel_parameters['length'] = 0  # internal free-space optics, not the fiber run
        channel = QuantumOpticalChannel(
            f"OpticalChannel_{link_index}", tl.env, **channel_parameters
        )
        channel.connect_channel([source_node, source_port], [dest_node, dest_port])

    detector_list = [
        alice_detector_horizontal, alice_detector_vertical,
        bob_detector_horizontal, bob_detector_vertical
    ]

    run_result = tl.run(
        runtime=RUNTIME_SECONDS,
        laser_list=[entangled_source],
        detector_list=detector_list
        # coincidence_window left as None -> ground-truth same-pulse pairing
    )

    print("\n" + "="*70)
    print("PHOTON NUMBER DISTRIBUTION")
    print("="*70)

    for n_pairs, count in sorted(entangled_source.my_dict.items(), key=lambda x: int(x[0])):
        n_pairs = int(n_pairs)
        total_photons = 2 * n_pairs

        print(
            f"{n_pairs} pair(s)  |  "
            f"{n_pairs} signal + {n_pairs} idler  |  "
            f"{total_photons} total photons  |  "
            f"{count} events"
        )

    coincidence_counts = run_result['coincidences']
    alice_h_id, alice_v_id = alice_detector_horizontal.get_id(), alice_detector_vertical.get_id()
    bob_h_id, bob_v_id = bob_detector_horizontal.get_id(), bob_detector_vertical.get_id()

    coincidence_by_outcome = {
        "horizontal_horizontal": coincidence_counts[(alice_h_id, bob_h_id)],
        "horizontal_vertical":   coincidence_counts[(alice_h_id, bob_v_id)],
        "vertical_horizontal":   coincidence_counts[(alice_v_id, bob_h_id)],
        "vertical_vertical":     coincidence_counts[(alice_v_id, bob_v_id)],
    }

    total_coincidences = sum(coincidence_by_outcome.values())

    correlation_value = (
        (coincidence_by_outcome["horizontal_horizontal"]
         + coincidence_by_outcome["vertical_vertical"]
         - coincidence_by_outcome["horizontal_vertical"]
         - coincidence_by_outcome["vertical_horizontal"])
        / total_coincidences
        if total_coincidences > 0 else 0.0
    )
    correlation_results[config_label] = correlation_value

    print(f"{config_label}: Alice={alice_angle_deg:+.1f} deg, Bob={bob_angle_deg:+.1f} deg | "
          f"HH={coincidence_by_outcome['horizontal_horizontal']} "
          f"HV={coincidence_by_outcome['horizontal_vertical']} "
          f"VH={coincidence_by_outcome['vertical_horizontal']} "
          f"VV={coincidence_by_outcome['vertical_vertical']} "
          f"total={total_coincidences} | E={correlation_value:+.6f}")

chsh_statistic = (
    correlation_results["correlation_alice1_bob1"]
    - correlation_results["correlation_alice1_bob2"]
    + correlation_results["correlation_alice2_bob1"]
    + correlation_results["correlation_alice2_bob2"]
)

print(f"\nCHSH statistic S = {chsh_statistic:+.6f}")
print(f"|S| = {abs(chsh_statistic):.6f}")
print("Bell-CHSH inequality violated." if abs(chsh_statistic) > 2 else "No Bell-CHSH violation.")
