% 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 the current folder
currentFolder = pwd;

% Get the parent folder (one level up)
parentFolder = fileparts(currentFolder);

% Construct the full path to the data files
dataFilePath = fullfile(parentFolder, 'Data', 'liquidity_lines.xlsx');

% Read the data from the specified sheets
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), :);

% Specify the column names to keep for data
columns_to_keep_data = {'deal_ID', 'ISO_source', 'ISO_recipient', 'start_date', 'end_date'};

% Select the specified columns in data
data = data(:, columns_to_keep_data);

% Specify the column names to keep for countries
columns_to_keep_countries = {'country_code', 'country_ID'};

% Select the specified columns in countries
countries = countries(:, columns_to_keep_countries);

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

%Define time range (number of months) - currently: 2000 - 2025 = 26 years
T = 12*26;

%Merge in country IDs 
countries.Properties.VariableNames{'country_code'} = 'ISO_source';
data = join(data, countries, 'Keys', {'ISO_source'});
data.Properties.VariableNames{'country_ID'} = 'source_country_ID';

countries.Properties.VariableNames{'ISO_source'} = 'ISO_recipient';
data = join(data, countries, 'Keys', {'ISO_recipient'});
data.Properties.VariableNames{'country_ID'} = 'recipient_country_ID';

%Drop unnecessary columns 
data.ISO_source = [];
data.ISO_recipient = [];

%Reorder columns
newOrder = [1, 4, 5, 2, 3, 6:width(data)];
data = data(:, newOrder);
%% Compile active matrix
% Convert dates to datetime objects
data.start_date = datetime(data.start_date, 'Format', 'dd.MM.yyyy');
data.end_date = datetime(data.end_date, 'Format', 'dd.MM.yyyy');

% Initialize 'Active' columns for each month
for year = 2000:2025
    for month = 1:12
        column_name = sprintf('Active_%d_%02d', year, month);
        data.(column_name) = NaN(height(data), 1);
        
        % Find valid rows for the specific year and month
        validRows = ~isnat(data.start_date) & ~isnat(data.end_date);
        
        % Update 'Active' column based on conditions
        data.(column_name)(validRows) = ...
            (data.start_date(validRows) <= datetime(year, month, eomday(year, month))) & ...
            (data.end_date(validRows) >= datetime(year, month, 1));
    end
end


%% Reduce deals data to unique pairs
deals = data;
deals(:, [1, 4, 5]) = [];

% Extract the source and recipient columns
sourceID = deals(:, 1);
recipientID = deals(:, 2);

% Extract the date columns
dates = table2array(deals(:, 3:end));

% Create a new table with unique combinations of source and recipient
uniquePairs = unique([sourceID, recipientID], 'rows');
numPairs = size(uniquePairs, 1);
newTable = table('Size', [numPairs, size(dates, 2)], ...
                 'VariableTypes', repmat({'double'}, 1, size(dates, 2)), ...
                 'VariableNames', deals.Properties.VariableNames(3:end));

% Sum across the date columns for each unique pair
for i = 1:numPairs
    pairIndex = ismember([sourceID, recipientID], uniquePairs(i, :), 'rows');
    newTable(i, :) = array2table(sum(dates(pairIndex, :), 1), 'VariableNames', deals.Properties.VariableNames(3:end));
end

deals = [uniquePairs, newTable];

%% Calculate shortest path

years = 2000:2025;

% Initialize the result matrix
resultMatrices = cell(numel(years), 12);

condition = deals.source_country_ID ~= 17 & deals.recipient_country_ID ~=17;
short_deals_EA = deals(condition, :);

condition = deals.source_country_ID ~= 69 & deals.recipient_country_ID ~=69;
short_deals_USA = deals(condition, :);

condition = deals.source_country_ID ~= 14 & deals.recipient_country_ID ~=14;
short_deals_CHN = deals(condition, :);



