# agency/utils.py - Utilidades para el dashboard
from django.db.models import Count, Avg, Q, F
from django.utils.timezone import now, timedelta
from .models import Property
from category.models import category
from location.models import Location

class DashboardAnalytics:
    """Clase para manejar análisis avanzados del dashboard"""
    
    @staticmethod
    def get_market_trends():
        """Obtiene tendencias del mercado"""
        last_30_days = now() - timedelta(days=30)
        last_60_days = now() - timedelta(days=60)
        
        # Propiedades agregadas en los últimos 30 días vs 30 días anteriores
        current_month = Property.objects.filter(
            created_date__gte=last_30_days
        ).count()
        
        previous_month = Property.objects.filter(
            created_date__gte=last_60_days,
            created_date__lt=last_30_days
        ).count()
        
        # Calcular tendencia
        if previous_month > 0:
            trend_percentage = ((current_month - previous_month) / previous_month) * 100
        else:
            trend_percentage = 100 if current_month > 0 else 0
            
        return {
            'current_month': current_month,
            'previous_month': previous_month,
            'trend_percentage': round(trend_percentage, 1),
            'is_positive': trend_percentage >= 0
        }
    
    @staticmethod
    def get_price_analysis():
        """Análisis detallado de precios"""
        # Precios por categoría
        category_prices = category.objects.annotate(
            avg_price=Avg('property__price'),
            min_price=models.Min('property__price'),
            max_price=models.Max('property__price'),
            property_count=Count('property')
        ).filter(property_count__gt=0)
        
        # Precios por ubicación
        location_prices = Location.objects.annotate(
            avg_price=Avg('property__price'),
            min_price=models.Min('property__price'),
            max_price=models.Max('property__price'),
            property_count=Count('property')
        ).filter(property_count__gt=0)
        
        return {
            'category_prices': category_prices,
            'location_prices': location_prices
        }
    
    @staticmethod
    def get_inventory_status():
        """Estado del inventario"""
        total = Property.objects.count()
        available = Property.objects.filter(is_available=True).count()
        featured = Property.objects.filter(is_featured=True).count()
        verified = Property.objects.filter(is_verified=True).count()
        
        # Propiedades que necesitan atención
        needs_attention = Property.objects.filter(
            Q(main_image__isnull=True) |  # Sin imagen principal
            Q(images__isnull=True) |      # Sin imágenes en galería
            Q(is_verified=False) |        # No verificadas
            Q(description='')             # Sin descripción
        ).distinct().count()
        
        return {
            'total': total,
            'available': available,
            'featured': featured,
            'verified': verified,
            'needs_attention': needs_attention,
            'availability_rate': round((available / total * 100), 1) if total > 0 else 0
        }
    
    @staticmethod
    def get_popular_features():
        """Características más populares con análisis"""
        features_analysis = {}
        
        for feature_code, feature_name in Property.FEATURES:
            count = Property.objects.filter(features__contains=[feature_code]).count()
            if count > 0:
                # Precio promedio de propiedades con esta característica
                avg_price = Property.objects.filter(
                    features__contains=[feature_code]
                ).aggregate(Avg('price'))['price__avg']
                
                features_analysis[str(feature_name)] = {
                    'count': count,
                    'avg_price': avg_price,
                    'percentage': round((count / Property.objects.count() * 100), 1)
                }
        
        return features_analysis

# agency/management/commands/generate_dashboard_report.py
# Comando para generar reportes automáticos
from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import render_to_string
from agency.utils import DashboardAnalytics
import json

class Command(BaseCommand):
    help = 'Genera reporte semanal del dashboard'
    
    def handle(self, *args, **options):
        # Generar datos del reporte
        analytics = DashboardAnalytics()
        
        context = {
            'market_trends': analytics.get_market_trends(),
            'price_analysis': analytics.get_price_analysis(),
            'inventory_status': analytics.get_inventory_status(),
            'popular_features': analytics.get_popular_features(),
        }
        
        # Generar reporte HTML
        report_html = render_to_string('admin/weekly_report.html', context)
        
        # Enviar por email (opcional)
        send_mail(
            'Reporte Semanal - Tu Espacio Elite',
            'Ver reporte adjunto',
            'admin@tuespacioelite.com',
            ['gerencia@tuespacioelite.com'],
            html_message=report_html,
            fail_silently=False,
        )
        
        self.stdout.write(
            self.style.SUCCESS('Reporte generado exitosamente')
        )

# agency/admin.py - Mejoras para el admin
from django.contrib import admin
from django.urls import path
from django.shortcuts import render
from django.http import JsonResponse
from .models import Property, PropertyGallery
from .views import dashboard_stats

class PropertyAdmin(admin.ModelAdmin):
    list_display = ['property_name', 'category', 'location', 'purpose', 'price', 'is_available', 'is_featured', 'created_date']
    list_filter = ['purpose', 'category', 'location', 'is_available', 'is_featured', 'is_verified', 'created_date']
    search_fields = ['property_name', 'address', 'description']
    list_editable = ['is_available', 'is_featured']
    readonly_fields = ['created_date', 'modified_date']
    
    fieldsets = (
        ('Información Básica', {
            'fields': ('property_name', 'slug', 'description', 'purpose', 'price', 'category', 'main_image')
        }),
        ('Ubicación', {
            'fields': ('address', 'location', 'floor', 'maps_url')
        }),
        ('Características', {
            'fields': ('area', 'bedrooms', 'bathrooms', 'is_furnished')
        }),
        ('Estado', {
            'fields': ('is_available', 'is_featured', 'is_verified')
        }),
        ('Extras', {
            'fields': ('features', 'services', 'rules', 'video_url', 'virtual_tour_url', 'notes'),
            'classes': ('collapse',)
        }),
        ('Fechas', {
            'fields': ('created_date', 'modified_date'),
            'classes': ('collapse',)
        })
    )
    
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('dashboard-stats/', self.admin_site.admin_view(dashboard_stats), name='property_dashboard'),
        ]
        return custom_urls + urls

class PropertyGalleryAdmin(admin.ModelAdmin):
    list_display = ['property', 'image_thumbnail', 'is_featured', 'order']
    list_filter = ['is_featured', 'property__category']
    list_editable = ['is_featured', 'order']
    
admin.site.register(Property, PropertyAdmin)
admin.site.register(PropertyGallery, PropertyGalleryAdmin)