# Reaction Time Color-Naming Study for PsychoPy (Direct Target Version)
# Compatibility revision: handles removed 'recStartTime' attribute in modern PsychoPy.
# RT filtering (225ms <= RT <= 750ms) for summary statistics.
# Designed for PsychoPy 2026.x (standalone or Python environment)
#
# Trial structure:
#   ITI:          uniform random 1.5-2.8 s
#   Target:       full-screen color (red, green, or blue), max 3.0 s or until vocal response onset
#
# Target generation:
#   Unobserved: Geiger count mapped 0->red, 1->green, 2->blue, 3->red...
#   Observed:   Python's cryptographically-seeded random generator.
#   The entire display changes to the selected color; no "0" is shown.
#
# 60 trials/session: 30 observed + 30 unobserved.

import csv
import os
import random
import statistics
import time
from pathlib import Path

import numpy as np
import serial
from psychopy import core, event, gui, logging, sound, visual
from psychopy.sound import microphone 

try:
    import psychtoolbox as ptb
except Exception:
    ptb = None


# =============================
# CONFIGURATION
# =============================

SERIAL_PORT = "COM3"          # CHANGE THIS to your Arduino port
BAUD_RATE = 115200
GEIGER_LINE_TIMEOUT = 3.0

N_TRIALS = 60
N_OBSERVED = 30
N_UNOBSERVED = 30

TARGET_DURATION = 3.0
ITI_MIN = 1.5
ITI_MAX = 2.8                 # Adjusted to 2.8 seconds

TARGET_COLORS = {
    "red": "red",
    "green": "green",
    "blue": "blue",
}

# Vocal-response detection.
MIC_SAMPLE_RATE = 48000
MIC_CHANNELS = 1
MIC_STREAM_BUFFER_SECS = 1.0
CALIBRATION_SECONDS = 2.0
VOICE_WINDOW_MS = 10.0
VOICE_MULTIPLIER = 3.0
MIN_VOICE_RMS = 0.005
MIN_RESPONSE_RT = 0.050
SAVE_AUDIO = True

# Output directory is created next to this script.
OUTPUT_ROOT = Path(__file__).resolve().parent / "data"


# =============================
# UTILITY FUNCTIONS
# =============================

def safe_float(value):
    try:
        return float(value)
    except Exception:
        return None

def choose_random_iti():
    # Draws a continuous random float between ITI_MIN (1.5) and ITI_MAX (2.8)
    return random.SystemRandom().uniform(ITI_MIN, ITI_MAX)

def make_conditions():
    conditions = ["observed"] * N_OBSERVED + ["unobserved"] * N_UNOBSERVED
    random.SystemRandom().shuffle(conditions)
    return conditions

def color_from_geiger(count):
    """Map Geiger integer counts cyclically: 0=red, 1=green, 2=blue, 3=red..."""
    mapping = ["red", "green", "blue"]
    return mapping[int(count) % 3]

def get_latest_geiger_line(ser):
    """Read all currently available complete serial lines and return the latest integer."""
    latest = None
    while True:
        waiting = getattr(ser, "in_waiting", 0)
        if waiting <= 0:
            break
        raw = ser.readline().decode("utf-8", errors="ignore").strip()
        if not raw:
            break
        value = safe_float(raw)
        if value is not None:
            latest = int(round(value))
    return latest

def wait_for_geiger_reading(ser, timeout=GEIGER_LINE_TIMEOUT):
    """Wait for one valid complete Geiger reading, retaining the newest reading."""
    latest = get_latest_geiger_line(ser)
    if latest is not None:
        return latest

    deadline = time.perf_counter() + timeout
    while time.perf_counter() < deadline:
        raw = ser.readline().decode("utf-8", errors="ignore").strip()
        if not raw:
            continue
        value = safe_float(raw)
        if value is not None:
            latest = int(round(value))
            drained = get_latest_geiger_line(ser)
            return drained if drained is not None else latest
    return None

