function result = example_minimal_eeg_acquisition(device_name, channel_ids, sample_rate_hz, duration_seconds)
%EXAMPLE_MINIMAL_EEG_ACQUISITION Minimal real-device acquisition example.
%
% Usage:
%   example_minimal_eeg_acquisition()
%   example_minimal_eeg_acquisition('BA MINI 001')
%   result = example_minimal_eeg_acquisition('BA MINI 001', [], 250, 5.0)

project_root = fileparts(fileparts(mfilename('fullpath')));
addpath(fullfile(project_root, 'matlab'));

if nargin < 1
    device_name = '';
end
if nargin < 2
    channel_ids = [];
end
if nargin < 3 || isempty(sample_rate_hz)
    sample_rate_hz = 250;
end
if nargin < 4 || isempty(duration_seconds)
    duration_seconds = 5.0;
end

ba_setup();
init_info = ba_init();
cleanup_obj = onCleanup(@() safe_shutdown());
devices = ba_scan();
device_name = resolve_device_name(device_name, devices);

fprintf('Backend ready: %s, Core %s\n', ...
    init_info.backend_variant, init_info.core_version.text);
fprintf('Connecting to %s\n', device_name);

connect_result = ba_connect(device_name);
if ~connect_result.connected
    error('brainaccess:api', 'Connection failed: %s (%s)', ...
        connect_result.message, connect_result.status_name);
end

device_info = ba_get_device_info();
device_features = ba_get_device_features();
channel_ids = resolve_channel_ids(channel_ids, device_features);
fprintf('Connected: %s, serial %.0f, fw %s, hw %s\n', ...
    device_info.device_model.name, ...
    device_info.serial_number, ...
    device_info.firmware_version.text, ...
    device_info.hardware_version.text);
fprintf('Using %d EEG channels.\n', numel(channel_ids));

ba_configure_eeg(channel_ids, sample_rate_hz, 8, []);
ba_start_stream();
pause(2.0);

[data, meta] = ba_collect_seconds(duration_seconds, 250, true);

ba_stop_stream();
ba_disconnect();
ba_close();
clear cleanup_obj

plot_eeg(data, sample_rate_hz, device_name);

result = struct( ...
    'data', data, ...
    'device_features', device_features, ...
    'device_info', device_info, ...
    'device_name', device_name, ...
    'devices', devices, ...
    'init_info', init_info, ...
    'meta', meta);
end

function channel_ids = resolve_channel_ids(channel_ids, device_features)
if ~isempty(channel_ids)
    return;
end

electrode_count = double(device_features.electrode_count);
channel_ids = 0:(electrode_count - 1);
end

function device_name = resolve_device_name(device_name, devices)
if ~isempty(device_name)
    return;
end

device_name = getenv('BA_DEVICE_NAME');
if ~isempty(device_name)
    return;
end

if isempty(devices)
    error('brainaccess:api', ...
        'No devices found. Set BA_DEVICE_NAME or pass a device name explicitly.');
end

device_name = devices(1).name;
end

function plot_eeg(data, sample_rate_hz, device_name)
if isempty(data)
    error('brainaccess:api', 'No samples were collected.');
end

channel_count = size(data, 1);
sample_count = size(data, 2);
time_axis = (0:(sample_count - 1)) / sample_rate_hz;
centered = data - mean(data, 2);
spacing = max(std(centered, 0, 2));
if isempty(spacing) || spacing <= 0
    spacing = 1;
end
offsets = ((channel_count - 1):-1:0)' * spacing * 4;

figure('Name', 'BrainAccess Minimal Acquisition');
plot(time_axis, (centered + offsets)');
xlabel('Time (s)');
ylabel('Amplitude + offset');
title(sprintf('BrainAccess minimal acquisition: %s', device_name));
grid on;
end

function safe_shutdown()
status = ba_status();
if status.streaming
    ba_stop_stream();
end
if status.connected
    ba_disconnect();
end
if status.core_initialized || status.manager_present
    ba_close();
end
end
