from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import uuid
from django.conf import settings

User = get_user_model()

# Import enhanced models to ensure they're registered with Django
from .enhanced_models import *


class LoanScoring(models.Model):
    """
    Credit scoring system for loan applications
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='credit_scores', null=True, blank=True)
    
    # Scoring factors
    repayment_history_score = models.PositiveIntegerField(default=0)
    income_score = models.PositiveIntegerField(default=0)
    rollover_frequency_score = models.PositiveIntegerField(default=0)
    employment_stability_score = models.PositiveIntegerField(default=0)
    
    # Total score
    total_score = models.PositiveIntegerField(default=0)
    credit_limit = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    
    # Status
    is_eligible = models.BooleanField(default=True)
    risk_level = models.CharField(
        max_length=20,
        choices=[
            ('low', 'Low Risk'),
            ('medium', 'Medium Risk'),
            ('high', 'High Risk'),
        ],
        default='medium'
    )
    
    # Timestamps
    calculated_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'loan_scoring'
        ordering = ['-calculated_at']
    
    def __str__(self):
        return f"Credit Score for {self.user.get_full_name()} - {self.total_score}"
    
    def calculate_score(self):
        """Calculate total credit score based on factors"""
        self.total_score = (
            self.repayment_history_score +
            self.income_score +
            self.rollover_frequency_score +
            self.employment_stability_score
        )
        
        # Determine risk level and eligibility
        if self.total_score >= 80:
            self.risk_level = 'low'
            self.credit_limit = 500000  # 500K
        elif self.total_score >= 60:
            self.risk_level = 'medium'
            self.credit_limit = 200000  # 200K
        else:
            self.risk_level = 'high'
            self.credit_limit = 50000   # 50K
        
        self.is_eligible = self.total_score >= 40
        self.save()


class Notification(models.Model):
    """
    System notifications for users
    """
    NOTIFICATION_TYPES = [
        ('application_status', 'Application Status'),
        ('payment_reminder', 'Payment Reminder'),
        ('overdue_alert', 'Overdue Alert'),
        ('welcome', 'Welcome Message'),
        ('loan_approved', 'Loan Approved'),
        ('loan_rejected', 'Loan Rejected'),
        ('payment_received', 'Payment Received'),
        ('rollover_approved', 'Rollover Approved'),
        ('rollover_rejected', 'Rollover Rejected'),
    ]
    
    CHANNELS = [
        ('email', 'Email'),
        ('sms', 'SMS'),
        ('push', 'Push Notification'),
        ('in_app', 'In-App'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='report_notifications', null=True, blank=True)
    
    # Notification details
    notification_type = models.CharField(max_length=30, choices=NOTIFICATION_TYPES)
    title = models.CharField(max_length=200)
    message = models.TextField()
    
    # Delivery
    channel = models.CharField(max_length=20, choices=CHANNELS)
    is_sent = models.BooleanField(default=False)
    sent_at = models.DateTimeField(blank=True, null=True)
    
    # Related objects
    related_loan = models.ForeignKey('loans.Loan', on_delete=models.CASCADE, null=True, blank=True, related_name='report_notifications')
    related_application = models.ForeignKey('loans.LoanApplication', on_delete=models.CASCADE, null=True, blank=True, related_name='notifications_as_application')
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'notifications'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.notification_type} - {self.user.get_full_name()}"
    
    def mark_as_sent(self):
        self.is_sent = True
        self.sent_at = timezone.now()
        self.save()


class SystemSettings(models.Model):
    """
    System configuration settings
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # Loan settings
    default_interest_rate = models.DecimalField(max_digits=5, decimal_places=2, default=24.0)
    default_processing_fee = models.DecimalField(max_digits=5, decimal_places=2, default=5.0)
    default_late_penalty = models.DecimalField(max_digits=5, decimal_places=2, default=5.0)
    
    # Rollover settings
    rollover_fee_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=10.0)
    max_rollover_days = models.PositiveIntegerField(default=30)
    max_rollover_count = models.PositiveIntegerField(default=3)
    
    # Auto-approval settings
    auto_approval_enabled = models.BooleanField(default=True)
    auto_approval_min_score = models.PositiveIntegerField(default=60)
    auto_approval_max_amount = models.DecimalField(max_digits=12, decimal_places=2, default=50000)
    
    # Notification settings
    email_notifications_enabled = models.BooleanField(default=True)
    sms_notifications_enabled = models.BooleanField(default=True)
    
    # M-Pesa settings
    mpesa_business_shortcode = models.CharField(max_length=10, blank=True, null=True)
    mpesa_passkey = models.CharField(max_length=100, blank=True, null=True)
    mpesa_environment = models.CharField(
        max_length=20,
        choices=[
            ('sandbox', 'Sandbox'),
            ('production', 'Production'),
        ],
        default='sandbox'
    )
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'system_settings'
        verbose_name = 'System Setting'
        verbose_name_plural = 'System Settings'
    
    def __str__(self):
        return "System Settings"
    
    @classmethod
    def get_settings(cls):
        """Get or create system settings"""
        settings, created = cls.objects.get_or_create()
        return settings


class ReportTemplate(models.Model):
    """
    Report templates for generating various reports
    """
    REPORT_TYPES = [
        ('borrower_report', 'Borrower Report'),
        ('loan_report', 'Loan Report'),
        ('collection_report', 'Collection Report'),
        ('default_report', 'Default Report'),
        ('rollover_report', 'Rollover Report'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    report_type = models.CharField(max_length=30, choices=REPORT_TYPES)
    description = models.TextField(blank=True, null=True)
    
    # Template configuration
    template_file = models.FileField(upload_to='report_templates/', blank=True, null=True)
    is_active = models.BooleanField(default=True)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'report_templates'
        ordering = ['name']
    
    def __str__(self):
        return f"{self.name} ({self.get_report_type_display()})"


class GeneratedReport(models.Model):
    """
    Generated reports history
    """
    REPORT_FORMATS = [
        ('pdf', 'PDF'),
        ('excel', 'Excel'),
        ('csv', 'CSV'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    report_type = models.CharField(max_length=50)
    report_name = models.CharField(max_length=200)
    
    # Report details
    format = models.CharField(max_length=10, choices=REPORT_FORMATS)
    file_path = models.FileField(upload_to='generated_reports/')
    file_size = models.PositiveIntegerField(blank=True, null=True)
    
    # Generation details
    generated_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    parameters = models.JSONField(blank=True, null=True)  # Report filters/parameters
    
    # Timestamps
    generated_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        db_table = 'generated_reports'
        ordering = ['-generated_at']
    
    def __str__(self):
        return f"{self.report_name} - {self.generated_at.strftime('%Y-%m-%d %H:%M')}"