def _recording_array(mic):
    """Return the current microphone buffer as a mono NumPy array."""
    raw = getattr(getattr(mic, "device", None), "recording", None)
    if raw is None:
        return np.empty(0, dtype=float)

    def extract_samples(item):
        if hasattr(item, "samples"):
            return np.asarray(item.samples)
        return np.asarray(item)

    if isinstance(raw, (list, tuple)):
        parts = []
        for item in raw:
            arr = extract_samples(item)
            if arr.size:
                parts.append(arr)
        if not parts:
            return np.empty(0, dtype=float)
        try:
            data = np.concatenate(parts, axis=0)
        except Exception:
            data = np.concatenate([a.reshape(-1) for a in parts])
    else:
        data = extract_samples(raw)

    if data.size == 0:
        return np.empty(0, dtype=float)
        
    if data.ndim == 1:
        return data.astype(float, copy=False)
        
    if data.shape[0] < data.shape[1] and data.shape[0] <= 8:
        return np.mean(data.astype(float), axis=0)
    else:
        return np.mean(data.astype(float), axis=1)

def _rms_windows(signal, window_samples):
    signal = np.asarray(signal, dtype=float)
    if signal.size < window_samples:
        return np.empty(0, dtype=float)
    n = signal.size // window_samples
    trimmed = signal[:n * window_samples].reshape(n, window_samples)
    return np.sqrt(np.mean(trimmed * trimmed, axis=1))

def calibrate_microphone(win, mic):
    """Record quiet-room baseline and compute an RMS voice threshold."""
    text = visual.TextStim(
        win,
        text="Microphone calibration\n\nPlease remain completely silent for 2 seconds.",
        color="white",
        height=0.06,
        wrapWidth=1.4,
    )
    text.draw()
    win.flip()

    mic.start(waitForStart=1)
    calibration_clock = core.Clock()
    while calibration_clock.getTime() < CALIBRATION_SECONDS:
        mic.device.poll()
        win.flip()
        if event.getKeys(keyList=["escape"]):
            mic.stop()
            raise KeyboardInterrupt
    mic.stop(blockUntilStopped=True)
    mic.device.poll()

    data = _recording_array(mic)
    sr = float(getattr(mic.device, "sampleRateHz", MIC_SAMPLE_RATE))
    window_samples = max(1, int(sr * VOICE_WINDOW_MS / 1000.0))
    levels = _rms_windows(data, window_samples)
    baseline = float(np.median(levels)) if levels.size else 0.0
    threshold = max(MIN_VOICE_RMS, baseline * VOICE_MULTIPLIER)

    text.text = (
        "Calibration complete.\n\n"
        f"Baseline RMS: {baseline:.6f}\n"
        f"Voice threshold RMS: {threshold:.6f}\n\n"
        "Press SPACE to begin."
    )
    text.draw()
    win.flip()
    event.waitKeys(keyList=["space"])
    return baseline, threshold, sr

def save_csv(path, rows, fieldnames):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

def write_summary(path, rows):
    # Filter bounds updated to 225ms - 750ms
    def is_valid_rt(row):
        if row["reaction_time_ms"] == "":
            return False
        try:
            rt = float(row["reaction_time_ms"])
            return 225 <= rt <= 750
        except ValueError:
            return False

    groups = {
        "observed": [r for r in rows if r["condition"] == "observed" and is_valid_rt(r)],
        "unobserved": [r for r in rows if r["condition"] == "unobserved" and is_valid_rt(r)],
    }

    summary_rows = []
    for name, subset in groups.items():
        values = [float(r["reaction_time_ms"]) for r in subset]
        summary_rows.append({
            "group": name,
            "n_valid": len(values),
            "mean_reaction_time_ms": f"{statistics.mean(values):.3f}" if values else "",
            "sd_reaction_time_ms": f"{statistics.stdev(values):.3f}" if len(values) > 1 else "",
        })

    save_csv(
        path,
        summary_rows,
        ["group", "n_valid", "mean_reaction_time_ms", "sd_reaction_time_ms"],
    )

    return summary_rows


# =============================
# MAIN EXPERIMENT
# =============================