% Loop through each year
for yearID = 1:numel(years)
    year = years(yearID);
    
    % Loop through each month
    for month = 1:12
        % 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);
        
        % Subset the data removing EA
        condition = short_deals_EA.(column_name) ~= 0;
        subsetData_EA = short_deals_EA(condition, :);
        source = subsetData_EA.source_country_ID;
        recipient = subsetData_EA.recipient_country_ID;
        G2 = digraph(source, recipient);
        % Subset the data removing USA
        condition = short_deals_USA.(column_name) ~= 0;
        subsetData_USA = short_deals_USA(condition, :);
        source = subsetData_USA.source_country_ID;
        recipient = subsetData_USA.recipient_country_ID;
        G3 = digraph(source, recipient);
        % Subset the data removing CHN
        condition = short_deals_CHN.(column_name) ~= 0;
        subsetData_CHN = short_deals_CHN(condition, :);
        source = subsetData_CHN.source_country_ID;
        recipient = subsetData_CHN.recipient_country_ID;
        G4 = digraph(source, recipient);
        
        % Define target node
        target = target_country;
                
        % Initialize the result matrix for the current year and month
        resultMatrix = zeros(max(data.source_country_ID), 13);
        
                 
        % Loop through each country in the dataset
        for i = 1:max(data.source_country_ID)
                % Calculate the shortest path to the target node
                try
                    [P, d] = shortestpath(G, target, i);
                    if isinf(d)
                        d = NaN;
                    end
                catch
                    d = NaN;
                end
                
                % Shortest path without EA
                try
                    [P,d2] = shortestpath(G2, target, i);
                    if isinf(d2)
                        d2 = NaN;
                    end
                catch
                    d2 = NaN;
                end

                % Shortest path without USA
                try
                    [P,d3] = shortestpath(G3, target, i);
                    if isinf(d3)
                        d3 = NaN;
                    end
                catch
                    d3 = NaN;
                end

                % Shortest path without CHN
                try
                    [P,d4] = shortestpath(G4, target, i);
                    if isinf(d4)
                        d4 = NaN;
                    end
                catch
                    d4 = NaN;
                end
    
    
    
               % Calculate intermediation 
                try
                    all_paths = allpaths(G, target, i,'MaxPathLength',5);
                catch
                    all_paths = {};
                end
                
                if ~isempty(all_paths)
                    lengths = cellfun(@length, all_paths);
                    shortest_indices = find(lengths == min(lengths));
                    num_paths = numel(shortest_indices);
                    
                    % Initialize counts for each country
                    EA_intermediate = 0; 
                    CHE_intermediate = 0; 
                    USA_intermediate = 0; 
                    CHN_intermediate = 0; 
                    UK_intermediate = 0; 
                    JPN_intermediate = 0; 
                
                    % Iterate over each shortest path index
                    for idx = 1:length(shortest_indices)
                        shortest_path = all_paths{shortest_indices(idx)};
                        
                        % Count occurrences for each desired value in the path
                        EA_intermediate = EA_intermediate + sum(shortest_path == 17);
                        CHE_intermediate = CHE_intermediate + sum(shortest_path == 53);
                        USA_intermediate = USA_intermediate + sum(shortest_path == 69);
                        CHN_intermediate = CHN_intermediate + sum(shortest_path == 14);
                        UK_intermediate = UK_intermediate + sum(shortest_path == 57);
                        JPN_intermediate = JPN_intermediate + sum(shortest_path == 24);
                    end
                    EA_intermediate = EA_intermediate/num_paths; 
                    CHE_intermediate = CHE_intermediate/num_paths; 
                    USA_intermediate = USA_intermediate/num_paths; 
                    CHN_intermediate = CHN_intermediate/num_paths; 
                    UK_intermediate = UK_intermediate/num_paths; 
                    JPN_intermediate = JPN_intermediate/num_paths;
    
                else
                    % Set intermediation values to NaN if no paths are found
                    EA_intermediate = NaN;
                    CHE_intermediate = NaN;
                    USA_intermediate = NaN;
                    CHN_intermediate = NaN;
                    UK_intermediate = NaN;
                    JPN_intermediate = NaN;
                end
                            
                % Store the result for the current year, month, and country
                resultMatrix(i, 1) = i;         % Country ID
                resultMatrix(i, 2) = year;      % Year
                resultMatrix(i, 3) = month;     % Month
                resultMatrix(i, 4) = d;         % Shortest path length
                resultMatrix(i, 5) = d2;        % Shortest path length without EA
                resultMatrix(i, 6) = d3;        % Shortest path length without USA
                resultMatrix(i, 7) = d4;        % Shortest path length without CHN
               
                resultMatrix(i, 8) = EA_intermediate;
                resultMatrix(i, 9) = CHE_intermediate;
                resultMatrix(i, 10) = JPN_intermediate;
                resultMatrix(i, 11) = UK_intermediate;
                resultMatrix(i, 12) = USA_intermediate;
                resultMatrix(i, 13) = CHN_intermediate;
                
            end
            
            % Store the result matrix for the current year and month
            resultMatrices{yearID, month} = resultMatrix;
    end
end

combinedResult = vertcat(resultMatrices{:});

%% printing
% Determine the column name based on the target_country value
if target_country == 17
    columnNames = {'country_ID', 'Year', 'Month', 'dist_EA', 'dist_EA_woEA','dist_EA_woUSA','dist_EA_woCHN','EA_inter_EA','CHE_inter_EA','JPN_inter_EA','UK_inter_EA','USA_inter_EA','CHN_inter_EA'};
elseif target_country == 69
    columnNames = {'country_ID', 'Year', 'Month', 'dist_USA', 'dist_USA_woEA', 'dist_USA_woUSA','dist_USA_woCHN','EA_inter_USA','CHE_inter_USA','JPN_inter_USA','UK_inter_USA','USA_inter_USA','CHN_inter_USA'};
elseif target_country == 14
    columnNames = {'country_ID', 'Year', 'Month', 'dist_CHN', 'dist_CHN_woEA','dist_CHN_woUSA','dist_CHN_woCHN','EA_inter_CHN','CHE_inter_CHN','JPN_inter_CHN','UK_inter_CHN','USA_inter_CHN','CHN_inter_CHN'};
elseif target_country == 24
    columnNames = {'country_ID', 'Year', 'Month', 'dist_JPN', 'dist_JPN_woEA','EA_inter_JPN','CHE_inter_JPN','JPN_inter_JPN','UK_inter_JPN','USA_inter_JPN','CHN_inter_JPN'};
else
    error('Invalid target_country value');
end

tbl = array2table(combinedResult, "VariableNames",columnNames);
%filename = sprintf('centrality_%s_%s.xlsx', bilateral, target_country_str);
filename = sprintf('centrality_%s_%s_cap.xlsx', bilateral, target_country_str);
saveFilePath = fullfile(parentFolder, 'Data', 'Interim', filename);
% Delete existing file if it exists
if isfile(saveFilePath)
    delete(saveFilePath);
end
writetable(tbl, saveFilePath, 'Sheet', 1);
