import csv
from django.core.management.base import BaseCommand
from backend.core.models import Control

class Command(BaseCommand):
    help = "Import controls from CSV file (only safeguard) and store as name"

    def add_arguments(self, parser):
        parser.add_argument("csv_file", type=str, help="CSV file to import controls from")

    def handle(self, *args, **options):
        csv_file_path = options["csv_file"]

        with open(csv_file_path, mode="r", encoding="utf-8") as csv_file:
            reader = csv.DictReader(csv_file)

            for row in reader:
                safeguard_id = row["Safeguard ID"].strip()
                safeguard = row["Name"].strip()
                description = row["Description"].strip()
                Control.objects.update_or_create(
                    name=safeguard,
                    safeguard_id = safeguard_id,
                    description=description, 
                    defaults={"name": safeguard},
                )

        self.stdout.write(self.style.SUCCESS("Safeguards imported successfully!"))
