import os
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'companyos.settings')
django.setup()

from apps.tasks.models import Task, TaskComment
from apps.discussions.models import Discussion, Message

print("Migrating Task Comments to Discussion Messages...")

tasks = Task.objects.all()
migrated_count = 0

for task in tasks:
    comments = task.comments.all().order_by('created_at')
    if not comments.exists():
        continue
    
    # Get or create the discussion board for this task
    discussion, _ = Discussion.objects.get_or_create(
        task=task,
        defaults={'board_type': 'task'}
    )
    
    for comment in comments:
        # Check if already migrated (simple content/author/timestamp check)
        exists = Message.objects.filter(
            discussion=discussion,
            author=comment.author,
            content=comment.content,
            created_at=comment.created_at
        ).exists()
        
        if not exists:
            msg = Message.objects.create(
                discussion=discussion,
                author=comment.author,
                content=comment.content
            )
            # Manually override auto_now_add for timestamp preservation
            Message.objects.filter(pk=msg.pk).update(created_at=comment.created_at)
            migrated_count += 1

print(f"Migration complete. {migrated_count} comments moved to discussion messages.")
