from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from documents.models import Document, DocumentCategory
from faker import Faker
import random
from datetime import datetime, timedelta

User = get_user_model()

# Import Penduduk model - try references first, then letters as fallback
try:
    from references.models import Penduduk
    print("Documents dummy: Using references.models.Penduduk")
except ImportError:
    try:
        from letters.models import Penduduk
        print("Documents dummy: Using letters.models.Penduduk")
    except ImportError:
        Penduduk = None
        print("Documents dummy: No Penduduk model found")


class Command(BaseCommand):
    help = 'Create dummy data for documents'

    def add_arguments(self, parser):
        parser.add_argument(
            '--count',
            type=int,
            default=50,
            help='Number of documents to create (default: 50)'
        )

    def handle(self, *args, **options):
        fake = Faker('id_ID')
        count = options['count']
        
        # Create document categories if they don't exist
        categories_data = [
            {'name': 'Surat Keterangan', 'description': 'Surat keterangan dari desa', 'color': '#007bff', 'is_active': True},
            {'name': 'Surat Pengantar', 'description': 'Surat pengantar untuk keperluan administrasi', 'color': '#28a745', 'is_active': True},
            {'name': 'Surat Izin', 'description': 'Surat izin untuk berbagai keperluan', 'color': '#ffc107', 'is_active': True},
            {'name': 'Surat Rekomendasi', 'description': 'Surat rekomendasi untuk berbagai keperluan', 'color': '#17a2b8', 'is_active': True},
            {'name': 'Surat Kepemilikan', 'description': 'Surat kepemilikan tanah atau aset', 'color': '#6f42c1', 'is_active': True},
            {'name': 'Surat Lainnya', 'description': 'Surat-surat lainnya', 'color': '#6c757d', 'is_active': True},
        ]
        
        for cat_data in categories_data:
            category, created = DocumentCategory.objects.get_or_create(
                name=cat_data['name'],
                defaults=cat_data
            )
            if created:
                self.stdout.write(f'Created category: {category.name}')
        
        # Get all categories
        doc_categories = DocumentCategory.objects.all()
        
        # Get users
        users = User.objects.all()
        if not users.exists():
            self.stdout.write(self.style.WARNING('No users found. Please create users first.'))
            return
        
        # Get penduduk if available
        penduduk_list = []
        if Penduduk:
            penduduk_list = list(Penduduk.objects.all())
        
        # Document categories and statuses
        doc_category_choices = [choice[0] for choice in Document.CATEGORY_CHOICES]
        status_choices = [choice[0] for choice in Document.STATUS_CHOICES]
        priority_choices = [choice[0] for choice in Document.PRIORITY_CHOICES]
        
        # Create documents
        created_count = 0
        for i in range(count):
            # Generate document data
            title = fake.sentence(nb_words=4).rstrip('.')
            year = fake.year()
            month = fake.month()
            day = fake.day_of_month()
            document_number = f"{random.choice(['SW', 'SM', 'SK', 'SI'])}/{year}{str(month).zfill(2)}{str(day).zfill(2)}/{str(fake.random_int(min=1, max=999)).zfill(3)}"
            
            # Random dates
            created_date = fake.date_between(start_date='-1y', end_date='today')
            document_date = fake.date_between(start_date=created_date, end_date='today')
            
            # Create document
            document = Document.objects.create(
                title=title,
                document_number=document_number,
                category=random.choice(doc_category_choices),
                document_category=random.choice(doc_categories) if doc_categories else None,
                summary=fake.paragraph(nb_sentences=2),
                status=random.choice(status_choices),
                priority=random.choice(priority_choices),
                applicant=random.choice(penduduk_list) if penduduk_list else None,
                recipient=fake.name() if random.choice([True, False]) else '',
                sender=fake.name() if random.choice([True, False]) else '',
                document_date=document_date,
                notes=fake.paragraph(nb_sentences=1) if random.choice([True, False]) else '',
                tags=', '.join(fake.words(nb=random.randint(1, 3))) if random.choice([True, False]) else '',
                created_by=random.choice(users),
                created_at=datetime.combine(created_date, fake.time_object()),
            )
            
            created_count += 1
            
            if created_count % 10 == 0:
                self.stdout.write(f'Created {created_count} documents...')
        
        self.stdout.write(
            self.style.SUCCESS(f'Successfully created {created_count} documents')
        )
        
        # Show statistics
        total_docs = Document.objects.count()
        self.stdout.write(f'Total documents in database: {total_docs}')
        
        # Show category statistics
        self.stdout.write('\nCategory statistics:')
        for category in DocumentCategory.objects.all():
            count = Document.objects.filter(document_category=category).count()
            self.stdout.write(f'  {category.name}: {count} documents')
        
        # Show status statistics
        self.stdout.write('\nStatus statistics:')
        for status, label in Document.STATUS_CHOICES:
            count = Document.objects.filter(status=status).count()
            self.stdout.write(f'  {label}: {count} documents')
