from django.db import models
import json

class BlacklistRecord(models.Model):
    sno = models.IntegerField()
    blacklist_no = models.CharField(max_length=100, unique=True)
    blacklist_date_bs = models.CharField(max_length=20)  # BS date as string
    blacklist_date_ad = models.DateField(null=True, blank=True)  # Converted AD date
    borrower_name = models.CharField(max_length=500)
    associated_entities = models.TextField(help_text="JSON list of associated persons/firms/companies")
    scrape_log = models.ForeignKey('ScrapeLog', on_delete=models.CASCADE, related_name='records', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def get_associated_list(self):
        try:
            return json.loads(self.associated_entities)
        except:
            return []

    def __str__(self):
        return f"{self.blacklist_no} - {self.borrower_name}"

class ScrapeLog(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=20, choices=[('Success', 'Success'), ('Failed', 'Failed')])
    file_name = models.CharField(max_length=255)
    file_url = models.URLField()
    file_path = models.FileField(upload_to='scraped_files/', null=True, blank=True)
    records_extracted = models.IntegerField(default=0)
    message = models.TextField(blank=True)

    def __str__(self):
        return f"{self.timestamp} - {self.status}"
