% 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 (60).\n', target_country_str);
        end
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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');

if strcmpi(bilateral, 'yes')
    data = data(~strcmp(data.initiative, "SAARC") & ~strcmp(data.initiative, "BRICS_CRA") & ~strcmp(data.initiative, "CMIM")& ~strcmp(data.initiative, "ASEAN")& ~strcmp(data.initiative, "Miyazawa"), :);
end

% 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);

%%
% 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

%%
%%%%%%%%%%%%%%%%%%
% Construct the full path to the ceilings file
ceilingsFilePath = fullfile(parentFolder, 'Data', 'Interim', 'MATLAB_ceilings.csv');
% Import the ceilings data
ceilings_all = readtable(ceilingsFilePath);

ceilings = table2array(ceilings_all);               %transform to array
N2 = N^2;
                         
indices = find(ceilings(:,3) == 0);                 %replace zero ceiling 
ceilings(indices,3) = 0.01;
ceilings(:, [1, 2]) = [];                           %remove irrelevant columns
ceilings = reshape(ceilings,[N2,T]);                %reshape to matrix

numbers = (1:N)';
Pairs = [repmat(numbers, N, 1), kron(numbers, ones(N,1))];
ceilings_new = [Pairs(:, [2, 1]), ceilings];


deals = data;
deals(:, [1, 4, 5]) = [];


%--------------------------------------------------------------------------
% ceilings attempt
% 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
%%
new = [uniquePairs, newTable];
new2 = table2array(new);
for i = 3:size(new2, 2)
    % Get source_ID, recipient_ID, and the values of the current column
    sourceID = new2(:, 1);
    recipientID = new2(:, 2);
    values = new2(:, i);
    
    % Find rows where the current column has non-zero values
    nonzeroRows = (values ~= 0);
    
    % Look up source_ID and recipient_ID in 'ceilings' for non-zero values
    for j = find(nonzeroRows)'
        source = sourceID(j);
        recipient = recipientID(j);
        % Find the corresponding row in 'ceilings'
        
            matching_row = find(ceilings_new(:, 1) == source & ceilings_new(:, 2) == recipient);
            % Replace the value in 'new' with the value from 'ceilings'
            new2(j, i) = ceilings_new(matching_row, i);
    end
end

ceilings_network = array2table(new2);

%% renaming columns
% Define the years and months
years = 2000:2025;
months = 1:12;

% Generate column names
column_names = cell(1, numel(years) * numel(months) + 2);

% Set column names for source and recipient
column_names{1} = 'source_country_ID';
column_names{2} = 'recipient_country_ID';

% Generate the column names for Active_yyyy_mm
idx = 3;
for yyyy = years
    for mm = months
        % Create the column name using the specified format
        column_names{idx} = sprintf('Active_%d_%02d', yyyy, mm);
        idx = idx + 1;
    end
end

ceilings_network.Properties.VariableNames = column_names;

%% calculate shortest paths
%%%%%%%%%%%%%%
years = 2000:2025;

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

