function csvFile = model2_awgn_link_retransmission(U, p, csvFile)
% Model 2:
% AWGN-Based Link-Layer Retransmission Model
%
% Inputs  = p + 9
% Output  = 1 (targetDelay)

if nargin < 2, p = 6; end
if nargin < 3 || isempty(csvFile)
    csvFile = 'model2_awgn_link_retransmission.csv';
end

N = numel(U.packetBytes);

packetDetected = zeros(N,1);
retryCount = zeros(N,1);
successFlag = zeros(N,1);
snrMarginDb = zeros(N,1);
txTimeMs = zeros(N,1);
delayMs = zeros(N,1);

ackMs = 0.044;
timeoutMs = 0.050;
nominalAccessMs = 0.15;

snrTable = [4 6 8 11 14 17 20 23 26 29 32 35];

for i = 1:N
    cfgHE = wlanHESUConfig;
    cfgHE.ChannelBandwidth = U.channelBandwidth;
    cfgHE.MCS = U.mcs(i);
    cfgHE.APEPLength = U.packetBytes(i);

    fs = wlanSampleRate(cfgHE);

    try
        psduBytes = getPSDULength(cfgHE);
    catch
        psduBytes = cfgHE.APEPLength;
    end

    txBits = randi([0 1], 8*psduBytes, 1);
    txWave = wlanWaveformGenerator(txBits, cfgHE);

    txTimeMs(i) = 1e3 * numel(txWave) / fs;
    snrMarginDb(i) = U.snrDb(i) - snrTable(U.mcs(i)+1);

    totalDelay = 0;
    ok = false;
    detAny = 0;

    for k = 1:(U.maxRetries+1)
        rxWave = awgn(txWave, U.snrDb(i), 'measured');

        pktOffset = wlanPacketDetect(rxWave, cfgHE.ChannelBandwidth);
        detected = ~isempty(pktOffset) && all(isfinite(pktOffset)) && (pktOffset >= 0);
        detAny = max(detAny, double(detected));

        phyOk = detected && (U.snrDb(i) >= snrTable(U.mcs(i)+1));

        totalDelay = totalDelay + nominalAccessMs + txTimeMs(i);

        if phyOk
            totalDelay = totalDelay + ackMs;
            ok = true;
            break;
        else
            totalDelay = totalDelay + timeoutMs;
            retryCount(i) = retryCount(i) + 1;
        end
    end

    packetDetected(i) = detAny;
    successFlag(i) = double(ok);
    delayMs(i) = totalDelay;
end

tbl = table( ...
    U.arrivalGapMs, ...
    U.packetBytes, ...
    U.snrDb, ...
    U.mcs, ...
    packetDetected, ...
    retryCount, ...
    successFlag, ...
    snrMarginDb, ...
    txTimeMs, ...
    delayMs, ...
    'VariableNames', { ...
    'arrivalGapMs','packetBytes','snrDb','mcs', ...
    'packetDetected','retryCount','successFlag','snrMarginDb','txTimeMs','delayMs'});

Treg = make_regression_table(tbl, 'delayMs', p, 1);
writetable(Treg, csvFile);

fprintf('Model 2 CSV saved: %s\n', csvFile);
fprintf('Model 2 inputs = %d, outputs = 1\n', width(Treg)-1);
end
