import os
import csv

# Define the directory where your text files are located
directory = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE'

# Define the CSV file paths
csv_file_path_internet = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE/output_internet.csv'
csv_file_path_fix = 'C:/Users/z.ahmizane/Downloads/tmp/retourFIXE/output_fix.csv'

# Mapping of codes to enterprise names
code_to_enterprise = {
    '002': 'ARAB',
    '007': 'BCM',
    '230': 'CIH',
    '040': 'BCP',
    '050': 'CFG',
    '013': 'BMCI',
    '022': 'SGMB',
    '021': 'CDM',
    '350': 'CCP',
    '310': 'TG',
    '011': 'BMCE',
    '005': 'UMB',
    '225': 'CNCA',
}

# Initialize a template for totals
totals_template = {'nombre total': 0, 'montant total': 0.0, 'nombre prelever': 0,
                   'nombre rejetes': 0, 'montant prelever': 0.0, 'montant rejetes': 0.0}

# Function to process and write data to a CSV file
def process_and_write_files(file_type, file_path):
    data_to_write = []
    totals = totals_template.copy()

    for filename in os.listdir(directory):
        if filename.startswith(file_type) and filename.endswith('R') and len(filename) > 7:
            enterprise_code = filename[1:4]
            enterprise_name = code_to_enterprise.get(enterprise_code, 'Unknown')

            with open(os.path.join(directory, filename), 'r') as file:
                lines = file.readlines()
                if lines:
                    last_line = lines[-1].strip().replace(" ", "")[2:]
                    fields = {
                        'nombre total': int(last_line[0:5]),
                        'montant total': float(int(last_line[5:25]) / 100),
                        'nombre prelever': int(last_line[25:30]),
                        'nombre rejetes': int(last_line[30:35]),
                        'montant prelever': float(int(last_line[35:55]) / 100),
                        'montant rejetes': float(int(last_line[55:75]) / 100)
                    }

                    # Update totals
                    for key in totals.keys():
                        if key in fields:
                            if 'montant' in key:
                                totals[key] += fields[key]
                    else:
                        totals[key] += fields[key]

                    fields['montant total'] = "{:.2f}".format(fields['montant total'])
                    fields['montant prelever'] = "{:.2f}".format(fields['montant prelever'])
                    fields['montant rejetes'] = "{:.2f}".format(fields['montant rejetes'])
                    fields['Enterprise Name'] = enterprise_name
                    data_to_write.append(fields)

    # Format monetary totals for output
    totals['montant total'] = "{:.2f}".format(totals['montant total'])
    totals['montant prelever'] = "{:.2f}".format(totals['montant prelever'])
    totals['montant rejetes'] = "{:.2f}".format(totals['montant rejetes'])
    totals['Enterprise Name'] = 'Total'
    data_to_write.append(totals)

    # Write the data to a CSV file
    with open(file_path, 'w', newline='') as csvfile:
        fieldnames = ['Enterprise Name', 'nombre total', 'montant total', 'nombre prelever',
                      'nombre rejetes', 'montant prelever', 'montant rejetes']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        for row in data_to_write:
           writer.writerow(row)

# Process and write files for INTERNET and FIX
process_and_write_files('I', csv_file_path_internet)
process_and_write_files('F', csv_file_path_fix)

print(f"INTERNET CSV file has been created at {csv_file_path_internet}")
print(f"FIX CSV file has been created at {csv_file_path_fix}")