% Map user input to numerical values using a switch statement
switch upper(target_country_str)
    case 'EA'
        target_country = 17;
    case 'CHN'
        target_country = 14;
    case 'USA'
        target_country = 69;
    case 'JPN'
        target_country = 24;
    otherwise
        % Use the default value (17) if the input is not recognized
        if isempty(target_country_str)
            target_country = 69;
        else
            fprintf('Unrecognized input "%s". Using the default value (69).\n', target_country_str);
        end
end


%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load data and select columns
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Get paths
currentFolder = pwd;
parentFolder = fileparts(currentFolder);
dataFilePath = fullfile(parentFolder, 'Data', 'liquidity_lines.xlsx');

% Read data
data = readtable(dataFilePath, 'Sheet', 'LiquidityLines');
countries = readtable(dataFilePath, 'Sheet', 'List');

% Filter bilateral if desired
if strcmpi(bilateral, 'yes')
    exclude = ismember(data.initiative, {'SAARC', 'BRICS_CRA', 'CMIM', 'ASEAN', 'Miyazawa'});
    data = data(~exclude, :);
end

% Filter small cap deals in desired
excludeDealsPath = fullfile(parentFolder, 'Data', 'Interim', 'cap_dealID.csv');
excludeDeals = readtable(excludeDealsPath);
data = data(~ismember(data.deal_ID, excludeDeals.deal_ID), :);

% Keep only needed columns
data = data(:, {'deal_ID', 'ISO_source', 'ISO_recipient', 'start_date', 'end_date'});
countries = countries(:, {'country_code', 'country_ID'});

% Save number of countries
N = height(countries);

% Merge in country IDs (source)
data = outerjoin(data, countries, 'LeftKeys', 'ISO_source', 'RightKeys', 'country_code', 'Type', 'left');
data.Properties.VariableNames{'country_ID'} = 'source_country_ID';
data.country_code = [];

% Merge in country IDs (recipient)
data = outerjoin(data, countries, 'LeftKeys', 'ISO_recipient', 'RightKeys', 'country_code', 'Type', 'left');
data.Properties.VariableNames{'country_ID'} = 'recipient_country_ID';
data.country_code = [];

% Drop ISO columns and reorder
data = data(:, {'deal_ID', 'source_country_ID', 'recipient_country_ID', 'start_date', 'end_date'});

% Convert dates
data.start_date = datetime(data.start_date, 'Format', 'dd.MM.yyyy');
data.end_date = datetime(data.end_date, 'Format', 'dd.MM.yyyy');

%% Compile active matrix (vectorized)

% Create year-month grid
years = 2000:2025;
months = 1:12;
[Y, M] = meshgrid(years, months);
Y = Y(:)'; M = M(:)';  % Flatten to row vectors
nMonths = length(Y);

% Precompute month start and end dates
monthStarts = datetime(Y, M, 1);
monthEnds = datetime(Y, M, eomday(Y, M));

% Get valid rows
validRows = ~isnat(data.start_date) & ~isnat(data.end_date);
startDates = data.start_date;
endDates = data.end_date;

% Vectorized active calculation: compare all deals against all months at once
% Result is nDeals x nMonths logical matrix
activeMatrix = (startDates <= monthEnds) & (endDates >= monthStarts);
activeMatrix(~validRows, :) = false;

% Convert to table columns
for t = 1:nMonths
    column_name = sprintf('Active_%d_%02d', Y(t), M(t));
    data.(column_name) = activeMatrix(:, t);
end

%% Reduce deals data to unique pairs (vectorized)

% Extract relevant columns
sourceID = data.source_country_ID;
recipientID = data.recipient_country_ID;
activeData = table2array(data(:, 6:end));

% Find unique pairs and their indices
[uniquePairs, ~, pairIdx] = unique([sourceID, recipientID], 'rows');
numPairs = size(uniquePairs, 1);

% Sum active columns by pair using accumarray
summedActive = zeros(numPairs, size(activeData, 2));
for col = 1:size(activeData, 2)
    summedActive(:, col) = accumarray(pairIdx, activeData(:, col), [], @sum);
end

% Build deals table
deals = array2table([uniquePairs, summedActive], ...
    'VariableNames', ['source_country_ID', 'recipient_country_ID', data.Properties.VariableNames(6:end)]);


%% Clean up workspace
tic
fprintf('Loaded %d unique pairs across %d countries\n', height(deals), N);
years = 2000:2025;

% Loop through each year
for yearID = 1:numel(years)
    year = years(yearID);
    
    % Initialize fresh for each year
    facilitatedPathsResults = {};
    
    % Loop through each month
    for month = 1:12
        fprintf('Processing %d-%02d\n', year, month);
        
        % Define the column name dynamically based on the year and month
        column_name = sprintf('Active_%d_%02d', year, month);
        
        % Subset the data based on the 'Active' column for the specific year and month
        condition = deals.(column_name) ~= 0;
        subsetData = deals(condition, :);
        
        % Initialize directed, unweighted shortest path calculation
        source0 = subsetData.source_country_ID;
        recipient0 = subsetData.recipient_country_ID;
        G = digraph(source0, recipient0);
        
        % for efficiency skip nodes not in graph
        activeNodes = unique([source0; recipient0]);
        
        % Precompute all distances once
        D = distances(G);
        
        % Loop through each country in the dataset
        for i = 1:max(data.source_country_ID)
            if ~ismember(i, activeNodes)
                continue
            end
            
            for j = 1:max(data.source_country_ID)
                if i == j
                    continue
                end
                
                if ~ismember(j, activeNodes)
                    continue
                end
                
                % Use precomputed distance
                d = D(j, i);
                if isinf(d)
                    continue
                end
                
                % find all possible paths
                all_paths = allpaths(G, j, i, 'MaxPathLength', d);
                if isempty(all_paths)
                    continue
                end
                
                % export paths
                for p = 1:length(all_paths)
                    path = all_paths{p};
                    path_str = strjoin(string(path), '-');
                    newRow = {year, month, j, i, path_str};
                    facilitatedPathsResults = [facilitatedPathsResults; newRow];
                end
            end
        end
    end
    
    % Save this year's results
    facilitatedPathsTable = cell2table(facilitatedPathsResults, ...
        'VariableNames', {'year', 'month', 'path_start', 'path_end', 'path_sequence'});
    
    saveFilePath = fullfile(parentFolder, 'Data', 'Interim', sprintf('shortest_paths_%d_cap.csv', year));
    
    if isfile(saveFilePath)
    delete(saveFilePath);
    end
    writetable(facilitatedPathsTable, saveFilePath);
    fprintf('Saved %d paths for year %d\n', size(facilitatedPathsResults, 1), year);
    
    % Clear memory
    clear facilitatedPathsResults facilitatedPathsTable
end

toc
fprintf('Done. Files saved separately for each year.\n');
