import csv
import os
import tempfile
import shutil

class DataBaseCsv:
    def __init__(self, filename: str):
        self.filename = filename

    def store_data(self, data: dict):
        new_fields = list(data.keys())

        # If file does not exist or is empty → create new file with header
        if not os.path.exists(self.filename) or os.path.getsize(self.filename) == 0:
            with open(self.filename, mode='w', newline='') as csv_file:
                writer = csv.DictWriter(csv_file, fieldnames=new_fields)
                writer.writeheader()
                writer.writerow(data)
            return

        # If file exists → read existing header and data
        with open(self.filename, mode='r', newline='') as csv_file:
            reader = csv.DictReader(csv_file)
            existing_fields = reader.fieldnames
            existing_data = list(reader)

        # Merge old and new fields (keep original order, add new ones)
        all_fields = existing_fields.copy()
        for field in new_fields:
            if field not in all_fields:
                all_fields.append(field)

        # Write to a temporary file with updated header
        with tempfile.NamedTemporaryFile(mode='w', delete=False, newline='', encoding='utf-8') as tmp_file:
            writer = csv.DictWriter(tmp_file, fieldnames=all_fields)
            writer.writeheader()

            # Write old rows with updated field list
            for row in existing_data:
                writer.writerow({field: row.get(field, '') for field in all_fields})

            # Write new data row
            writer.writerow({field: data.get(field, '') for field in all_fields})

        # Replace original file with updated temporary file
        shutil.move(tmp_file.name, self.filename)
