from django.core.management.base import BaseCommand
from django.db import transaction
from app.models import DashboardProject, ProjectActivity

STANDARD_ACTIVITIES = [
    ("Phase 1 - Études", "ETUDE"),
    ("Phase 2 - Fondations", "REALISATION"),
    ("Phase 3 - Soubassement", "REALISATION"),
    ("Phase 4 - Élévations (Gros Œuvre)", "REALISATION"),
    ("Phase 5 - Second Œuvre", "REALISATION"),
    ("Phase 6 - Finitions", "FINITION"),
    ("Phase 7 - Livraison", "LIVRAISON"),
    ("Phase 8 - SAV / Garantie", "SAV"),
]

class Command(BaseCommand):
    help = "Crée les 8 activités standards par projet (idempotent)."

    def add_arguments(self, parser):
        parser.add_argument('--project-id', type=int, default=None, help='Limiter au projet (ID) donné')

    @transaction.atomic
    def handle(self, *args, **options):
        project_id = options.get('project_id')
        qs = DashboardProject.objects.all()
        if project_id:
            qs = qs.filter(id=project_id)

        total_created = 0
        for project in qs:
            for title, act_type in STANDARD_ACTIVITIES:
                # Vérifier existence par titre et projet
                if not ProjectActivity.objects.filter(project=project, title=title).exists():
                    ProjectActivity.objects.create(
                        project=project,
                        title=title,
                        activity_type=act_type,
                        description=f"Activité standard: {title}",
                        billing_type='MILESTONE',
                        is_active=True,
                        created_by=project.created_by,
                    )
                    total_created += 1

        self.stdout.write(self.style.SUCCESS(f"Activités standards créées: {total_created}"))