% 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 = ceilings_network.(column_name) ~= 0;
        subsetData = ceilings_network(condition, :);
        
        % Initialize directed, unweighted shortest path calculation
        source = subsetData.source_country_ID;
        recipient = subsetData.recipient_country_ID;
        ceiling = subsetData.(column_name);
        
        %adaptation
        indices = (ceiling == -1);
        ceiling(indices) = 0;
        indices = (ceiling == 0.01);
        ceiling(indices) = 0;
        
        G = digraph(source, recipient);
        G2 = digraph(source, recipient,ceiling);
        % Define target node (node 67)
        target = target_country; %69 = USA, 17 = EA, 14 = China, 24 = Japan
        
        incloseness = centrality(G, 'incloseness'); %measures centrality within network (meaure of how many nodes can be reached from node i)
        betweenness = centrality(G, 'betweenness'); %measures number of instances under which node facilitates shortest path between two other nodes, bec multiple shortest paths exists this can eceed the number of countries
        TG = transclosure(digraph(recipient, source)); %inverted order bec want reachable nodes = countries from which to borrow
        
        % Initialize the result matrix for the current year and month
        resultMatrix = zeros(max(data.source_country_ID), 3); % Assuming the highest node number is used
        
               
        % Loop through each country in the dataset
        for i = 1:max(data.source_country_ID)
            % Calculate the shortest path to the target node (67)
            [P, d] = shortestpath(G, target, i);
            [~, d2] = shortestpath(G2, target, i);
            if isinf(d)
                d = NaN;
                d2 = NaN;
            end
            
            reachable = numel(successors(TG,i))-1;
            if reachable == -1
                reachable = 0;
            end
            
            EA_intermediate = sum(P == 17);
            UK_intermediate = sum(P == 57);
            CHE_intermediate = sum(P == 53);
            JPN_intermediate = sum(P == 24);
            USA_intermediate = sum(P == 69);
            CHN_intermediate = sum(P == 14);
                        
            % 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 ceiling
            resultMatrix(i, 6) = reachable; % Number of rechable countries(including oneself), to get country IDs of rechable countries use predecessors
            resultMatrix(i, 7) = EA_intermediate;
            resultMatrix(i, 8) = UK_intermediate;
            resultMatrix(i, 9) = CHE_intermediate;
            resultMatrix(i, 10) = JPN_intermediate;
            resultMatrix(i, 11) = USA_intermediate;
            resultMatrix(i, 12) = CHN_intermediate;
            
            
        end
        resultMatrix = horzcat(resultMatrix, incloseness);
        resultMatrix = horzcat(resultMatrix, betweenness);
        
        % Store the result matrix for the current year and month
        resultMatrices{yearID, month} = resultMatrix;
    end
end

% Combine the result matrices for all years into a single matrix
%combinedResult = vertcat(resultMatrices{:});
%columnNames = {'country_ID', 'Year','Month', 'dist_EA'};
% Combine the result matrices for all years into a single matrix
combinedResult = vertcat(resultMatrices{:});

%% output results
% Determine the column name based on the target_country value
if target_country == 17
    columnNames = {'country_ID', 'Year', 'Month', 'dist_EA', 'ceiling_EA','reachable_nodes', 'EA_inter_EA', 'UK_inter_EA','CHE_inter_EA','JPN_inter_EA','USA_inter_EA','CHN_inter_EA','incloseness','betweenness'};
elseif target_country == 69
    columnNames = {'country_ID', 'Year', 'Month', 'dist_USA', 'ceiling_USA','reachable_nodes','EA_inter_USA','UK_inter_USA','CHE_inter_USA','JPN_inter_USA','USA_inter_USA','CHN_inter_EA','incloseness','betweenness'};
elseif target_country == 14
    columnNames = {'country_ID', 'Year', 'Month', 'dist_CHN', 'ceiling_CHN','reachable_nodes','EA_inter_CHN','UK_inter_CHN','CHE_inter_CHN','JPN_inter_CHN','USA_inter_CHN','CHN_inter_EA','incloseness','betweenness'};
elseif target_country == 24
    columnNames = {'country_ID', 'Year', 'Month', 'dist_JPN', 'ceiling_JPN', 'reachable_nodes','EA_inter_JPN','UK_inter_JPN','CHE_inter_JPN','JPN_inter_JPN','USA_inter_JPN','CHN_inter_EA','incloseness','betweenness'};
else
    error('Invalid target_country value');
end

tbl = array2table(combinedResult, "VariableNames",columnNames);
%filename = sprintf('monthly_full_data_%s_%s_reduced.xlsx', bilateral, target_country_str);
filename = sprintf('monthly_full_data_%s_%s_reduced.xlsx', bilateral, target_country_str);
saveFilePath = fullfile(parentFolder, 'Data', 'Interim', filename);
writetable(tbl, saveFilePath, 'Sheet', 1);
