%% A2_export_kaenzig_extentions.m
% Export selected extension dataset and results from Känzig replication run (after s06_figures6_8_9a_10_11.m).

fprintf('\n=== Exporting Känzig extended models ===\n');

%% Output folder
outDir = fullfile(fileparts(fileparts(mfilename('fullpath'))),'Data','kaenzig_exports');
if ~exist(outDir,'dir'), mkdir(outDir); end

%% Locate Kaenzig codes folder
thisFileDir = fileparts(mfilename('fullpath'));

rp = thisFileDir;
while ~isempty(rp) && ~exist(fullfile(rp,'1_Kaenzig_replication','codes'),'dir')
    rp2 = fileparts(rp);
    if strcmp(rp2,rp), rp = ''; else, rp = rp2; end
end

kaenzigDir = fullfile(rp,'1_Kaenzig_replication','codes');
if ~exist(kaenzigDir,'dir')
    error('Kaenzig codes folder not found: %s', kaenzigDir);
end

oldDir = pwd;

%% Run Kaenzig code (requires cd due to relative paths)
cd(kaenzigDir);

try
timeStr  = string(sampleDates(:));
base_raw = string(varNames_paper_base(:));
ext_raw  = string(varNames_paper_extended(:));
T        = size(data_base,1);

%% 1) Selected extensions dataset (time + selected series)
fprintf('-> Writing selected extensions dataset...\n');

sel_raw = { ...
    'Unemployment rate', ...
    'PCE', ...
    'Oil price expectations', ...
    'Inflation expectations (Michigan)', ...
    'VXO', ...
    'Geopolitical risk', ...
    'Fed funds rate', ...
    'Excess bond premium', ...
    'S\&P 500', ...
    'NEER Broad', ...
    'NEER Major', ...
    'Terms of trade'};

sel_tag = { ...
    'UnemploymentRate', ...
    'PCE', ...
    'OilPriceExpectations', ...
    'InflationExpectationsMichigan', ...
    'VXO', ...
    'GeopoliticalRisk', ...
    'FedFundsRate', ...
    'ExcessBondPremium', ...
    'SP500', ...
    'NEERBroad', ...
    'NEERMajor', ...
    'TermsOfTrade'};

X = nan(T,numel(sel_raw));
for j = 1:numel(sel_raw)
    t  = string(sel_raw{j});
    ib = find(base_raw==t,1);
    if ~isempty(ib)
        X(:,j) = data_base(:,ib);
    else
        ie = find(ext_raw==t,1);
        X(:,j) = data_extended(:,ie);
    end
end

Ts = array2table(X,'VariableNames',sel_tag);
Ts = addvars(Ts,timeStr,'Before',1,'NewVariableNames','time');
writetable(Ts, fullfile(outDir,'kaenzig_extensions_data.csv'));

%% 2) Export b1/U/timeNum for each selected extension (Känzig trimming)
fprintf('-> Running proxy VARs and exporting results...\n');

idx_ext = nan(numel(sel_raw),1);
for j = 1:numel(sel_raw)
    idx_ext(j) = find(ext_raw==string(sel_raw{j}),1);
end

for j = 1:numel(sel_raw)

    tag = sel_tag{j};
    fprintf('   [%2d/%2d] Processing %s...\n', j, numel(sel_tag), tag);

    id = idx_ext(j);

    startInd_extended = find(~isnan(data_extended(:,id)),1,'first');

    if startInd_extended > find(strcmp(sampleDatesRaw, smplStartProxy_base)) - p
        smplStartProxy = sampleDatesRaw(startInd_extended + p); %#ok<NASGU>
    else
        smplStartProxy = smplStartProxy_base; %#ok<NASGU>
    end

    data = [data_base, data_extended(:,id)]; %#ok<NASGU>
    varNames_paper = [varNames_paper_base, varNames_paper_extended(id)]; %#ok<NASGU>
    varNames = varNames_paper; %#ok<NASGU>

    data           = data(startInd_extended:smplEndInd,:); %#ok<NASGU>
    dataExo        = dataExo_base(startInd_extended:smplEndInd,:); %#ok<NASGU>
    sampleDates    = sampleDatesRaw(startInd_extended:smplEndInd,:); %#ok<NASGU>
    sampleDatesNum = sampleDatesRawNum(startInd_extended:smplEndInd,:); %#ok<NASGU>

    loadProxy;
    runProxyVAR;

    writematrix(b1(:), fullfile(outDir, ['kaenzig_extensions_' tag '_b1.csv']));
    writematrix(U,     fullfile(outDir, ['kaenzig_extensions_' tag '_U.csv']));
    writematrix(sampleDatesNum(p+1:end), ...
        fullfile(outDir, ['kaenzig_extensions_' tag '_timeNum.csv']));
end

catch ME
    cd(oldDir);
    rethrow(ME);
end

cd(oldDir);

fprintf('=== Extensions export finished successfully ===\n\n');
