#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Listening experiment — Day 1: Le Petit Prince.

Subjects listen to 26 chapters of the French audiobook (read by Xavier Perez)
presented sequentially, with rest periods between chapters.
"""

import os
from psychopy import logging

from exp_common import (
    HARDWARE_DEFAULTS,
    show_dialog,
    open_serial_port,
    setup_window,
    setup_logging,
    instruction_show,
    cross_show,
    sound_play,
    preload_sounds,
)

# ── Hardware config (override per site) ──────────────────────────────
config = {**HARDWARE_DEFAULTS, 'serial_port': 'COM5'}  # TOULOUSE

# ── Data paths ───────────────────────────────────────────────────────
data_path = '../data_experiments'
audio_dir = os.path.join(data_path, 'audio', 'lpp_fr')
log_dir = '../logs'

# ── Dialog box ───────────────────────────────────────────────────────
exp_info = show_dialog(
    exp_name='Listening - Le Petit Prince',
    exp_info={
        'Enter subject ID': 'subject_1',
        'ITI duration (s)': '2',
        'Baseline duration (s)': '30',
    },
    field_order=['Enter subject ID', 'ITI duration (s)', 'Baseline duration (s)'],
)

# ── Serial port ──────────────────────────────────────────────────────
mmbts, serial_port = open_serial_port(config['serial_port'])

# ── Window ───────────────────────────────────────────────────────────
win = setup_window(config)
frame_rate = config['frame_rate']

# ── Logging ──────────────────────────────────────────────────────────
subject_id = str(exp_info['Enter subject ID'])
time_string, log_file = setup_logging(subject_id, log_dir)

# ── Parameters (convert to frames) ──────────────────────────────────
tITI_frames = int(float(exp_info['ITI duration (s)']) * frame_rate)
tbaseline_frames = int(float(exp_info['Baseline duration (s)']) * frame_rate)

logging.data('Starting the experiment. Time and date: ' + time_string)
logging.data('Subject ID: ' + subject_id)
logging.data('ITI duration: ' + exp_info['ITI duration (s)'])
logging.data('Baseline duration: ' + exp_info['Baseline duration (s)'])

# ── Load audio (durations are read from the files, not hardcoded) ────
filenames = ['lpp-xavierperez_ch' + str(i) for i in range(1, 27)]
logging.data('file order: ' + '\n'.join(filenames))

sound_stims = preload_sounds(filenames, audio_dir)

# ── Experiment ───────────────────────────────────────────────────────
DESCRIPTION_TEXT = (
    "Bonjour !\n\nBienvenue dans cette experience. \n\n"
    "Vous allez écouter le livre Le petit prince."
    "\n\nPendant l'experience, bougez le moins possible et fixez la croix."
    "\n\nPressez 'Espace' pour continuer"
)

instruction_show(win, 'description', description_text=DESCRIPTION_TEXT)
instruction_show(win, 'baseline', int(2 * frame_rate))
cross_show(win, tbaseline_frames, config=config)
instruction_show(win, 'start')

for isent, filename in enumerate(filenames):
    if serial_port:
        mmbts.write(bytes(bytearray([isent % 254 + 1])))  # trigger codes 1-255
    sound_play(win, sound_stims[filename], filename, frame_rate, config=config)
    cross_show(win, tITI_frames, photodiode=0, config=config)
    instruction_show(win, 'rest')
    instruction_show(win, 'baseline', int(2 * frame_rate))
    cross_show(win, tITI_frames, photodiode=0, config=config)

instruction_show(win, 'baseline', int(2 * frame_rate))
cross_show(win, tbaseline_frames, config=config)
instruction_show(win, 'end', int(2 * frame_rate))

# ── Cleanup ──────────────────────────────────────────────────────────
if serial_port:
    mmbts.close()

win.close()
from psychopy import core
core.quit()