def run_experiment():
    OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)

    exp_info = {"participant": "", "session": "1"}
    dlg = gui.DlgFromDict(exp_info, title="Reaction Time Color-Naming Study")
    if not dlg.OK:
        return

    participant = str(exp_info["participant"]).strip() or "P001"
    session = str(exp_info["session"]).strip() or "1"

    stamp = time.strftime("%Y%m%d_%H%M%S")
    session_dir = OUTPUT_ROOT / f"{participant}_session_{session}_{stamp}"
    session_dir.mkdir(parents=True, exist_ok=True)
    audio_dir = session_dir / "audio"
    if SAVE_AUDIO:
        audio_dir.mkdir(parents=True, exist_ok=True)

    trial_csv = session_dir / f"{participant}_session_{session}_trials.csv"
    summary_csv = session_dir / f"{participant}_session_{session}_summary.csv"

    win = visual.Window(
        fullscr=True,
        color="black",
        units="height",
        waitBlanking=True,
        checkTiming=True,
    )
    win.mouseVisible = False

    frame_rate = win.getActualFrameRate(nIdentical=20, nMaxFrames=100, nWarmUpFrames=20, threshold=1)
    if frame_rate is None:
        frame_rate = 60.0

    try:
        ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=0.25)
        time.sleep(2.0)
        ser.reset_input_buffer()
    except Exception as exc:
        win.close()
        raise RuntimeError(
            f"Could not open Arduino serial port {SERIAL_PORT}. "
            f"Change SERIAL_PORT at the top of the script. Original error: {exc}"
        )

    mic = microphone.Microphone(
        sampleRateHz=MIC_SAMPLE_RATE,
        channels=MIC_CHANNELS,
        streamBufferSecs=MIC_STREAM_BUFFER_SECS,
        maxRecordingSize=120000,
        audioRunMode=1,
        name="responseMic",
        recordingFolder=audio_dir,
    )

    baseline, voice_threshold, mic_sample_rate = calibrate_microphone(win, mic)

    instruction = visual.TextStim(
        win,
        text=(
            "Your screen will change from all black to a specfic color: red, blue, or green.\n\n"
            "Say the color name aloud as fast as you can.\n"
            "Say only the color name (red, green, or blue).\n\n"
            "The display will disappear after 3 seconds if no response is detected.\n\n"
            "Press SPACE to begin."
        ),
        color="white",
        height=0.055,
        wrapWidth=1.5,
    )
    instruction.draw()
    win.flip()
    event.waitKeys(keyList=["space"])

    # Full-screen target stimulus. This preserves the original microphone
    # detection loop while making the visual target cover the entire screen.
    target = visual.Rect(
        win,
        units="height",
        width=2.0,
        height=2.0,
        fillColor="black",
        lineColor="black",
    )

    conditions = make_conditions()
    sysrand = random.SystemRandom()

    global_clock = core.Clock()
    rows = []

    for trial_index in range(N_TRIALS):
        condition = conditions[trial_index]
        geiger_count = ""

        # Determine target color based on condition
        if condition == "unobserved":
            geiger_count_value = wait_for_geiger_reading(ser)
            if geiger_count_value is None:
                raise RuntimeError(
                    "No valid Geiger reading was received during an unobserved trial. "
                    "Check the Arduino and serial connection."
                )
            geiger_count = geiger_count_value
            target_color_name = color_from_geiger(geiger_count_value)
        else:
            target_color_name = sysrand.choice(list(TARGET_COLORS.keys()))

        iti = choose_random_iti()

        if trial_index > 0:
            iti_clock = core.Clock()
            while iti_clock.getTime() < iti:
                event.clearEvents(eventType="keyboard")
                core.wait(0.001)

        mic.start(waitForStart=1)
        mic_start_time = core.getTime()
        
        # Present the full-screen target.
        target.fillColor = TARGET_COLORS[target_color_name]
        target.lineColor = TARGET_COLORS[target_color_name]
        target.draw()
        target_onset_ptb = win.flip()
        if target_onset_ptb is None:
            target_onset_ptb = core.getTime()
            
        target_onset_global = global_clock.getTime()
        target_clock = core.Clock()
        target_clock.reset()

        response_rt = None
        audio_data_error = None
        last_seen_samples = 0
        voice_window_samples = max(1, int(mic_sample_rate * VOICE_WINDOW_MS / 1000.0))
        above_count = 0
        candidate_sample = None

        while target_clock.getTime() < TARGET_DURATION:
            try:
                mic.device.poll()
                data = _recording_array(mic)
                if data.size > last_seen_samples:
                    first_new = last_seen_samples
                    usable_end = data.size - ((data.size - first_new) % voice_window_samples)
                    if usable_end > first_new:
                        chunk = data[first_new:usable_end]
                        levels = _rms_windows(chunk, voice_window_samples)
                        
                        try:
                            rec_start = float(mic.device.recStartTime)
                        except Exception:
                            rec_start = mic_start_time
                            
                        for i, level in enumerate(levels):
                            sample_index = first_new + i * voice_window_samples
                            sample_abs_ptb = rec_start + sample_index / mic_sample_rate
                            rt = sample_abs_ptb - float(target_onset_ptb)
                            if rt < MIN_RESPONSE_RT:
                                continue
                            if rt > TARGET_DURATION:
                                break
                            if level >= voice_threshold:
                                if above_count == 0:
                                    candidate_sample = sample_index
                                above_count += 1
                                if above_count >= 2:
                                    response_rt = (
                                        rec_start + candidate_sample / mic_sample_rate
                                    ) - float(target_onset_ptb)
                                    break
                            else:
                                above_count = 0
                                candidate_sample = None
                    last_seen_samples = data.size
                if response_rt is not None:
                    # Immediately return the display to black after vocal response.
                    win.color = "black"
                    win.flip()
                    break
            except Exception as exc:
                audio_data_error = str(exc)
                break

            # Keep the target visible until a response is detected or 3 seconds elapse.
            target.draw()
            win.flip()

            if event.getKeys(keyList=["escape"]):
                mic.stop(blockUntilStopped=True)
                raise KeyboardInterrupt

        # Make sure the display is black between trials.
        win.color = "black"
        win.flip()

        mic.stop(blockUntilStopped=True)
        mic.device.poll()

        if audio_data_error:
            raise RuntimeError(
                "PsychoPy could record the microphone, but the live audio buffer "
                f"could not be read for onset detection: {audio_data_error}"
            )

        audio_filename = ""
        if SAVE_AUDIO:
            try:
                clip = mic.getRecording()
                audio_filename = str(audio_dir / f"trial_{trial_index + 1:03d}.wav")
                clip.save(audio_filename)
            except Exception as exc:
                logging.warning(f"Could not save audio for trial {trial_index + 1}: {exc}")
        event.clearEvents(eventType="keyboard")

        rows.append({
            "participant": participant,
            "session": session,
            "trial": trial_index + 1,
            "condition": condition,
            "target_color": target_color_name,
            "target_stimulus": "full_screen_color",
            "geiger_count": geiger_count,
            "iti_seconds": f"{iti:.6f}",
            "target_onset_global": f"{target_onset_global:.9f}",
            "reaction_time_ms": f"{response_rt * 1000.0:.3f}" if response_rt is not None else "",
            "response_detected": int(response_rt is not None),
            "microphone_baseline_rms": f"{baseline:.8f}",
            "voice_threshold_rms": f"{voice_threshold:.8f}",
            "audio_file": audio_filename,
            "psychopy_frame_rate_hz": f"{frame_rate:.6f}",
        })

    fieldnames = list(rows[0].keys()) if rows else []
    save_csv(trial_csv, rows, fieldnames)
    summary_rows = write_summary(summary_csv, rows)

    lines = ["Session complete", "", f"Trial data: {trial_csv.name}", f"Summary: {summary_csv.name}", ""]
    for item in summary_rows:
        lines.append(
            f"{item['group']}: n={item['n_valid']}, mean={item['mean_reaction_time_ms']} ms"
        )
    lines += ["", "Press SPACE to exit."]
    done = visual.TextStim(win, text="\n".join(lines), color="white", height=0.035, wrapWidth=1.55)
    done.draw()
    win.flip()
    event.waitKeys(keyList=["space"])

    ser.close()
    mic.close()
    win.close()
    core.quit()


if __name__ == "__main__":
    try:
        run_experiment()
    except KeyboardInterrupt:
        core.quit()
    except Exception as exc:
        logging.error(f"Experiment terminated: {exc}")
        raise